<commit_before>#include "Project0.hh"

//Initialization of the windows, SDL, SDL_TTF, the surface
bool InitEverything()
{
	//Load configuration from ini files
	if (!Set_Config())
	{
		cout << "\nConfiguration could not been set " << std::endl;
        return false;
	}
	P0_Logger << nl << "Configuration Set" << std::endl;

	//Set window name
	App::getInstance().setName(Window_Name);
	//SDL_WM_SetCaption( "Project 0 - 2D", NULL );

	//Initialize SDL Video
    if (! App::getInstance().initVideo(false,false,true,false) )
		//SDL_Init( SDL_INIT_EVERYTHING )
	{
		P0_Logger << nl << "Init Video Failed : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Init Video : OK " << std::endl;

	//Intialize Timer
	if (! App::getInstance().initTimer() )
	{
		P0_Logger << nl << "Init Timer Failed : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Init Timer : OK " << std::endl;

	//Initialize SDL_ttf
	if (! App::getInstance().initText())
		//if( TTF_Init() == -1 )
    {
		//P0_Logger << nl << "TTF Init Error : " << TTF::GetError() << std::endl;
		P0_Logger << nl <<  " TTF Init Error : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "TTF Init : OK " << std::endl;

	//Create the video surface aka the display
	if (App::getInstance().getWindow()->resetDisplay(SCREEN_WIDTH, SCREEN_HEIGHT) == NULL  )
	{
		P0_Logger << nl << "Create Surface Failed : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Video Surface Creation : OK " << std::endl;

	//Initialize Audio Mixer
	if (!App::getInstance().initAudio())
    {
		P0_Logger << nl << "Audio Init Error : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Audio Init : OK " << std::endl;

	//Load Fxs & Musics Sounds Files to the mixer and set there respective channels
	if (!Set_Sounds_Channels())
	{
		P0_Logger << nl << "Mixing Sound Error : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Mixing Sound : OK " << std::endl;

	//If eveything loads fine
    return true;
}

//Main
int main( int argc, char* args[] )
{
try { //global error management

	//Init the rand method using the current time in order to generate more random numbers
	srand( (unsigned)time( NULL ) );

/********INIT********/
	//Create the windows and init everything (SDL, SDL_TTF, ...)
	if( InitEverything() == false )
	{
		P0_Logger << nl << "Init Everything failed... " << std::endl;
		Delay(2000);
		//SDL_Delay(2000);
		return 1;
	}
	P0_Logger << nl << "-> Windows, SDL, SDL_TTF And VideoSurface Where Initialized Successfully <-" << std::endl;

/****Battlefield****/
	//Initialize the BackGround
	BackGround* myBackGround = new BackGround();
	P0_Logger << nl << "BackGround Init: OK " << std::endl;

	//Fill the BackGround vector with all BackGround sprite corresponding to the map file
//#ifdef _DEBUG //debug mode
//	std::vector<BattleField_Sprite*>* BackGround_Sprite_Vector = new std::vector<BattleField_Sprite*>;
//#else //rlz mode
	std::vector<BattleField_Sprite*>* BackGround_Sprite_Vector = myBackGround->BackGround_Vector(); //Vector which will contains all BackGround type and clip
//#endif
	P0_Logger << nl << "BackGround_Sprite Vector Fill: OK " << std::endl;

	//Initialize the Environment
	Environment* myEnvironment = new Environment();
	P0_Logger << nl << "Environment Init: OK " << std::endl;

	//Fill the Environment vector with all Environment sprite corresponding to the map file
#ifdef _DEBUG //debug mode
	std::vector<BattleField_Sprite*>* Environment_Sprite_Vector = new std::vector<BattleField_Sprite*>;
#else //rlz mode*/
	std::vector<BattleField_Sprite*>* Environment_Sprite_Vector = myEnvironment->Environment_Vector(); //Vector which will contains all Environment items type and clip
#endif
	P0_Logger << nl << "Environment_Sprite Vector Fill: OK " << std::endl;

/****PlayerS****/
	//Vector containing pointers to vector of pointers to monsters
	std::vector< std::vector<Character_Base*> *>* Global_Player_Vector = new std::vector< std::vector<Character_Base*> *>;

			/****NPCs****/
	//Vector of npcs
	std::vector<Character_Base*>* NPCs_Vector = new std::vector<Character_Base*>;

	//Create npc & initialized it
	NPCs* myNPC = new NPCs();
	if( myNPC->Set_Attack_Style() == false ) //intialize Character's graphic aspect
	{
        P0_Logger << nl << "Failed to set NPC Graphic " << std::endl;
    	Delay(2000);
    	return 1;
    }
    P0_Logger << nl << "NPC Creation: OK " << std::endl;

	NPCs_Vector->push_back(myNPC);

	Global_Player_Vector->push_back(NPCs_Vector);

			/****Player****/
	//Vector of players
	std::vector<Character_Base*>* Players_Vector = new std::vector<Character_Base*>;

	//Create player & initialized it
	Player* myPlayer = new Player();
	if( myPlayer->Following_Camera() == false ) //center camera
	{
        P0_Logger << nl << "Failed to center camera over Player" << std::endl;
    	Delay(2000);
    	return 1;
    }
	if( myPlayer->Set_Attack_Style() == false ) //intialize Character's graphic aspect
	{
        P0_Logger << nl << "Failed to set Player Graphic " << std::endl;
    	Delay(2000);
    	return 1;
    }
    P0_Logger << nl << "Player Creation: OK " << std::endl;

	Players_Vector->push_back(myPlayer);

	Global_Player_Vector->push_back(Players_Vector);

/****Monsters****/
	//Vector containing pointers to vector of pointers to monsters
	std::vector< std::vector<Character_Base*> *>* Global_Monster_Vector = new std::vector< std::vector<Character_Base*> *>;

	//Initialize the skeleton factory
	Monster_Factory<Monster_Skeleton>* Monster_Factory_Skeleton = new Monster_Factory<Monster_Skeleton>(INITIAL_MONSTERS, Global_Monster_Vector);  //A factory of Monster Skeletons
	P0_Logger << nl << "Skeleton Factory Init: OK " << std::endl;

	//Create all the monsters skeletons
	//std::vector<Character_Base*>* Monster_Vector_Skeleton =
	Monster_Factory_Skeleton->Create_Monsters(Global_Player_Vector, Environment_Sprite_Vector, BackGround_Sprite_Vector, Global_Monster_Vector);  //Vector which will contains all skeletons
	P0_Logger << nl << "Skeleton Vector Fill: OK " << std::endl;

	//Initialize the worm factory
	Monster_Factory<Monster_Worm>* Monster_Factory_Worm = new Monster_Factory<Monster_Worm>(INITIAL_MONSTERS, Global_Monster_Vector);  //A factory of Monster Worms
	P0_Logger << nl << "Worm Factory Init: OK " << std::endl;

	//Create all the monsters worms
	//std::vector<Character_Base*>* Monster_Vector_Worm =
	Monster_Factory_Worm->Create_Monsters(Global_Player_Vector, Environment_Sprite_Vector, BackGround_Sprite_Vector, Global_Monster_Vector); //Vector which will contains all skeletons
	P0_Logger << nl << "Worm Vector Fill: OK " << std::endl;

/*********ENGINE************/

	//Create the ingame escape menu
	Escape_Menu* myEsc_Menu = new Escape_Menu();

	//Create the victory screen
	Victory_Screen* myVictory_Screen = new Victory_Screen();

/********DEAMONS CREATION********/
	//Instanciate the daemon class
	Daemons* myDaemons = new Daemons(myPlayer, myNPC, BackGround_Sprite_Vector, Environment_Sprite_Vector, Monster_Factory_Skeleton,
									Monster_Factory_Worm, Global_Player_Vector, Global_Monster_Vector );

	//Create monster's movement daemons
	Timer<Daemons>* myMonster_Factory_Monsters_Moves_Timer = new Timer<Daemons>(); //set definition
	myMonster_Factory_Monsters_Moves_Timer->setInterval( MONSTERS_MOVEMENT_INTERVAL ); //set interval
	myMonster_Factory_Monsters_Moves_Timer->setCallback(myDaemons,&Daemons::Move_Monsters, (void*)NULL); //set callback

	//Create monster's generation daemons
	Timer<Daemons>* myMonster_Factory_Monsters_Generation_Timer = new Timer<Daemons>; //set definition
	myMonster_Factory_Monsters_Generation_Timer->setInterval( MONSTERS_GENERATION_INTERVAL ); //set interval
	myMonster_Factory_Monsters_Generation_Timer->setCallback(myDaemons,&Daemons::Generate_Monsters, (void*)NULL); //set callback

	//Create npcs's movement daemons
	Timer<Daemons>* myNPCs_Moves_Timer = new Timer<Daemons>(); //set definition
	myNPCs_Moves_Timer->setInterval( NPCS_MOVEMENT_INTERVAL ); //set interval
	myNPCs_Moves_Timer->setCallback(myDaemons,&Daemons::Move_NPCs, (void*)NULL); //set callback

	//Manage score
	Timer<Daemons>* myScore = new Timer<Daemons>; //set definition
	myScore->setInterval( 1000 / FRAMES_PER_SECOND ); //set interval
	myScore->setCallback(myDaemons,&Daemons::Score, (void*)NULL); //set callback

/********ENGINE********/
	//Create the keyboard instance that will managed input
	KeyboardInput* myKeyboardInput = new KeyboardInput(myPlayer, myNPC, BackGround_Sprite_Vector, Environment_Sprite_Vector, Monster_Factory_Skeleton,
													Monster_Factory_Worm, Global_Player_Vector, Global_Monster_Vector, myEsc_Menu,
													myVictory_Screen, myDaemons );
	//myKeyboardInput->enableKeyRepeat();  //enable key repeat

	//Engine instanciation
	Render_Engine* myRender_Engine = new Render_Engine(myPlayer, myNPC, myBackGround, myEnvironment, Monster_Factory_Skeleton,
														Monster_Factory_Worm, myEsc_Menu, myVictory_Screen, myKeyboardInput );

	//Affect the keyboard instance to the windows
    App::getInstance().getWindow()->getEventManager()->setKeyboard(myKeyboardInput);

	//Affect the game render engine to the windows
	App::getInstance().getWindow()->setEngine(myRender_Engine);

/********Start music********/
if (ENABLE_MUSIC)
	App::getInstance().getMixer()->playChannel(GlobalMusic_Chan);

/*******Score Management********/
	FiNiSH_TiME = (unsigned)time( NULL );

/********Start Daemons Process********/
	myMonster_Factory_Monsters_Moves_Timer->start(); //monsters movements
	myMonster_Factory_Monsters_Generation_Timer->start(); //monsters generation
	myNPCs_Moves_Timer->start(); //npcs movements
	myScore->start(); //Score

/********Launch the mainloop that will use the render method of the Engine and so will render the screen and will manage all events********/
	App::getInstance().getWindow()->mainLoop(FRAMES_PER_SECOND);

/********Stop Daemons Process********/
	myMonster_Factory_Monsters_Moves_Timer->stop(); //monsters movements
	myMonster_Factory_Monsters_Generation_Timer->stop(); //monsters generation
	myNPCs_Moves_Timer->stop(); //npcs movements
	myScore->stop(); //Score

/********Clean UP********/
#ifdef _DEBUG //debug mode
	delete myScore, myScore = NULL;
	delete myMonster_Factory_Monsters_Generation_Timer, myMonster_Factory_Monsters_Generation_Timer = NULL;
	delete myMonster_Factory_Monsters_Moves_Timer, myMonster_Factory_Monsters_Moves_Timer = NULL;
	delete myVictory_Screen, myVictory_Screen = NULL;
	delete myEsc_Menu, myEsc_Menu = NULL;
	delete Monster_Factory_Worm, Monster_Factory_Worm = NULL;
	delete Monster_Factory_Skeleton, Monster_Factory_Skeleton = NULL;
	delete Global_Monster_Vector, Global_Monster_Vector = NULL;
	delete myPlayer, myPlayer = NULL;
	delete myNPC, myNPC = NULL;
	delete Players_Vector, Players_Vector = NULL;
	delete Global_Player_Vector, Global_Player_Vector = NULL;
	delete myEnvironment, myEnvironment = NULL;
	delete myBackGround, myBackGround = NULL;

	delete myKeyboardInput, myKeyboardInput = NULL;

	delete myRender_Engine, myRender_Engine = NULL;
	delete myDaemons, myDaemons = NULL;
#endif

    return 0; //no error occured

} catch (std::exception e) {
    P0_Logger << nl << "Unhandled Exception occured in Main : " << e.what() << std::endl;
    P0_Logger << nl << "P0 stopped in emergency" << std::endl;
    Delay(2000);
    return 1;
}
}

<commit_msg>Project 0 2D v0.03:<commit_after>#include "Project0.hh"

//Initialization of the windows, SDL, SDL_TTF, the surface
bool InitEverything()
{
	//Load configuration from ini files
	if (!Set_Config())
	{
		cout << "\nConfiguration could not been set " << std::endl;
        return false;
	}
	P0_Logger << nl << "Configuration Set" << std::endl;

	//Set window name
	App::getInstance().setName(Window_Name);
	//SDL_WM_SetCaption( "Project 0 - 2D", NULL );

	//Initialize SDL Video
    if (! App::getInstance().initVideo(false,false,true,false) )
		//SDL_Init( SDL_INIT_EVERYTHING )
	{
		P0_Logger << nl << "Init Video Failed : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Init Video : OK " << std::endl;

	//Intialize Timer
	if (! App::getInstance().initTimer() )
	{
		P0_Logger << nl << "Init Timer Failed : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Init Timer : OK " << std::endl;

	//Initialize SDL_ttf
	if (! App::getInstance().initText())
		//if( TTF_Init() == -1 )
    {
		//P0_Logger << nl << "TTF Init Error : " << TTF::GetError() << std::endl;
		P0_Logger << nl <<  " TTF Init Error : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "TTF Init : OK " << std::endl;

	//Create the video surface aka the display
	if (App::getInstance().getWindow()->resetDisplay(SCREEN_WIDTH, SCREEN_HEIGHT) == NULL  )
	{
		P0_Logger << nl << "Create Surface Failed : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Video Surface Creation : OK " << std::endl;

	//Initialize Audio Mixer
	if (!App::getInstance().initAudio())
    {
		P0_Logger << nl << "Audio Init Error : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Audio Init : OK " << std::endl;

	//Load Fxs & Musics Sounds Files to the mixer and set there respective channels
	if (!Set_Sounds_Channels())
	{
		P0_Logger << nl << "Mixing Sound Error : " << GetError() << std::endl;
        return false;
    }
	P0_Logger << nl << "Mixing Sound : OK " << std::endl;

	//If eveything loads fine
    return true;
}

//Main
int main( int argc, char* args[] )
{
try { //global error management

	//Init the rand method using the current time in order to generate more random numbers
	srand( (unsigned)time( NULL ) );

/********INIT********/
	//Create the windows and init everything (SDL, SDL_TTF, ...)
	if( InitEverything() == false )
	{
		P0_Logger << nl << "Init Everything failed... " << std::endl;
		Delay(2000);
		//SDL_Delay(2000);
		return 1;
	}
	P0_Logger << nl << "-> Windows, SDL, SDL_TTF And VideoSurface Where Initialized Successfully <-" << std::endl;

/****Battlefield****/
	//Initialize the BackGround
	BackGround* myBackGround = new BackGround();
	P0_Logger << nl << "BackGround Init: OK " << std::endl;

	//Fill the BackGround vector with all BackGround sprite corresponding to the map file
#ifdef _DEBUG //debug mode
	std::vector<BattleField_Sprite*>* BackGround_Sprite_Vector = new std::vector<BattleField_Sprite*>;
#else //rlz mode
	std::vector<BattleField_Sprite*>* BackGround_Sprite_Vector = myBackGround->BackGround_Vector(); //Vector which will contains all BackGround type and clip
#endif
	P0_Logger << nl << "BackGround_Sprite Vector Fill: OK " << std::endl;

	//Initialize the Environment
	Environment* myEnvironment = new Environment();
	P0_Logger << nl << "Environment Init: OK " << std::endl;

	//Fill the Environment vector with all Environment sprite corresponding to the map file
#ifdef _DEBUG //debug mode
	std::vector<BattleField_Sprite*>* Environment_Sprite_Vector = new std::vector<BattleField_Sprite*>;
#else //rlz mode*/
	std::vector<BattleField_Sprite*>* Environment_Sprite_Vector = myEnvironment->Environment_Vector(); //Vector which will contains all Environment items type and clip
#endif
	P0_Logger << nl << "Environment_Sprite Vector Fill: OK " << std::endl;

/****PlayerS****/
	//Vector containing pointers to vector of pointers to monsters
	std::vector< std::vector<Character_Base*> *>* Global_Player_Vector = new std::vector< std::vector<Character_Base*> *>;

			/****NPCs****/
	//Vector of npcs
	std::vector<Character_Base*>* NPCs_Vector = new std::vector<Character_Base*>;

	//Create npc & initialized it
	NPCs* myNPC = new NPCs();
	if( myNPC->Set_Attack_Style() == false ) //intialize Character's graphic aspect
	{
        P0_Logger << nl << "Failed to set NPC Graphic " << std::endl;
    	Delay(2000);
    	return 1;
    }
    P0_Logger << nl << "NPC Creation: OK " << std::endl;

	NPCs_Vector->push_back(myNPC);

	Global_Player_Vector->push_back(NPCs_Vector);

			/****Player****/
	//Vector of players
	std::vector<Character_Base*>* Players_Vector = new std::vector<Character_Base*>;

	//Create player & initialized it
	Player* myPlayer = new Player();
	if( myPlayer->Following_Camera() == false ) //center camera
	{
        P0_Logger << nl << "Failed to center camera over Player" << std::endl;
    	Delay(2000);
    	return 1;
    }
	if( myPlayer->Set_Attack_Style() == false ) //intialize Character's graphic aspect
	{
        P0_Logger << nl << "Failed to set Player Graphic " << std::endl;
    	Delay(2000);
    	return 1;
    }
    P0_Logger << nl << "Player Creation: OK " << std::endl;

	Players_Vector->push_back(myPlayer);

	Global_Player_Vector->push_back(Players_Vector);

/****Monsters****/
	//Vector containing pointers to vector of pointers to monsters
	std::vector< std::vector<Character_Base*> *>* Global_Monster_Vector = new std::vector< std::vector<Character_Base*> *>;

	//Initialize the skeleton factory
	Monster_Factory<Monster_Skeleton>* Monster_Factory_Skeleton = new Monster_Factory<Monster_Skeleton>(INITIAL_MONSTERS, Global_Monster_Vector);  //A factory of Monster Skeletons
	P0_Logger << nl << "Skeleton Factory Init: OK " << std::endl;

	//Create all the monsters skeletons
	//std::vector<Character_Base*>* Monster_Vector_Skeleton =
	Monster_Factory_Skeleton->Create_Monsters(Global_Player_Vector, Environment_Sprite_Vector, BackGround_Sprite_Vector, Global_Monster_Vector);  //Vector which will contains all skeletons
	P0_Logger << nl << "Skeleton Vector Fill: OK " << std::endl;

	//Initialize the worm factory
	Monster_Factory<Monster_Worm>* Monster_Factory_Worm = new Monster_Factory<Monster_Worm>(INITIAL_MONSTERS, Global_Monster_Vector);  //A factory of Monster Worms
	P0_Logger << nl << "Worm Factory Init: OK " << std::endl;

	//Create all the monsters worms
	//std::vector<Character_Base*>* Monster_Vector_Worm =
	Monster_Factory_Worm->Create_Monsters(Global_Player_Vector, Environment_Sprite_Vector, BackGround_Sprite_Vector, Global_Monster_Vector); //Vector which will contains all skeletons
	P0_Logger << nl << "Worm Vector Fill: OK " << std::endl;

/*********ENGINE************/

	//Create the ingame escape menu
	Escape_Menu* myEsc_Menu = new Escape_Menu();

	//Create the victory screen
	Victory_Screen* myVictory_Screen = new Victory_Screen();

/********DEAMONS CREATION********/
	//Instanciate the daemon class
	Daemons* myDaemons = new Daemons(myPlayer, myNPC, BackGround_Sprite_Vector, Environment_Sprite_Vector, Monster_Factory_Skeleton,
									Monster_Factory_Worm, Global_Player_Vector, Global_Monster_Vector );

	//Create monster's movement daemons
	Timer<Daemons>* myMonster_Factory_Monsters_Moves_Timer = new Timer<Daemons>(); //set definition
	myMonster_Factory_Monsters_Moves_Timer->setInterval( MONSTERS_MOVEMENT_INTERVAL ); //set interval
	myMonster_Factory_Monsters_Moves_Timer->setCallback(myDaemons,&Daemons::Move_Monsters, (void*)NULL); //set callback

	//Create monster's generation daemons
	Timer<Daemons>* myMonster_Factory_Monsters_Generation_Timer = new Timer<Daemons>; //set definition
	myMonster_Factory_Monsters_Generation_Timer->setInterval( MONSTERS_GENERATION_INTERVAL ); //set interval
	myMonster_Factory_Monsters_Generation_Timer->setCallback(myDaemons,&Daemons::Generate_Monsters, (void*)NULL); //set callback

	//Create npcs's movement daemons
	Timer<Daemons>* myNPCs_Moves_Timer = new Timer<Daemons>(); //set definition
	myNPCs_Moves_Timer->setInterval( NPCS_MOVEMENT_INTERVAL ); //set interval
	myNPCs_Moves_Timer->setCallback(myDaemons,&Daemons::Move_NPCs, (void*)NULL); //set callback

	//Manage score
	Timer<Daemons>* myScore = new Timer<Daemons>; //set definition
	myScore->setInterval( 1000 / FRAMES_PER_SECOND ); //set interval
	myScore->setCallback(myDaemons,&Daemons::Score, (void*)NULL); //set callback

/********ENGINE********/
	//Create the keyboard instance that will managed input
	KeyboardInput* myKeyboardInput = new KeyboardInput(myPlayer, myNPC, BackGround_Sprite_Vector, Environment_Sprite_Vector, Monster_Factory_Skeleton,
													Monster_Factory_Worm, Global_Player_Vector, Global_Monster_Vector, myEsc_Menu,
													myVictory_Screen, myDaemons );
	//myKeyboardInput->enableKeyRepeat();  //enable key repeat

	//Engine instanciation
	Render_Engine* myRender_Engine = new Render_Engine(myPlayer, myNPC, myBackGround, myEnvironment, Monster_Factory_Skeleton,
														Monster_Factory_Worm, myEsc_Menu, myVictory_Screen, myKeyboardInput );

	//Affect the keyboard instance to the windows
    App::getInstance().getWindow()->getEventManager()->setKeyboard(myKeyboardInput);

	//Affect the game render engine to the windows
	App::getInstance().getWindow()->setEngine(myRender_Engine);

/********Start music********/
if (ENABLE_MUSIC)
	App::getInstance().getMixer()->playChannel(GlobalMusic_Chan);

/*******Score Management********/
	FiNiSH_TiME = (unsigned)time( NULL );

/********Start Daemons Process********/
	myMonster_Factory_Monsters_Moves_Timer->start(); //monsters movements
	myMonster_Factory_Monsters_Generation_Timer->start(); //monsters generation
	myNPCs_Moves_Timer->start(); //npcs movements
	myScore->start(); //Score

/********Launch the mainloop that will use the render method of the Engine and so will render the screen and will manage all events********/
	App::getInstance().getWindow()->mainLoop(FRAMES_PER_SECOND);

/********Stop Daemons Process********/
	myMonster_Factory_Monsters_Moves_Timer->stop(); //monsters movements
	myMonster_Factory_Monsters_Generation_Timer->stop(); //monsters generation
	myNPCs_Moves_Timer->stop(); //npcs movements
	myScore->stop(); //Score

/********Clean UP********/
#ifdef _DEBUG //debug mode
	delete myScore, myScore = NULL;
	delete myMonster_Factory_Monsters_Generation_Timer, myMonster_Factory_Monsters_Generation_Timer = NULL;
	delete myMonster_Factory_Monsters_Moves_Timer, myMonster_Factory_Monsters_Moves_Timer = NULL;
	delete myVictory_Screen, myVictory_Screen = NULL;
	delete myEsc_Menu, myEsc_Menu = NULL;
	delete Monster_Factory_Worm, Monster_Factory_Worm = NULL;
	delete Monster_Factory_Skeleton, Monster_Factory_Skeleton = NULL;
	delete Global_Monster_Vector, Global_Monster_Vector = NULL;
	delete myPlayer, myPlayer = NULL;
	delete myNPC, myNPC = NULL;
	delete Players_Vector, Players_Vector = NULL;
	delete Global_Player_Vector, Global_Player_Vector = NULL;
	delete myEnvironment, myEnvironment = NULL;
	delete myBackGround, myBackGround = NULL;

	delete myKeyboardInput, myKeyboardInput = NULL;

	delete myRender_Engine, myRender_Engine = NULL;
	delete myDaemons, myDaemons = NULL;
#endif

    return 0; //no error occured

} catch (std::exception e) {
    P0_Logger << nl << "Unhandled Exception occured in Main : " << e.what() << std::endl;
    P0_Logger << nl << "P0 stopped in emergency" << std::endl;
    Delay(2000);
    return 1;
}
}

<|endoftext|>


<commit_before>#ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP

#include <boost/atomic.hpp>

// boost::intrusive_ptr but safe/atomic

template<typename T>
struct IntrusivePtr {
	boost::atomic<T*> ptr;

	IntrusivePtr(T* _p = NULL) : ptr(NULL) {
		if(_p) {
			intrusive_ptr_add_ref(_p);
			ptr = _p;
		}
	}

	IntrusivePtr(const IntrusivePtr& other) {
		T* p = other.ptr.load();
		swap(IntrusivePtr(p));
	}

	~IntrusivePtr() {
		T* _p = ptr.exchange(NULL);
		if(_p)
			intrusive_ptr_release(_p);
	}

	IntrusivePtr& operator=(const IntrusivePtr& other) {
		T* p = other.ptr.load();
		swap(IntrusivePtr(p));
		return *this;
	}

	T& operator*() const { return *ptr; }
	T* operator->() const { return ptr; }
	operator bool() const { return ptr; }

	void swap(IntrusivePtr&& other) {
		T* old = ptr.exchange(other.ptr);
		other.ptr = old;
	}

	void reset(T* _p = NULL) {
		swap(IntrusivePtr(_p));
	}
};

#endif // INTRUSIVEPTR_HPP
<commit_msg>very stupid fix<commit_after>#ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP

#include <boost/atomic.hpp>

// boost::intrusive_ptr but safe/atomic

template<typename T>
struct IntrusivePtr {
	boost::atomic<T*> ptr;

	IntrusivePtr(T* _p = NULL) : ptr(NULL) {
		if(_p) {
			intrusive_ptr_add_ref(_p);
			ptr = _p;
		}
	}

	IntrusivePtr(const IntrusivePtr& other) : ptr(NULL) {
		T* p = other.ptr.load();
		swap(IntrusivePtr(p));
	}

	~IntrusivePtr() {
		T* _p = ptr.exchange(NULL);
		if(_p)
			intrusive_ptr_release(_p);
	}

	IntrusivePtr& operator=(const IntrusivePtr& other) {
		T* p = other.ptr.load();
		swap(IntrusivePtr(p));
		return *this;
	}

	T& operator*() const { return *ptr; }
	T* operator->() const { return ptr; }
	operator bool() const { return ptr; }

	void swap(IntrusivePtr&& other) {
		T* old = ptr.exchange(other.ptr);
		other.ptr = old;
	}

	void reset(T* _p = NULL) {
		swap(IntrusivePtr(_p));
	}
};

#endif // INTRUSIVEPTR_HPP
<|endoftext|>


<commit_before>#ifndef INCLUDE_AL_CSVREADER_HPP
#define INCLUDE_AL_CSVREADER_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012. The Regents of the University of California.
	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 University of California 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.

	File description:
	CSV File reader

	File author(s):
	Andres Cabrera mantaraya36@gmail.com 2017
*/

#include <vector>
#include <string>
#include <memory>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cstring>

/**
 * @brief The CSVReader class reads simple CSV files
 *
 * To use, first create a CSVReader object and call addType() to add the type of a
 * column. Then call readFile().
 *
 * Once the file is in memory it can be read as columns of floats using
 * getColumn(). Or the whole CSV data can be copied to memory by defining
 * a struct that will hold the values from each row from the csv file and calling
 * copyToStruct() to create a vector with the data from the CSV file.
 *
 * This reader is currently very naive (but efficient) and might choke with
 * complex or malformed CSV files.
 *
 * \code
typedef struct {
	char s[32];
	double val1, val2, val3;
	bool b;
} RowTypes;

int main(int argc, char *argv[]) {

	CSVReader reader;
	reader.addType(CSVReader::STRING);
	reader.addType(CSVReader::REAL);
	reader.addType(CSVReader::REAL);
	reader.addType(CSVReader::REAL);
	reader.addType(CSVReader::BOOLEAN);
	reader.readFile("examples/csv/I13893-gm-21DIV-0001.csv");

	std::vector<RowTypes> rows = reader.copyToStruct<RowTypes>();
	for(auto row: rows) {
		std::cout << std::string(row.s) << " : "
		          << row.val1 << "   "
		          << row.val2 << "   "
		          << row.val3 << "   "
		          << (row.b ? "+" : "-")
		          << std::endl;
	}

	std::vector<double> column1 = reader.getColumn(1);
	for(auto value: column1) {
		std::cout << value << std::endl;
	}
	std::cout << " Num rows:" << rows.size() << std::endl;
	return 0;
	\endcode
 */
class CSVReader {
public:
	typedef enum {
		STRING,
		REAL,
		INTEGER,
		BOOLEAN,
		NONE
	} DataType;

	CSVReader() {
		// TODO We could automatically add types by trying to parse the file
	}

	~CSVReader();

	/**
	 * @brief readFile reads the CSV file into internal memory
	 * @param fileName the csv file name
	 * \returns whether the file was successfully read.
	 */
	bool readFile(std::string fileName);

	/**
	 * @brief Set the delimiter used by readFile for parsing values
	 */
	CSVReader& delim(char v){ mDelim=v; return *this; }

	/**
	 * @brief addType
	 * @param type
	 */
	void addType(DataType type) {
		mDataTypes.push_back(type);
	}

	/**
	 * @brief Returns all columns from the csv file
	 * @param index column index
	 * @return vector with the data
	 */
	template<class DataStruct>
	std::vector<DataStruct> copyToStruct() {
		std::vector<DataStruct> output;
		if (sizeof(DataStruct) < calculateRowLength()) {
			return output;
		}
		for (auto row: mData) {
			DataStruct newValues;
			memcpy(&newValues, row, sizeof(newValues));
			output.push_back(newValues);
		}

		return output;
	}

	/**
	 * @brief Returns a column from the csv file
	 * @param index column index
	 * @return vector with the data
	 */
	std::vector<double> getColumn(int index);

private:

	size_t calculateRowLength();

	const size_t maxStringSize = 32;

	std::vector<std::string> mColumnNames;
	std::vector<DataType> mDataTypes;
	std::vector<char *> mData;
	char mDelim = ',';
};

#endif // INCLUDE_AL_CSVREADER_HPP
<commit_msg>CSVReader: add description of what CSV actually is<commit_after>#ifndef INCLUDE_AL_CSVREADER_HPP
#define INCLUDE_AL_CSVREADER_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012. The Regents of the University of California.
	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 University of California 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.

	File description:
	CSV File reader

	File author(s):
	Andres Cabrera mantaraya36@gmail.com 2017
*/

#include <vector>
#include <string>
#include <memory>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cstring>

/**
 * @brief The CSVReader class reads simple CSV files
 *
 * CSV is a delimited data format that has fields/columns separated by the comma
 * character and records/rows terminated by newlines. "CSV" formats vary greatly
 * in choice of separator character. In particular, in locales where the comma
 * is used as a decimal separator, semicolon, TAB, or other characters are used
 * instead. [Reference: https://en.wikipedia.org/wiki/Comma-separated_values].
 *
 * To use, first create a CSVReader object and call addType() to add the type of a
 * column. Then call readFile().
 *
 * Once the file is in memory it can be read as columns of floats using
 * getColumn(). Or the whole CSV data can be copied to memory by defining
 * a struct that will hold the values from each row from the csv file and calling
 * copyToStruct() to create a vector with the data from the CSV file.
 *
 * This reader is currently very naive (but efficient) and might choke with
 * complex or malformed CSV files.
 *
 * \code
typedef struct {
	char s[32];
	double val1, val2, val3;
	bool b;
} RowTypes;

int main(int argc, char *argv[]) {

	CSVReader reader;
	reader.addType(CSVReader::STRING);
	reader.addType(CSVReader::REAL);
	reader.addType(CSVReader::REAL);
	reader.addType(CSVReader::REAL);
	reader.addType(CSVReader::BOOLEAN);
	reader.readFile("examples/csv/I13893-gm-21DIV-0001.csv");

	std::vector<RowTypes> rows = reader.copyToStruct<RowTypes>();
	for(auto row: rows) {
		std::cout << std::string(row.s) << " : "
		          << row.val1 << "   "
		          << row.val2 << "   "
		          << row.val3 << "   "
		          << (row.b ? "+" : "-")
		          << std::endl;
	}

	std::vector<double> column1 = reader.getColumn(1);
	for(auto value: column1) {
		std::cout << value << std::endl;
	}
	std::cout << " Num rows:" << rows.size() << std::endl;
	return 0;
	\endcode
 */
class CSVReader {
public:
	typedef enum {
		STRING,
		REAL,
		INTEGER,
		BOOLEAN,
		NONE
	} DataType;

	CSVReader() {
		// TODO We could automatically add types by trying to parse the file
	}

	~CSVReader();

	/**
	 * @brief readFile reads the CSV file into internal memory
	 * @param fileName the csv file name
	 * \returns whether the file was successfully read.
	 */
	bool readFile(std::string fileName);

	/**
	 * @brief Set the delimiter used by readFile for parsing values
	 */
	CSVReader& delim(char v){ mDelim=v; return *this; }

	/**
	 * @brief addType
	 * @param type
	 */
	void addType(DataType type) {
		mDataTypes.push_back(type);
	}

	/**
	 * @brief Returns all columns from the csv file
	 * @param index column index
	 * @return vector with the data
	 */
	template<class DataStruct>
	std::vector<DataStruct> copyToStruct() {
		std::vector<DataStruct> output;
		if (sizeof(DataStruct) < calculateRowLength()) {
			return output;
		}
		for (auto row: mData) {
			DataStruct newValues;
			memcpy(&newValues, row, sizeof(newValues));
			output.push_back(newValues);
		}

		return output;
	}

	/**
	 * @brief Returns a column from the csv file
	 * @param index column index
	 * @return vector with the data
	 */
	std::vector<double> getColumn(int index);

private:

	size_t calculateRowLength();

	const size_t maxStringSize = 32;

	std::vector<std::string> mColumnNames;
	std::vector<DataType> mDataTypes;
	std::vector<char *> mData;
	char mDelim = ',';
};

#endif // INCLUDE_AL_CSVREADER_HPP
<|endoftext|>


<commit_before>// LifeSDL.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;

int _tmain(int argc, _TCHAR* argv[])
{
    SDL_Surface* screen = NULL;

    if (-1 == SDL_Init(SDL_INIT_EVENTTHREAD)) {
        printf("SDL init failed\n");
        return EXIT_FAILURE;
    }

    if (NULL == (screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE))) {
        printf("SDL set video mode failed\n");
        return EXIT_FAILURE;
    }

    SDL_Delay(2000);

    SDL_Quit();
    return EXIT_SUCCESS;
}

<commit_msg>event loop<commit_after>// LifeSDL.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;
const int SCREEN_BPP = 32;

int _tmain(int argc, _TCHAR* argv[])
{
    SDL_Surface* screen = NULL;
    SDL_Event event;
    bool quit = false;

    if (-1 == SDL_Init(SDL_INIT_EVENTTHREAD)) {
        printf("SDL init failed\n");
        return EXIT_FAILURE;
    }

    if (NULL == (screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE))) {
        printf("SDL set video mode failed\n");
        return EXIT_FAILURE;
    }

    SDL_WM_SetCaption("Game of Life", NULL);

    while (!quit) {
        while (SDL_PollEvent(&event)) {
            quit = (event.type == SDL_QUIT || event.type == SDL_KEYDOWN);
        }
    }

    SDL_Quit();
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * 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 Initial Developer of the Original Code is
 *       [ Caolán McNamara <caolanm:redhat.com> ]
 * Portions created by Caolán McNamara are Copyright (C) 2010 * Red Hat, Inc.
 * All Rights Reserved.
 *
 * Contributor(s): Caolán McNamara <caolanm@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */
#include <sal/main.h>
#include <rtl/ustring.hxx>
#include <osl/time.h>

#include <iostream>

#if defined __GXX_EXPERIMENTAL_CXX0X__
#   define HAVE_CXX_Ox 1
#endif

#ifdef HAVE_CXX_Ox
#  define SAL_DECLARE_UTF16(str) u ## str
#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550)
#  define SAL_DECLARE_UTF16(str) U ## str
#elif __SIZEOF_WCHAR_T__ == 2
#  define SAL_DECLARE_UTF16(str) L ## str
#endif

#ifdef SAL_DECLARE_UTF16
#  define RTL_CONSTASCII_USTRINGPARAM_WIDE(str) \
     reinterpret_cast<const sal_Unicode*>(SAL_DECLARE_UTF16(str)), SAL_N_ELEMENTS(str)
#endif

SAL_IMPLEMENT_MAIN()
{
    //get my cpu fan up to speed :-)
    for (int i = 0; i < 10000000; ++i)
    {
        rtl::OUString sFoo(rtl::OUString::createFromAscii("X"));
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM("X"));
#ifdef SAL_DECLARE_UTF16
        rtl::OUString sBoo(RTL_CONSTASCII_USTRINGPARAM_WIDE("X"));
#endif
        rtl::OUString sBaz(static_cast<sal_Unicode>('X'));
        rtl::OUString sNone;
    }

    std::cout << "--Empty Strings--" << std::endl;

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo;
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString() " << nEndTime - nStartTime << "ms" << std::endl;
    }

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo(rtl::OUString::createFromAscii(""));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString::createFromAscii() " << nEndTime - nStartTime << "ms" << std::endl;
    }

    std::cout << "--Single Chars--" << std::endl;

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo(rtl::OUString::createFromAscii("X"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString::createFromAscii(\"X\") " << nEndTime - nStartTime << "ms" << std::endl;
    }

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM("X"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"X\")) " << nEndTime - nStartTime << "ms" << std::endl;
    }

#ifdef SAL_DECLARE_UTF16
    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_WIDE("X"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM_WIDE(\"X\")) " << nEndTime - nStartTime<< "ms" << std::endl;
    }
#endif

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBaz(static_cast<sal_Unicode>('X'));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(static_cast<sal_Unicode>('X') " << nEndTime - nStartTime << "ms" << std::endl;
    }

    std::cout << "--MultiChar Strings--" << std::endl;
    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo(rtl::OUString::createFromAscii("XXXXXXXXXXXXXXX"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString::createFromAscii(\"XXXXXXXX\") " << nEndTime - nStartTime << "ms" << std::endl;
    }

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM("XXXXXXXXXXXXXXX"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"XXXXXXXX\")) " << nEndTime - nStartTime << "ms" << std::endl;
    }

#ifdef SAL_DECLARE_UTF16
    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_WIDE("XXXXXXXXXXXXXXX"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM_WIDE(\"XXXXXXXX\")) " << nEndTime - nStartTime << "ms" << std::endl;
    }
#endif

    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>tweak this to compare classic and wide versions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * 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 Initial Developer of the Original Code is
 *       [ Caolán McNamara <caolanm:redhat.com> ]
 * Portions created by Caolán McNamara are Copyright (C) 2010 * Red Hat, Inc.
 * All Rights Reserved.
 *
 * Contributor(s): Caolán McNamara <caolanm@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */
#include <sal/main.h>
#include <rtl/ustring.hxx>
#include <osl/time.h>

#include <iostream>

#if defined __GXX_EXPERIMENTAL_CXX0X__
#   define HAVE_CXX_Ox 1
#endif

#ifdef HAVE_CXX_Ox
#  define SAL_DECLARE_UTF16(str) u ## str
#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550)
#  define SAL_DECLARE_UTF16(str) U ## str
#elif __SIZEOF_WCHAR_T__ == 2
#  define SAL_DECLARE_UTF16(str) L ## str
#endif

#ifdef SAL_DECLARE_UTF16
#  define RTL_CONSTASCII_USTRINGPARAM_WIDE(str) \
     reinterpret_cast<const sal_Unicode*>(SAL_DECLARE_UTF16(str)), (SAL_N_ELEMENTS(str)-1)
#endif

#define RTL_CONSTASCII_USTRINGPARAM_CLASSIC(str) \
    str, ((sal_Int32)(SAL_N_ELEMENTS(str)-1)), RTL_TEXTENCODING_ASCII_US

SAL_IMPLEMENT_MAIN()
{
    //get my cpu fan up to speed :-)
    for (int i = 0; i < 10000000; ++i)
    {
        rtl::OUString sFoo(rtl::OUString::createFromAscii("X"));
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_CLASSIC("X"));
#ifdef SAL_DECLARE_UTF16
        rtl::OUString sBoo(RTL_CONSTASCII_USTRINGPARAM_WIDE("X"));
#endif
        rtl::OUString sBaz(static_cast<sal_Unicode>('X'));
        rtl::OUString sNone;
    }

    std::cout << "--Empty Strings--" << std::endl;

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo;
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString() " << nEndTime - nStartTime << "ms" << std::endl;
    }

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo(rtl::OUString::createFromAscii(""));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString::createFromAscii() " << nEndTime - nStartTime << "ms" << std::endl;
    }

    std::cout << "--Single Chars--" << std::endl;

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo(rtl::OUString::createFromAscii("X"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString::createFromAscii(\"X\") " << nEndTime - nStartTime << "ms" << std::endl;
    }

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_CLASSIC("X"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM_CLASSIC(\"X\")) " << nEndTime - nStartTime << "ms" << std::endl;
    }

#ifdef SAL_DECLARE_UTF16
    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_WIDE("X"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM_WIDE(\"X\")) " << nEndTime - nStartTime<< "ms" << std::endl;
    }
#endif

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBaz(static_cast<sal_Unicode>('X'));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(static_cast<sal_Unicode>('X') " << nEndTime - nStartTime << "ms" << std::endl;
    }

    std::cout << "--MultiChar Strings--" << std::endl;
    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sFoo(rtl::OUString::createFromAscii("XXXXXXXXXXXXXXX"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString::createFromAscii(\"XXXXXXXX\") " << nEndTime - nStartTime << "ms" << std::endl;
    }

    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_CLASSIC("XXXXXXXXXXXXXXX"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM_CLASSIC(\"XXXXXXXX\")) " << nEndTime - nStartTime << "ms" << std::endl;
    }

#ifdef SAL_DECLARE_UTF16
    {
    sal_uInt32 nStartTime = osl_getGlobalTimer();
    for (int i = 0; i < 100000000; ++i)
        rtl::OUString sBar(RTL_CONSTASCII_USTRINGPARAM_WIDE("XXXXXXXXXXXXXXX"));
    sal_uInt32 nEndTime = osl_getGlobalTimer();
    std::cout << "rtl::OUString(RTL_CONSTASCII_USTRINGPARAM_WIDE(\"XXXXXXXX\")) " << nEndTime - nStartTime << "ms" << std::endl;
    }
#endif

    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#ifndef AMGCL_PERF_COUNTER_MPI_AGGREGATOR_HPP
#define AMGCL_PERF_COUNTER_MPI_AGGREGATOR_HPP

/*
The MIT License

Copyright (c) 2012-2019 Denis Demidov <dennis.demidov@gmail.com>
Copyright (c) 2016 Mohammad Siahatgar <siahatgar@luis.uni-hannover.de>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/perf_counter/mpi_aggregator.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Aggregate performace counter over MPI.
 */

#include <functional>
#include <cmath>
#include <type_traits>
#include <amgcl/mpi/util.hpp>

namespace amgcl {
namespace perf_counter {

template <class Counter, bool SingleReaderPerNode = true>
class mpi_aggregator {
    public:
        typedef typename Counter::value_type value_type;

        mpi_aggregator(MPI_Comm comm = MPI_COMM_WORLD)
            : world(comm), dtype(amgcl::mpi::datatype<value_type>::get())
        {
            if (SingleReaderPerNode) {
                typedef std::integral_constant<bool, sizeof(size_t) == sizeof(int)>::type _32bit;

                char node_name[MPI_MAX_PROCESSOR_NAME];
                int node_name_len, node_master;

                MPI_Get_processor_name(node_name, &node_name_len);
                MPI_Comm_split(world, name_hash(node_name, _32bit()), world.rank, &node_comm);
                MPI_Allreduce(&world.rank, &node_master, 1, MPI_INT, MPI_MIN, node_comm);

                reader = (world.rank == node_master);
                MPI_Comm_split(world, reader, world.rank, &reader_comm);
            }
        }

        ~mpi_aggregator() {
            if (SingleReaderPerNode) {
                MPI_Comm_free(&node_comm);
                MPI_Comm_free(&reader_comm);
            }
        }

        static const char* units() {
            return Counter::units();
        }

        value_type current() {
            value_type gval;

            if (SingleReaderPerNode) {
                if (reader) {
                    value_type lval = counter.current();
                    MPI_Allreduce(&lval, &gval, 1, dtype, MPI_SUM, reader_comm);
                }

                MPI_Bcast(&gval, 1, dtype, 0, node_comm);
            } else {
                value_type lval = counter.current();
                MPI_Allreduce(&lval, &gval, 1, dtype, MPI_SUM, world);
            }

            return gval;
        }
    private:
        amgcl::mpi::communicator world;
        MPI_Datatype dtype;

        bool reader;
        MPI_Comm node_comm, reader_comm;

        Counter counter;

        int name_hash(const char *name, std::true_type) {
            return std::hash<std::string>()(name);
        }

        int name_hash(const char *name, std::false_type) {
            union {
                size_t full;
                struct {
                    int lo, hi;
                };
            } h;

            h.full = std::hash<std::string>()(name);
            return std::abs(h.lo ^ h.hi);
        }
};

} // namespace perf_counter
} // namespace amgcl

#endif
<commit_msg>Fix perf_counter::mpi_aggregator<commit_after>#ifndef AMGCL_PERF_COUNTER_MPI_AGGREGATOR_HPP
#define AMGCL_PERF_COUNTER_MPI_AGGREGATOR_HPP

/*
The MIT License

Copyright (c) 2012-2019 Denis Demidov <dennis.demidov@gmail.com>
Copyright (c) 2016 Mohammad Siahatgar <siahatgar@luis.uni-hannover.de>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/perf_counter/mpi_aggregator.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Aggregate performace counter over MPI.
 */

#include <functional>
#include <cmath>
#include <type_traits>
#include <amgcl/mpi/util.hpp>

namespace amgcl {
namespace perf_counter {

template <class Counter, bool SingleReaderPerNode = true>
class mpi_aggregator {
    public:
        typedef typename Counter::value_type value_type;

        mpi_aggregator(MPI_Comm comm = MPI_COMM_WORLD)
            : world(comm), dtype(amgcl::mpi::datatype<value_type>())
        {
            if (SingleReaderPerNode) {
                typedef std::integral_constant<bool, sizeof(size_t) == sizeof(int)>::type _32bit;

                char node_name[MPI_MAX_PROCESSOR_NAME];
                int node_name_len, node_master;

                MPI_Get_processor_name(node_name, &node_name_len);
                MPI_Comm_split(world, name_hash(node_name, _32bit()), world.rank, &node_comm);
                MPI_Allreduce(&world.rank, &node_master, 1, MPI_INT, MPI_MIN, node_comm);

                reader = (world.rank == node_master);
                MPI_Comm_split(world, reader, world.rank, &reader_comm);
            }
        }

        ~mpi_aggregator() {
            if (SingleReaderPerNode) {
                MPI_Comm_free(&node_comm);
                MPI_Comm_free(&reader_comm);
            }
        }

        static const char* units() {
            return Counter::units();
        }

        value_type current() {
            value_type gval;

            if (SingleReaderPerNode) {
                if (reader) {
                    value_type lval = counter.current();
                    MPI_Allreduce(&lval, &gval, 1, dtype, MPI_SUM, reader_comm);
                }

                MPI_Bcast(&gval, 1, dtype, 0, node_comm);
            } else {
                value_type lval = counter.current();
                MPI_Allreduce(&lval, &gval, 1, dtype, MPI_SUM, world);
            }

            return gval;
        }
    private:
        amgcl::mpi::communicator world;
        MPI_Datatype dtype;

        bool reader;
        MPI_Comm node_comm, reader_comm;

        Counter counter;

        int name_hash(const char *name, std::true_type) {
            return std::hash<std::string>()(name);
        }

        int name_hash(const char *name, std::false_type) {
            union {
                size_t full;
                struct {
                    int lo, hi;
                } part;
            } h;

            h.full = std::hash<std::string>()(name);
            return std::abs(h.part.lo ^ h.part.hi);
        }
};

} // namespace perf_counter
} // namespace amgcl

#endif
<|endoftext|>


<commit_before>//===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/PathV2.h"

#include "gtest/gtest.h"

using namespace llvm;

namespace {

TEST(Support, Path) {
  SmallVector<StringRef, 40> paths;
  paths.push_back("");
  paths.push_back(".");
  paths.push_back("..");
  paths.push_back("foo");
  paths.push_back("/");
  paths.push_back("/foo");
  paths.push_back("foo/");
  paths.push_back("/foo/");
  paths.push_back("foo/bar");
  paths.push_back("/foo/bar");
  paths.push_back("//net");
  paths.push_back("//net/foo");
  paths.push_back("///foo///");
  paths.push_back("///foo///bar");
  paths.push_back("/.");
  paths.push_back("./");
  paths.push_back("/..");
  paths.push_back("../");
  paths.push_back("foo/.");
  paths.push_back("foo/..");
  paths.push_back("foo/./");
  paths.push_back("foo/./bar");
  paths.push_back("foo/..");
  paths.push_back("foo/../");
  paths.push_back("foo/../bar");
  paths.push_back("c:");
  paths.push_back("c:/");
  paths.push_back("c:foo");
  paths.push_back("c:/foo");
  paths.push_back("c:foo/");
  paths.push_back("c:/foo/");
  paths.push_back("c:/foo/bar");
  paths.push_back("prn:");
  paths.push_back("c:\\");
  paths.push_back("c:foo");
  paths.push_back("c:\\foo");
  paths.push_back("c:foo\\");
  paths.push_back("c:\\foo\\");
  paths.push_back("c:\\foo/");
  paths.push_back("c:/foo\\bar");

  for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
                                                  e = paths.end();
                                                  i != e;
                                                  ++i) {
    outs() << *i << " =>\n    Iteration: [";
    for (sys::path::const_iterator ci = sys::path::begin(*i),
                                   ce = sys::path::end(*i);
                                   ci != ce;
                                   ++ci) {
      outs() << *ci << ',';
    }
    outs() << "]\n";

    StringRef res;
    SmallString<16> temp_store;
    if (error_code ec = sys::path::root_path(*i, res)) ASSERT_FALSE(ec.message().c_str());
    outs() << "    root_path: " << res << '\n';
    if (error_code ec = sys::path::root_name(*i, res)) ASSERT_FALSE(ec.message().c_str());
    outs() << "    root_name: " << res << '\n';
    if (error_code ec = sys::path::root_directory(*i, res)) ASSERT_FALSE(ec.message().c_str());
    outs() << "    root_directory: " << res << '\n';

    temp_store = *i;
    if (error_code ec = sys::path::make_absolute(temp_store)) ASSERT_FALSE(ec.message().c_str());
    outs() << "    make_absolute: " << temp_store << '\n';

    outs().flush();
  }
}

} // anonymous namespace
<commit_msg>Support/PathV2: Fix 80 col.<commit_after>//===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/PathV2.h"

#include "gtest/gtest.h"

using namespace llvm;

namespace {

TEST(Support, Path) {
  SmallVector<StringRef, 40> paths;
  paths.push_back("");
  paths.push_back(".");
  paths.push_back("..");
  paths.push_back("foo");
  paths.push_back("/");
  paths.push_back("/foo");
  paths.push_back("foo/");
  paths.push_back("/foo/");
  paths.push_back("foo/bar");
  paths.push_back("/foo/bar");
  paths.push_back("//net");
  paths.push_back("//net/foo");
  paths.push_back("///foo///");
  paths.push_back("///foo///bar");
  paths.push_back("/.");
  paths.push_back("./");
  paths.push_back("/..");
  paths.push_back("../");
  paths.push_back("foo/.");
  paths.push_back("foo/..");
  paths.push_back("foo/./");
  paths.push_back("foo/./bar");
  paths.push_back("foo/..");
  paths.push_back("foo/../");
  paths.push_back("foo/../bar");
  paths.push_back("c:");
  paths.push_back("c:/");
  paths.push_back("c:foo");
  paths.push_back("c:/foo");
  paths.push_back("c:foo/");
  paths.push_back("c:/foo/");
  paths.push_back("c:/foo/bar");
  paths.push_back("prn:");
  paths.push_back("c:\\");
  paths.push_back("c:foo");
  paths.push_back("c:\\foo");
  paths.push_back("c:foo\\");
  paths.push_back("c:\\foo\\");
  paths.push_back("c:\\foo/");
  paths.push_back("c:/foo\\bar");

  for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
                                                  e = paths.end();
                                                  i != e;
                                                  ++i) {
    outs() << *i << " =>\n    Iteration: [";
    for (sys::path::const_iterator ci = sys::path::begin(*i),
                                   ce = sys::path::end(*i);
                                   ci != ce;
                                   ++ci) {
      outs() << *ci << ',';
    }
    outs() << "]\n";

    StringRef res;
    SmallString<16> temp_store;
    if (error_code ec = sys::path::root_path(*i, res))
      ASSERT_FALSE(ec.message().c_str());
    outs() << "    root_path: " << res << '\n';
    if (error_code ec = sys::path::root_name(*i, res))
      ASSERT_FALSE(ec.message().c_str());
    outs() << "    root_name: " << res << '\n';
    if (error_code ec = sys::path::root_directory(*i, res))
      ASSERT_FALSE(ec.message().c_str());
    outs() << "    root_directory: " << res << '\n';

    temp_store = *i;
    if (error_code ec = sys::path::make_absolute(temp_store))
      ASSERT_FALSE(ec.message().c_str());
    outs() << "    make_absolute: " << temp_store << '\n';

    outs().flush();
  }
}

} // anonymous namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xehelper.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 10:58:51 $
 *
 *  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 SC_XEHELPER_HXX
#define SC_XEHELPER_HXX

#ifndef SC_XEROOT_HXX
#include "xeroot.hxx"
#endif
#ifndef SC_XESTRING_HXX
#include "xestring.hxx"
#endif

// EditEngine->String conversion ==============================================

class EditEngine;
class ScEditCell;
class ScPatternAttr;
class SdrTextObj;

/** This class provides methods to create an XclExpString.
    @descr  The string can be created from an edit engine text object or
    directly from a Calc edit cell. */
class XclExpStringHelper : ScfNoInstance
{
public:
    /** Creates a new formatted string from a Calc edit cell.
        @param rEditCell  The Calc edit cell object.
        @param pCellAttr  The set item containing the cell formatting.
        @param nFlags  Modifiers for string export.
        @param nMaxLen  The maximum number of characters to store in this string.
        @return  The new string object (shared pointer). */
    static XclExpStringPtr      CreateString(
                                    const XclExpRoot& rRoot,
                                    const ScEditCell& rEditCell,
                                    const ScPatternAttr* pCellAttr,
                                    XclStrFlags nFlags = EXC_STR_DEFAULT,
                                    sal_uInt16 nMaxLen = 0xFFFF );

    /** Creates a new formatted string from a drawing text box.
        @param rTextObj  The text box object.
        @param nFlags  Modifiers for string export.
        @param nMaxLen  The maximum number of characters to store in this string.
        @return  The new string object (shared pointer). */
    static XclExpStringPtr      CreateString(
                                    const XclExpRoot& rRoot,
                                    const SdrTextObj& rTextObj,
                                    XclStrFlags nFlags = EXC_STR_DEFAULT,
                                    sal_uInt16 nMaxLen = 0xFFFF );
};

// Header/footer conversion ===================================================

class EditEngine;

/** Converts edit engine text objects to an Excel header/footer string.
    @descr  Header/footer content is divided into three parts: Left, center and
    right portion. All formatting information will be encoded in the Excel string
    using special character seuences. A control sequence starts with the ampersand
    character.

    Supported control sequences:
    &L                      start of left portion
    &C                      start of center portion
    &R                      start of right portion
    &P                      current page number
    &N                      page count
    &D                      current date
    &T                      current time
    &A                      table name
    &F                      file name without path
    &Z                      file path without file name
    &Z&F                    file path and name
    &U                      underlining on/off
    &E                      double underlining on/off
    &S                      strikeout characters on/off
    &X                      superscript on/off
    &Y                      subscript on/off
    &"fontname,fontstyle"   use font with name 'fontname' and style 'fontstyle'
    &fontheight             set font height in points ('fontheight' is a decimal value)

    Known but unsupported control sequences:
    &G                      picture
 */
class XclExpHFConverter : protected XclExpRoot, ScfNoCopy
{
public:
    explicit                    XclExpHFConverter( const XclExpRoot& rRoot );

    /** Generates the header/footer string from the passed edit engine text objects. */
    String                      GenerateString(
                                    const EditTextObject* pLeftObj,
                                    const EditTextObject* pCenterObj,
                                    const EditTextObject* pRightObj );

private:
    /** Converts the text object contents and stores it in the passed string. */
    void                        AppendPortion(
                                    String& rHFString,
                                    const EditTextObject* pTextObj,
                                    sal_Unicode cPortionCode );

private:
    EditEngine&                 mrEE;           /// The header/footer edit engine.
};

// URL conversion =============================================================

/** This class contains static methods to encode a file URL.
    @descr  Excel stores URLs in a format that contains special control characters,
    i.e. for directory separators or volume names. */
class XclExpUrlHelper : ScfNoInstance
{
public:
    /** Encodes and returns the URL passed in rAbsUrl to an Excel like URL.
        @param pTableName  Optional pointer to a table name to be encoded in this URL. */
    static String               EncodeUrl( const XclExpRoot& rRoot, const String& rAbsUrl, const String* pTableName = NULL );
    /** Encodes and returns the passed DDE link to an Excel like DDE link. */
    static String               EncodeDde( const String& rApplic, const String rTopic );
};

// Cached Value Lists =========================================================

class XclExpStream;

/** The base class for cached values.
    @descr  Cached values are used to store a list or a 2D array of double,
    string and Boolean values and error codes, for instannce in the records
    CRN and EXTERNNAME or in the token tArray. */
class XclExpCachedValue
{
public:
    virtual                     ~XclExpCachedValue();
    virtual void                Save( XclExpStream& rStrm ) const = 0;
};

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

/** A cached value that stores a double. */
class XclExpCachedDouble : public XclExpCachedValue
{
public:
    explicit inline             XclExpCachedDouble( double fVal ) : mfVal( fVal ) {}
    /** Writes the double value to stream. */
    virtual void                Save( XclExpStream& rStrm ) const;

private:
    double                      mfVal;          /// The double value.
};

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

/** A cached value that stores a string. */
class XclExpCachedString : public XclExpCachedValue
{
public:
    explicit                    XclExpCachedString( const String& rStr, XclStrFlags nFlags = EXC_STR_DEFAULT );
    /** Writes the string to stream. */
    virtual void                Save( XclExpStream& rStrm ) const;

private:
    XclExpString                maStr;
};

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

/** A cached value that stores an error code. */
class XclExpCachedError : public XclExpCachedValue
{
public:
    explicit                    XclExpCachedError( USHORT nScError );
    /** Writes the error code to stream. */
    virtual void                Save( XclExpStream& rStrm ) const;

private:
    sal_uInt8                   mnError;
};

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

class ScDocument;
class ScMatrix;

/** Contains cached values in a 2-dimensional array. */
class XclExpCachedMatrix
{
public:
    /** Constructs and fills a new matrix.
        @param rMatrix  The Calc value matrix.
        @param nFlags  Flags for writing strings. */
    explicit                    XclExpCachedMatrix(
                                    const ScMatrix& rMatrix,
                                    XclStrFlags nFlags = EXC_STR_DEFAULT );

    /** Returns the byte count of all contained data. */
    sal_uInt32                  GetSize() const;
    /** Writes the complete matrix to stream. */
    void                        Save( XclExpStream& rStrm ) const;

private:
    typedef ScfDelList< XclExpCachedValue > XclExpCachedValueList;

    XclExpCachedValueList       maValueList;    /// The list containing the cached values.
    SCSIZE                      mnScCols;       /// Calc column count of the value matrix.
    SCSIZE                      mnScRows;       /// Calc row count of the value matrix.
};

// ============================================================================

#endif

<commit_msg>INTEGRATION: CWS dr19 (1.9.14); FILE MERGED 2004/06/16 14:36:12 dr 1.9.14.1: #i23296# correct export of header/footer position<commit_after>/*************************************************************************
 *
 *  $RCSfile: xehelper.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: kz $ $Date: 2004-07-30 16:22:44 $
 *
 *  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 SC_XEHELPER_HXX
#define SC_XEHELPER_HXX

#ifndef SC_XEROOT_HXX
#include "xeroot.hxx"
#endif
#ifndef SC_XESTRING_HXX
#include "xestring.hxx"
#endif

// EditEngine->String conversion ==============================================

class EditEngine;
class ScEditCell;
class ScPatternAttr;
class SdrTextObj;

/** This class provides methods to create an XclExpString.
    @descr  The string can be created from an edit engine text object or
    directly from a Calc edit cell. */
class XclExpStringHelper : ScfNoInstance
{
public:
    /** Creates a new formatted string from a Calc edit cell.
        @param rEditCell  The Calc edit cell object.
        @param pCellAttr  The set item containing the cell formatting.
        @param nFlags  Modifiers for string export.
        @param nMaxLen  The maximum number of characters to store in this string.
        @return  The new string object (shared pointer). */
    static XclExpStringPtr      CreateString(
                                    const XclExpRoot& rRoot,
                                    const ScEditCell& rEditCell,
                                    const ScPatternAttr* pCellAttr,
                                    XclStrFlags nFlags = EXC_STR_DEFAULT,
                                    sal_uInt16 nMaxLen = 0xFFFF );

    /** Creates a new formatted string from a drawing text box.
        @param rTextObj  The text box object.
        @param nFlags  Modifiers for string export.
        @param nMaxLen  The maximum number of characters to store in this string.
        @return  The new string object (shared pointer). */
    static XclExpStringPtr      CreateString(
                                    const XclExpRoot& rRoot,
                                    const SdrTextObj& rTextObj,
                                    XclStrFlags nFlags = EXC_STR_DEFAULT,
                                    sal_uInt16 nMaxLen = 0xFFFF );
};

// Header/footer conversion ===================================================

class EditEngine;

/** Converts edit engine text objects to an Excel header/footer string.
    @descr  Header/footer content is divided into three parts: Left, center and
    right portion. All formatting information will be encoded in the Excel string
    using special character seuences. A control sequence starts with the ampersand
    character.

    Supported control sequences:
    &L                      start of left portion
    &C                      start of center portion
    &R                      start of right portion
    &P                      current page number
    &N                      page count
    &D                      current date
    &T                      current time
    &A                      table name
    &F                      file name without path
    &Z                      file path without file name
    &Z&F                    file path and name
    &U                      underlining on/off
    &E                      double underlining on/off
    &S                      strikeout characters on/off
    &X                      superscript on/off
    &Y                      subscript on/off
    &"fontname,fontstyle"   use font with name 'fontname' and style 'fontstyle'
    &fontheight             set font height in points ('fontheight' is a decimal value)

    Known but unsupported control sequences:
    &G                      picture
 */
class XclExpHFConverter : protected XclExpRoot, ScfNoCopy
{
public:
    explicit                    XclExpHFConverter( const XclExpRoot& rRoot );

    /** Generates the header/footer string from the passed edit engine text objects. */
    void                GenerateString(
                            const EditTextObject* pLeftObj,
                            const EditTextObject* pCenterObj,
                            const EditTextObject* pRightObj );

    /** Returns the last generated header/footer string. */
    inline const String& GetHFString() const { return maHFString; }
    /** Returns the total height of the last generated header/footer in twips. */
    inline sal_Int32    GetTotalHeight() const { return mnTotalHeight; }

private:
    /** Converts the text object contents and stores it in the passed string. */
    void                        AppendPortion(
                                    const EditTextObject* pTextObj,
                                    sal_Unicode cPortionCode );

private:
    EditEngine&                 mrEE;           /// The header/footer edit engine.
    String              maHFString;     /// The last generated header/footer string.
    sal_Int32           mnTotalHeight;  /// Total height of the last header/footer (twips).
};

// URL conversion =============================================================

/** This class contains static methods to encode a file URL.
    @descr  Excel stores URLs in a format that contains special control characters,
    i.e. for directory separators or volume names. */
class XclExpUrlHelper : ScfNoInstance
{
public:
    /** Encodes and returns the URL passed in rAbsUrl to an Excel like URL.
        @param pTableName  Optional pointer to a table name to be encoded in this URL. */
    static String               EncodeUrl( const XclExpRoot& rRoot, const String& rAbsUrl, const String* pTableName = NULL );
    /** Encodes and returns the passed DDE link to an Excel like DDE link. */
    static String               EncodeDde( const String& rApplic, const String rTopic );
};

// Cached Value Lists =========================================================

class XclExpStream;

/** The base class for cached values.
    @descr  Cached values are used to store a list or a 2D array of double,
    string and Boolean values and error codes, for instannce in the records
    CRN and EXTERNNAME or in the token tArray. */
class XclExpCachedValue
{
public:
    virtual                     ~XclExpCachedValue();
    virtual void                Save( XclExpStream& rStrm ) const = 0;
};

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

/** A cached value that stores a double. */
class XclExpCachedDouble : public XclExpCachedValue
{
public:
    explicit inline             XclExpCachedDouble( double fVal ) : mfVal( fVal ) {}
    /** Writes the double value to stream. */
    virtual void                Save( XclExpStream& rStrm ) const;

private:
    double                      mfVal;          /// The double value.
};

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

/** A cached value that stores a string. */
class XclExpCachedString : public XclExpCachedValue
{
public:
    explicit                    XclExpCachedString( const String& rStr, XclStrFlags nFlags = EXC_STR_DEFAULT );
    /** Writes the string to stream. */
    virtual void                Save( XclExpStream& rStrm ) const;

private:
    XclExpString                maStr;
};

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

/** A cached value that stores an error code. */
class XclExpCachedError : public XclExpCachedValue
{
public:
    explicit                    XclExpCachedError( USHORT nScError );
    /** Writes the error code to stream. */
    virtual void                Save( XclExpStream& rStrm ) const;

private:
    sal_uInt8                   mnError;
};

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

class ScDocument;
class ScMatrix;

/** Contains cached values in a 2-dimensional array. */
class XclExpCachedMatrix
{
public:
    /** Constructs and fills a new matrix.
        @param rMatrix  The Calc value matrix.
        @param nFlags  Flags for writing strings. */
    explicit                    XclExpCachedMatrix(
                                    const ScMatrix& rMatrix,
                                    XclStrFlags nFlags = EXC_STR_DEFAULT );

    /** Returns the byte count of all contained data. */
    sal_uInt32                  GetSize() const;
    /** Writes the complete matrix to stream. */
    void                        Save( XclExpStream& rStrm ) const;

private:
    typedef ScfDelList< XclExpCachedValue > XclExpCachedValueList;

    XclExpCachedValueList       maValueList;    /// The list containing the cached values.
    SCSIZE                      mnScCols;       /// Calc column count of the value matrix.
    SCSIZE                      mnScRows;       /// Calc row count of the value matrix.
};

// ============================================================================

#endif

<|endoftext|>