<commit_before>#include "ScriptWrapper.h"
#include "MagnetiteCore.h"
#include "WorldChunk.h"
#include "Renderer.h"
#include "TextureManager.h"
#include "InputManager.h"
#include "StoneBlock.h"
#include "World.h"
#include "Character.h"
#include "BlockFactory.h"
#include "BaseGame.h"
#include "ScriptGame.h"
#include "BulletDebug.h"
#include "ResourceManager.h"
#include <ctime>

MagnetiteCore* MagnetiteCore::Singleton = 0;
static GLDebugDrawer debug;

/* Simple events */
void globalEventHandler( const InputEvent& evt )
{
	MagnetiteCore::Singleton->getGame()->_inputEvents( evt );
	if( evt.event == Inputs::SCREENSHOT && evt.down == true ) {
		MagnetiteCore::Singleton->screenshot();
	}
}

MagnetiteCore::MagnetiteCore(void)
: mContinue( true ),
mWorld( NULL ),
mResourceManager( NULL ),
mTextureManager( NULL ),
mInputManager( NULL ),
mScriptWrapper( NULL ),
mTimescale( 1.f ),
mLastX( 0.f ),
mLastY( 0.f ),
mPBroadphase( NULL ),
mPCConfig( NULL ),
mCCDispatch ( NULL ),
mSolver( NULL ),
mPhysicsWorld( NULL )
{
	MagnetiteCore::Singleton = this;
	mRenderer = new Renderer();
	mTextureManager = new TextureManager();
	mInputManager = new InputManager();
	mScriptWrapper = new ScriptWrapper();
	mInputManager->setEventCallback( Inputs::FORWARD, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::BACK, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::LEFT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::RIGHT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::JUMP, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::SPRINT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::SCREENSHOT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::FLY, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::RESPAWN, &globalEventHandler );
}

MagnetiteCore::~MagnetiteCore(void)
{
	unloadWorld();

	delete mRenderer;
	delete mResourceManager;
	delete mTextureManager;
	delete mInputManager;
	delete mScriptWrapper;

	mPhysicsWorld->removeRigidBody( mGroundBody );

	delete mGroundBody;
	delete mGroundShape;
	delete mGroundState;

	delete mPhysicsWorld;
	delete mSolver;
	delete mCCDispatch;
	delete mPCConfig;
	delete mPBroadphase;
}

void MagnetiteCore::init(int *argc, char **argv)
{
	mResourceManager = new ResourceManager();
	mResourceManager->addLocation("../resources/shaders/");
	mResourceManager->addLocation("../resources/sprites/");
	mResourceManager->addLocation("../resources/ui/");
	sf::ContextSettings wnds;
	wnds.DepthBits = 24;
	//wnds.AntialiasingLevel = 2;
	mWindow.Create(sf::VideoMode(800,600,32), "Magnetite", sf::Style::Close | sf::Style::Resize, wnds);
	mWindow.EnableKeyRepeat( false );
	mWindow.EnableVerticalSync( false );
	//mWindow.UseVerticalSync(true);
	mRenderer->initialize(mWindow);
	mTextureManager->initalize();
	mRenderer->resizeViewport(0,0,800,600);
	initalizePhysics();
}

void MagnetiteCore::initalizePhysics()
{
	mPBroadphase = new btDbvtBroadphase();
	mPCConfig = new btDefaultCollisionConfiguration();
	mCCDispatch = new btCollisionDispatcher(mPCConfig);
	mSolver = new btSequentialImpulseConstraintSolver();
	mPhysicsWorld = new btDiscreteDynamicsWorld( mCCDispatch, mPBroadphase, mSolver, mPCConfig );
	mPhysicsWorld->setGravity( btVector3( 0.f, -9.81f, 0.f ) );
	mGroundShape = new btStaticPlaneShape( btVector3(0, 1, 0), 0 );
	mGroundState = new btDefaultMotionState;
	btRigidBody::btRigidBodyConstructionInfo ci( 0, mGroundState, mGroundShape, btVector3(0,0,0) );
	mGroundBody = new btRigidBody( ci );
	mPhysicsWorld->addRigidBody( mGroundBody );
	debug.setDebugMode( btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb );
	mPhysicsWorld->setDebugDrawer( &debug );
}

btDiscreteDynamicsWorld* MagnetiteCore::getPhysicsWorld()
{
	return mPhysicsWorld;
}

void MagnetiteCore::screenshot()
{
	sf::Image screen = mWindow.Capture();
	time_t rawt = time( NULL );
	tm* t = localtime( &rawt );
	char tstr[80];
	strftime(tstr, 80, "%Y-%m-%d_%H-%M-%S", t);
	std::string fname("screenshot_");
	fname.append( tstr );
	fname.append(".png");
	Util::log("Saving screenshot to: " + fname);
	screen.SaveToFile(fname);
}

void MagnetiteCore::startGame( const std::string& type )
{
	mScriptWrapper->init();

	//mGame = FactoryManager::getManager().createGame(type);
	ScriptGame* g = new ScriptGame();
	g->setName("script");
	g->_setScriptObject( mScriptWrapper->newGame("tetris") );
	mGame = g;
	if( mGame != NULL )
		Util::log("Starting game: " + mGame->getName() );
	mGame->_startGameSingle();

	newWorld("test");

	mGame->_loadGame();

	mScriptWrapper->runFile("./scripts/main.js");

	// No multiplayer yet so just force player join
	mGame->_playerJoined();
}

void MagnetiteCore::inputMovement( const Vector3 &v )
{
	mGame->_inputMovement( v );
}

void MagnetiteCore::mouseMoved( const float x, const float y )
{
	mGame->_mouseMoved( x, y );
}

void MagnetiteCore::go()
{
	// Print factory list for testing
	FactoryManager::getManager().logFactories();

	int lastX = mWindow.GetWidth()/2;
	int lastY = mWindow.GetHeight()/2;

	mClock.Reset();
	while(mContinue && mWindow.IsOpened()) {
#ifdef WIN32
		float lDelta = mClock.GetElapsedTime();
#else
		float lDelta = mClock.GetElapsedTime()*0.001;
#endif
		mClock.Reset();

		// Handle Events before we render.
		sf::Event lEvt;
		while( mWindow.PollEvent(lEvt) ) {
			if( lEvt.Type == sf::Event::Closed ) {
				exit();
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Escape) ) {
				exit();
			}

			if( lEvt.Type == sf::Event::KeyPressed )
			{
				mInputManager->keyDown( lEvt.Key.Code );
				mGame->keyDown( lEvt.Key.Code );
			}
			if( lEvt.Type == sf::Event::KeyReleased )
			{
				mInputManager->keyUp( lEvt.Key.Code );
				mGame->keyUp( lEvt.Key.Code );
			}

			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::R) ) {
					if(mRenderer->getRenderMode() == Renderer::RENDER_SOLID)
						mRenderer->setRenderMode(Renderer::RENDER_LIGHTING);
					else
						mRenderer->setRenderMode(Renderer::RENDER_SOLID);
			}

			//==========
			//= Debug Buttons
			//==========
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F1 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_OFF );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F3 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_STATS );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F4 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_PHYSICS );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F5 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_LINES );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F6 ) ) {
				Util::setLogLevel( Util::Verbose );
			}
			if( (lEvt.Type == sf::Event::KeyReleased) &&
				(lEvt.Key.Code == sf::Keyboard::F) ) {
					//mPlayer->enableFlying( !mPlayer->isFlying() );
					//Util::log( (Util::toString(mPlayer->isFlying())) + " Flying");
			}
			if( (lEvt.Type == sf::Event::KeyReleased) &&
				(lEvt.Key.Code == sf::Keyboard::F) ) {
					//mPlayer->enableFlying( !mPlayer->isFlying() );
					//Util::log( (Util::toString(mPlayer->isFlying())) + " Flying");
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Add) ) {
					mRenderer->nextBlock();
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Num9) ) {
					mTimescale *= 0.5f;
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Num0) ) {
					mTimescale *= 2.f;
			}
			if( (lEvt.Type == sf::Event::MouseMoved) ) {
					mGame->_mouseMoved( -(lEvt.MouseMove.X - lastX), -(lEvt.MouseMove.Y  - lastY));
					lastX = lEvt.MouseMove.X;
					lastY = lEvt.MouseMove.Y;
			}
			if( (lEvt.Type == sf::Event::MouseLeft) ) {
					sf::Mouse::SetPosition( sf::Vector2i( mWindow.GetWidth() / 2, mWindow.GetHeight() / 2), mWindow );
			}
			if( lEvt.Type == sf::Event::MouseButtonPressed && lEvt.MouseButton.Button == sf::Mouse::Left ) {
				mGame->_primary();
			}
			if( lEvt.Type == sf::Event::MouseButtonPressed && lEvt.MouseButton.Button == sf::Mouse::Right ) {
				mGame->_secondary();
			}
			if( lEvt.Type == sf::Event::Resized ) {
				mRenderer->resizeViewport( 0, 0, lEvt.Size.Width, lEvt.Size.Height );
			}
		}

		lDelta *= mTimescale;

		mPhysicsWorld->stepSimulation( lDelta );

		//Ensure each loaded chunk is updated before being sent to the GPU
		mWorld->update( lDelta );

		// Update all the characters
		for( std::vector<Character*>::iterator it = mCharacters.begin(); it != mCharacters.end(); it++ )
		{
			(*it)->update( lDelta );
		}

		if( mGame != NULL )
		{
			mGame->think( lDelta );
		}

		//Ensure the renderer has the correct camera
		mRenderer->setCamera( mGame->getLocalPlayer()->getCamera() );
		mRenderer->render(lDelta, mWorld);

		mGame->uiPaint( mRenderer );

		mWindow.Display();
	}

	mWindow.Close();

}

void MagnetiteCore::exit()
{
	mContinue = false;
}

TextureManager* MagnetiteCore::getTextureManager()
{
	return mTextureManager;
}

ResourceManager* MagnetiteCore::getResourceManager()
{
	return mResourceManager;
}

Renderer* MagnetiteCore::getRenderer()
{
	return mRenderer;
}

ScriptWrapper* MagnetiteCore::getScriptManager()
{
	return mScriptWrapper;
}

BaseGame* MagnetiteCore::getGame()
{
	return mGame;
}

float MagnetiteCore::getTimescale()
{
	return mTimescale;
}

void MagnetiteCore::newWorld( std::string name )
{
	unloadWorld();

	mWorld = new World( 5 );
	//mWorld->newWorld( name );
}

void MagnetiteCore::unloadWorld()
{
	if( mWorld != NULL ) {
		// world handles saving.
		delete mWorld;
	}
	mWorld = NULL;
}

World* MagnetiteCore::getWorld()
{
	return mWorld;
}

Character* MagnetiteCore::createCharacter()
{
	Character* c = new Character();
	mCharacters.push_back( c );
	return c;
}

void MagnetiteCore::destroyCharacter( Character* c )
{
	for( std::vector<Character*>::iterator it = mCharacters.begin(); it != mCharacters.end(); it++ ) {
		if( c == (*it) )
			mCharacters.erase( it++ );
	}
}

<commit_msg>reorganized logic to avoid graphical errors<commit_after>#include "ScriptWrapper.h"
#include "MagnetiteCore.h"
#include "WorldChunk.h"
#include "Renderer.h"
#include "TextureManager.h"
#include "InputManager.h"
#include "StoneBlock.h"
#include "World.h"
#include "Character.h"
#include "BlockFactory.h"
#include "BaseGame.h"
#include "ScriptGame.h"
#include "BulletDebug.h"
#include "ResourceManager.h"
#include <ctime>

MagnetiteCore* MagnetiteCore::Singleton = 0;
static GLDebugDrawer debug;

/* Simple events */
void globalEventHandler( const InputEvent& evt )
{
	MagnetiteCore::Singleton->getGame()->_inputEvents( evt );
	if( evt.event == Inputs::SCREENSHOT && evt.down == true ) {
		MagnetiteCore::Singleton->screenshot();
	}
}

MagnetiteCore::MagnetiteCore(void)
: mContinue( true ),
mWorld( NULL ),
mResourceManager( NULL ),
mTextureManager( NULL ),
mInputManager( NULL ),
mScriptWrapper( NULL ),
mTimescale( 1.f ),
mLastX( 0.f ),
mLastY( 0.f ),
mPBroadphase( NULL ),
mPCConfig( NULL ),
mCCDispatch ( NULL ),
mSolver( NULL ),
mPhysicsWorld( NULL )
{
	MagnetiteCore::Singleton = this;
	mRenderer = new Renderer();
	mTextureManager = new TextureManager();
	mInputManager = new InputManager();
	mScriptWrapper = new ScriptWrapper();
	mInputManager->setEventCallback( Inputs::FORWARD, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::BACK, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::LEFT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::RIGHT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::JUMP, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::SPRINT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::SCREENSHOT, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::FLY, &globalEventHandler );
	mInputManager->setEventCallback( Inputs::RESPAWN, &globalEventHandler );
}

MagnetiteCore::~MagnetiteCore(void)
{
	unloadWorld();

	delete mRenderer;
	delete mResourceManager;
	delete mTextureManager;
	delete mInputManager;
	delete mScriptWrapper;

	mPhysicsWorld->removeRigidBody( mGroundBody );

	delete mGroundBody;
	delete mGroundShape;
	delete mGroundState;

	delete mPhysicsWorld;
	delete mSolver;
	delete mCCDispatch;
	delete mPCConfig;
	delete mPBroadphase;
}

void MagnetiteCore::init(int *argc, char **argv)
{
	mResourceManager = new ResourceManager();
	mResourceManager->addLocation("../resources/shaders/");
	mResourceManager->addLocation("../resources/sprites/");
	mResourceManager->addLocation("../resources/ui/");
	sf::ContextSettings wnds;
	wnds.DepthBits = 24;
	//wnds.AntialiasingLevel = 2;
	mWindow.Create(sf::VideoMode(800,600,32), "Magnetite", sf::Style::Close | sf::Style::Resize, wnds);
	mWindow.EnableKeyRepeat( false );
	mWindow.EnableVerticalSync( false );
	//mWindow.UseVerticalSync(true);
	mRenderer->initialize(mWindow);
	mTextureManager->initalize();
	mRenderer->resizeViewport(0,0,800,600);
	initalizePhysics();
}

void MagnetiteCore::initalizePhysics()
{
	mPBroadphase = new btDbvtBroadphase();
	mPCConfig = new btDefaultCollisionConfiguration();
	mCCDispatch = new btCollisionDispatcher(mPCConfig);
	mSolver = new btSequentialImpulseConstraintSolver();
	mPhysicsWorld = new btDiscreteDynamicsWorld( mCCDispatch, mPBroadphase, mSolver, mPCConfig );
	mPhysicsWorld->setGravity( btVector3( 0.f, -9.81f, 0.f ) );
	mGroundShape = new btStaticPlaneShape( btVector3(0, 1, 0), 0 );
	mGroundState = new btDefaultMotionState;
	btRigidBody::btRigidBodyConstructionInfo ci( 0, mGroundState, mGroundShape, btVector3(0,0,0) );
	mGroundBody = new btRigidBody( ci );
	mPhysicsWorld->addRigidBody( mGroundBody );
	debug.setDebugMode( btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb );
	mPhysicsWorld->setDebugDrawer( &debug );
}

btDiscreteDynamicsWorld* MagnetiteCore::getPhysicsWorld()
{
	return mPhysicsWorld;
}

void MagnetiteCore::screenshot()
{
	sf::Image screen = mWindow.Capture();
	time_t rawt = time( NULL );
	tm* t = localtime( &rawt );
	char tstr[80];
	strftime(tstr, 80, "%Y-%m-%d_%H-%M-%S", t);
	std::string fname("screenshot_");
	fname.append( tstr );
	fname.append(".png");
	Util::log("Saving screenshot to: " + fname);
	screen.SaveToFile(fname);
}

void MagnetiteCore::startGame( const std::string& type )
{
	mScriptWrapper->init();

	//mGame = FactoryManager::getManager().createGame(type);
	ScriptGame* g = new ScriptGame();
	g->setName("script");
	g->_setScriptObject( mScriptWrapper->newGame("tetris") );
	mGame = g;
	if( mGame != NULL )
		Util::log("Starting game: " + mGame->getName() );
	mGame->_startGameSingle();

	newWorld("test");

	mGame->_loadGame();

	mScriptWrapper->runFile("./scripts/main.js");

	// No multiplayer yet so just force player join
	mGame->_playerJoined();
}

void MagnetiteCore::inputMovement( const Vector3 &v )
{
	mGame->_inputMovement( v );
}

void MagnetiteCore::mouseMoved( const float x, const float y )
{
	mGame->_mouseMoved( x, y );
}

void MagnetiteCore::go()
{
	// Print factory list for testing
	FactoryManager::getManager().logFactories();

	int lastX = mWindow.GetWidth()/2;
	int lastY = mWindow.GetHeight()/2;

	mClock.Reset();
	while(mContinue && mWindow.IsOpened()) {
#ifdef WIN32
		float lDelta = mClock.GetElapsedTime();
#else
		float lDelta = mClock.GetElapsedTime()*0.001;
#endif
		mClock.Reset();

		// Handle Events before we render.
		sf::Event lEvt;
		while( mWindow.PollEvent(lEvt) ) {
			if( lEvt.Type == sf::Event::Closed ) {
				exit();
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Escape) ) {
				exit();
			}

			if( lEvt.Type == sf::Event::KeyPressed )
			{
				mInputManager->keyDown( lEvt.Key.Code );
				mGame->keyDown( lEvt.Key.Code );
			}
			if( lEvt.Type == sf::Event::KeyReleased )
			{
				mInputManager->keyUp( lEvt.Key.Code );
				mGame->keyUp( lEvt.Key.Code );
			}

			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::R) ) {
					if(mRenderer->getRenderMode() == Renderer::RENDER_SOLID)
						mRenderer->setRenderMode(Renderer::RENDER_LIGHTING);
					else
						mRenderer->setRenderMode(Renderer::RENDER_SOLID);
			}

			//==========
			//= Debug Buttons
			//==========
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F1 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_OFF );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F3 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_STATS );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F4 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_PHYSICS );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F5 ) ) {
				mRenderer->setDebugMode( Renderer::DEBUG_LINES );
			}
			if( (lEvt.Type == sf::Event::KeyReleased ) &&
				(lEvt.Key.Code == sf::Keyboard::F6 ) ) {
				Util::setLogLevel( Util::Verbose );
			}
			if( (lEvt.Type == sf::Event::KeyReleased) &&
				(lEvt.Key.Code == sf::Keyboard::F) ) {
					//mPlayer->enableFlying( !mPlayer->isFlying() );
					//Util::log( (Util::toString(mPlayer->isFlying())) + " Flying");
			}
			if( (lEvt.Type == sf::Event::KeyReleased) &&
				(lEvt.Key.Code == sf::Keyboard::F) ) {
					//mPlayer->enableFlying( !mPlayer->isFlying() );
					//Util::log( (Util::toString(mPlayer->isFlying())) + " Flying");
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Add) ) {
					mRenderer->nextBlock();
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Num9) ) {
					mTimescale *= 0.5f;
			}
			if( (lEvt.Type == sf::Event::KeyPressed) &&
				(lEvt.Key.Code == sf::Keyboard::Num0) ) {
					mTimescale *= 2.f;
			}
			if( (lEvt.Type == sf::Event::MouseMoved) ) {
					mGame->_mouseMoved( -(lEvt.MouseMove.X - lastX), -(lEvt.MouseMove.Y  - lastY));
					lastX = lEvt.MouseMove.X;
					lastY = lEvt.MouseMove.Y;
			}
			if( (lEvt.Type == sf::Event::MouseLeft) ) {
					sf::Mouse::SetPosition( sf::Vector2i( mWindow.GetWidth() / 2, mWindow.GetHeight() / 2), mWindow );
			}
			if( lEvt.Type == sf::Event::MouseButtonPressed && lEvt.MouseButton.Button == sf::Mouse::Left ) {
				mGame->_primary();
			}
			if( lEvt.Type == sf::Event::MouseButtonPressed && lEvt.MouseButton.Button == sf::Mouse::Right ) {
				mGame->_secondary();
			}
			if( lEvt.Type == sf::Event::Resized ) {
				mRenderer->resizeViewport( 0, 0, lEvt.Size.Width, lEvt.Size.Height );
			}
		}

		lDelta *= mTimescale;

		mPhysicsWorld->stepSimulation( lDelta );

		if( mGame != NULL )
		{
			mGame->think( lDelta );
		}

		//Ensure each loaded chunk is updated before being sent to the GPU
		mWorld->update( lDelta );

		// Update all the characters
		for( std::vector<Character*>::iterator it = mCharacters.begin(); it != mCharacters.end(); it++ )
		{
			(*it)->update( lDelta );
		}

		//Ensure the renderer has the correct camera
		mRenderer->setCamera( mGame->getLocalPlayer()->getCamera() );
		mRenderer->render(lDelta, mWorld);

		mGame->uiPaint( mRenderer );

		mWindow.Display();
	}

	mWindow.Close();

}

void MagnetiteCore::exit()
{
	mContinue = false;
}

TextureManager* MagnetiteCore::getTextureManager()
{
	return mTextureManager;
}

ResourceManager* MagnetiteCore::getResourceManager()
{
	return mResourceManager;
}

Renderer* MagnetiteCore::getRenderer()
{
	return mRenderer;
}

ScriptWrapper* MagnetiteCore::getScriptManager()
{
	return mScriptWrapper;
}

BaseGame* MagnetiteCore::getGame()
{
	return mGame;
}

float MagnetiteCore::getTimescale()
{
	return mTimescale;
}

void MagnetiteCore::newWorld( std::string name )
{
	unloadWorld();

	mWorld = new World( 5 );
	//mWorld->newWorld( name );
}

void MagnetiteCore::unloadWorld()
{
	if( mWorld != NULL ) {
		// world handles saving.
		delete mWorld;
	}
	mWorld = NULL;
}

World* MagnetiteCore::getWorld()
{
	return mWorld;
}

Character* MagnetiteCore::createCharacter()
{
	Character* c = new Character();
	mCharacters.push_back( c );
	return c;
}

void MagnetiteCore::destroyCharacter( Character* c )
{
	for( std::vector<Character*>::iterator it = mCharacters.begin(); it != mCharacters.end(); it++ ) {
		if( c == (*it) )
			mCharacters.erase( it++ );
	}
}

<|endoftext|>


<commit_before>/**
 * @file    Statement.cpp
 * @ingroup SQLiteCpp
 * @brief   A prepared SQLite Statement is a compiled SQL query ready to be executed, pointing to a row of result.
 *
 * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#include <SQLiteCpp/Statement.h>

#include <SQLiteCpp/Database.h>
#include <SQLiteCpp/Column.h>
#include <SQLiteCpp/Assertion.h>
#include <SQLiteCpp/Exception.h>

#include <string>

namespace SQLite
{

// Compile and register the SQL query for the provided SQLite Database Connection
Statement::Statement(Database &aDatabase, const char* apQuery) :
    mQuery(apQuery),
    mStmtPtr(aDatabase.mpSQLite, mQuery), // prepare the SQL query, and ref count (needs Database friendship)
    mColumnCount(0),
    mbOk(false),
    mbDone(false)
{
    mColumnCount = sqlite3_column_count(mStmtPtr);
}

// Compile and register the SQL query for the provided SQLite Database Connection
Statement::Statement(Database &aDatabase, const std::string& aQuery) :
    mQuery(aQuery),
    mStmtPtr(aDatabase.mpSQLite, mQuery), // prepare the SQL query, and ref count (needs Database friendship)
    mColumnCount(0),
    mbOk(false),
    mbDone(false)
{
    mColumnCount = sqlite3_column_count(mStmtPtr);
}

// Finalize and unregister the SQL query from the SQLite Database Connection.
Statement::~Statement() noexcept // nothrow
{
    // the finalization will be done by the destructor of the last shared pointer
}

// Reset the statement to make it ready for a new execution
void Statement::reset()
{
    mbOk = false;
    mbDone = false;
    int ret = sqlite3_reset(mStmtPtr);
    check(ret);
}

// Clears away all the bindings of a prepared statement.
// "Contrary to the intuition of many, [sqlite3_reset()] does not reset
//    ** the [sqlite3_bind_blob | bindings] on a [prepared statement]."
void Statement::clearBindings(void)
{
    mbOk = false;
    mbDone = false;
    int ret = sqlite3_clear_bindings(mStmtPtr);
    check(ret);
}

// Bind an int value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const int& aValue)
{
    int ret = sqlite3_bind_int(mStmtPtr, aIndex, aValue);
    check(ret);
}

// Bind a 64bits int value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const sqlite3_int64& aValue)
{
    int ret = sqlite3_bind_int64(mStmtPtr, aIndex, aValue);
    check(ret);
}

// Bind a double (64bits float) value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const double& aValue)
{
    int ret = sqlite3_bind_double(mStmtPtr, aIndex, aValue);
    check(ret);
}

// Bind a string value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const std::string& aValue)
{
    int ret = sqlite3_bind_text(mStmtPtr, aIndex, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}

// Bind a text value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const char* apValue)
{
    int ret = sqlite3_bind_text(mStmtPtr, aIndex, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a binary blob value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const void* apValue, const int aSize)
{
    int ret = sqlite3_bind_blob(mStmtPtr, aIndex, apValue, aSize, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a NULL value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex)
{
    int ret = sqlite3_bind_null(mStmtPtr, aIndex);
    check(ret);
}

// Bind an int value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const int& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_int(mStmtPtr, index, aValue);
    check(ret);
}

// Bind a 64bits int value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const sqlite3_int64& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_int64(mStmtPtr, index, aValue);
    check(ret);
}

// Bind a double (64bits float) value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const double& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_double(mStmtPtr, index, aValue);
    check(ret);
}

// Bind a string value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const std::string& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}

// Bind a text value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const char* apValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a binary blob value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const void* apValue, const int aSize)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_blob(mStmtPtr, index, apValue, aSize, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a NULL value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_null(mStmtPtr, index);
    check(ret);
}

// Execute a step of the query to fetch one row of results
bool Statement::executeStep()
{
    if (false == mbDone)
    {
        int ret = sqlite3_step(mStmtPtr);
        if (SQLITE_ROW == ret) // one row is ready : call getColumn(N) to access it
        {
            mbOk = true;
        }
        else if (SQLITE_DONE == ret) // no (more) row ready : the query has finished executing
        {
            mbOk = false;
            mbDone = true;
        }
        else
        {
            mbOk = false;
            mbDone = false;
            throw SQLite::Exception(sqlite3_errmsg(mStmtPtr));
        }
    }
    else
    {
        throw SQLite::Exception("Statement needs to be reset");
    }

    return mbOk; // true only if one row is accessible by getColumn(N)
}

// Execute a one-step query with no expected result
int Statement::exec()
{
    if (false == mbDone)
    {
        int ret = sqlite3_step(mStmtPtr);
        if (SQLITE_DONE == ret) // the statement has finished executing successfully
        {
            mbOk = false;
            mbDone = true;
        }
        else if (SQLITE_ROW == ret)
        {
            mbOk = false;
            mbDone = false;
            throw SQLite::Exception("exec() does not expect results");
        }
        else
        {
            mbOk = false;
            mbDone = false;
            throw SQLite::Exception(sqlite3_errmsg(mStmtPtr));
        }
    }
    else
    {
        throw SQLite::Exception("Statement need to be reseted");
    }

    // Return the number of rows modified by those SQL statements (INSERT, UPDATE or DELETE)
    return sqlite3_changes(mStmtPtr);
}

// Return a copy of the column data specified by its index starting at 0
// (use the Column copy-constructor)
Column Statement::getColumn(const int aIndex)
{
    if (false == mbOk)
    {
        throw SQLite::Exception("No row to get a column from");
    }
    else if ((aIndex < 0) || (aIndex >= mColumnCount))
    {
        throw SQLite::Exception("Column index out of range");
    }

    // Share the Statement Object handle with the new Column created
    return Column(mStmtPtr, aIndex);
}

// Return a copy of the column data specified by its column name starting at 0
// (use the Column copy-constructor)
Column  Statement::getColumn(const char* aName)
{
    int aIndex = -1;

    if (false == mbOk)
    {
        throw SQLite::Exception("No row to get a column from");
    }
    else
    {
        for (int i = 0; i < mColumnCount; i++) {
            if (sqlite3_column_name(mStmtPtr, i) == aName)
                break;
        }

        if ((aIndex < 0) || (aIndex >= mColumnCount)) {
            throw SQLite::Exception("Column index out of range");
        }

    }

    // Share the Statement Object handle with the new Column created
    return Column(mStmtPtr, aIndex);
}

// Test if the column is NULL
bool Statement::isColumnNull(const int aIndex) const
{
    if (false == mbOk)
    {
        throw SQLite::Exception("No row to get a column from");
    }
    else if ((aIndex < 0) || (aIndex >= mColumnCount))
    {
        throw SQLite::Exception("Column index out of range");
    }

    return (SQLITE_NULL == sqlite3_column_type(mStmtPtr, aIndex));
}

// Check if aRet equal SQLITE_OK, else throw a SQLite::Exception with the SQLite error message
void Statement::check(const int aRet)
{
    if (SQLITE_OK != aRet)
    {
        throw SQLite::Exception(sqlite3_errmsg(mStmtPtr));
    }
}

////////////////////////////////////////////////////////////////////////////////
// Internal class : shared pointer to the sqlite3_stmt SQLite Statement Object
////////////////////////////////////////////////////////////////////////////////

/**
 * @brief Prepare the statement and initialize its reference counter
 *
 * @param[in] apSQLite  The sqlite3 database connexion
 * @param[in] aQuery    The SQL query string to prepare
 */
Statement::Ptr::Ptr(sqlite3* apSQLite, std::string& aQuery) :
    mpSQLite(apSQLite),
    mpStmt(NULL),
    mpRefCount(NULL)
{
    int ret = sqlite3_prepare_v2(apSQLite, aQuery.c_str(), static_cast<int>(aQuery.size()), &mpStmt, NULL);
    if (SQLITE_OK != ret)
    {
        throw SQLite::Exception(sqlite3_errmsg(mpSQLite));
    }
    // Initialize the reference counter of the sqlite3_stmt :
    // used to share the mStmtPtr between Statement and Column objects;
    // This is needed to enable Column objects to live longer than the Statement objet it refers to.
    mpRefCount = new unsigned int(1);  // NOLINT(readability/casting)
}

/**
 * @brief Copy constructor increments the ref counter
 *
 * @param[in] aPtr Pointer to copy
 */
Statement::Ptr::Ptr(const Statement::Ptr& aPtr) :
    mpSQLite(aPtr.mpSQLite),
    mpStmt(aPtr.mpStmt),
    mpRefCount(aPtr.mpRefCount)
{
    assert(NULL != mpRefCount);
    assert(0 != *mpRefCount);

    // Increment the reference counter of the sqlite3_stmt,
    // asking not to finalize the sqlite3_stmt during the lifetime of the new objet
    ++(*mpRefCount);
}

/**
 * @brief Decrement the ref counter and finalize the sqlite3_stmt when it reaches 0
 */
Statement::Ptr::~Ptr() noexcept // nothrow
{
    assert(NULL != mpRefCount);
    assert(0 != *mpRefCount);

    // Decrement and check the reference counter of the sqlite3_stmt
    --(*mpRefCount);
    if (0 == *mpRefCount)
    {
        // If count reaches zero, finalize the sqlite3_stmt, as no Statement nor Column objet use it anymore.
        // No need to check the return code, as it is the same as the last statement evaluation.
        sqlite3_finalize(mpStmt);

        // and delete the reference counter
        delete mpRefCount;
        mpRefCount = NULL;
        mpStmt = NULL;
    }
    // else, the finalization will be done later, by the last object
}

}  // namespace SQLite
<commit_msg>Fix cpplint style warning introduced by #45<commit_after>/**
 * @file    Statement.cpp
 * @ingroup SQLiteCpp
 * @brief   A prepared SQLite Statement is a compiled SQL query ready to be executed, pointing to a row of result.
 *
 * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#include <SQLiteCpp/Statement.h>

#include <SQLiteCpp/Database.h>
#include <SQLiteCpp/Column.h>
#include <SQLiteCpp/Assertion.h>
#include <SQLiteCpp/Exception.h>

#include <string>

namespace SQLite
{

// Compile and register the SQL query for the provided SQLite Database Connection
Statement::Statement(Database &aDatabase, const char* apQuery) :
    mQuery(apQuery),
    mStmtPtr(aDatabase.mpSQLite, mQuery), // prepare the SQL query, and ref count (needs Database friendship)
    mColumnCount(0),
    mbOk(false),
    mbDone(false)
{
    mColumnCount = sqlite3_column_count(mStmtPtr);
}

// Compile and register the SQL query for the provided SQLite Database Connection
Statement::Statement(Database &aDatabase, const std::string& aQuery) :
    mQuery(aQuery),
    mStmtPtr(aDatabase.mpSQLite, mQuery), // prepare the SQL query, and ref count (needs Database friendship)
    mColumnCount(0),
    mbOk(false),
    mbDone(false)
{
    mColumnCount = sqlite3_column_count(mStmtPtr);
}

// Finalize and unregister the SQL query from the SQLite Database Connection.
Statement::~Statement() noexcept // nothrow
{
    // the finalization will be done by the destructor of the last shared pointer
}

// Reset the statement to make it ready for a new execution
void Statement::reset()
{
    mbOk = false;
    mbDone = false;
    int ret = sqlite3_reset(mStmtPtr);
    check(ret);
}

// Clears away all the bindings of a prepared statement.
// "Contrary to the intuition of many, [sqlite3_reset()] does not reset
//    ** the [sqlite3_bind_blob | bindings] on a [prepared statement]."
void Statement::clearBindings(void)
{
    mbOk = false;
    mbDone = false;
    int ret = sqlite3_clear_bindings(mStmtPtr);
    check(ret);
}

// Bind an int value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const int& aValue)
{
    int ret = sqlite3_bind_int(mStmtPtr, aIndex, aValue);
    check(ret);
}

// Bind a 64bits int value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const sqlite3_int64& aValue)
{
    int ret = sqlite3_bind_int64(mStmtPtr, aIndex, aValue);
    check(ret);
}

// Bind a double (64bits float) value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const double& aValue)
{
    int ret = sqlite3_bind_double(mStmtPtr, aIndex, aValue);
    check(ret);
}

// Bind a string value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const std::string& aValue)
{
    int ret = sqlite3_bind_text(mStmtPtr, aIndex, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}

// Bind a text value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const char* apValue)
{
    int ret = sqlite3_bind_text(mStmtPtr, aIndex, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a binary blob value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const void* apValue, const int aSize)
{
    int ret = sqlite3_bind_blob(mStmtPtr, aIndex, apValue, aSize, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a NULL value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex)
{
    int ret = sqlite3_bind_null(mStmtPtr, aIndex);
    check(ret);
}

// Bind an int value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const int& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_int(mStmtPtr, index, aValue);
    check(ret);
}

// Bind a 64bits int value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const sqlite3_int64& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_int64(mStmtPtr, index, aValue);
    check(ret);
}

// Bind a double (64bits float) value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const double& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_double(mStmtPtr, index, aValue);
    check(ret);
}

// Bind a string value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const std::string& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}

// Bind a text value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const char* apValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a binary blob value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const void* apValue, const int aSize)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_blob(mStmtPtr, index, apValue, aSize, SQLITE_TRANSIENT);
    check(ret);
}

// Bind a NULL value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_null(mStmtPtr, index);
    check(ret);
}

// Execute a step of the query to fetch one row of results
bool Statement::executeStep()
{
    if (false == mbDone)
    {
        int ret = sqlite3_step(mStmtPtr);
        if (SQLITE_ROW == ret) // one row is ready : call getColumn(N) to access it
        {
            mbOk = true;
        }
        else if (SQLITE_DONE == ret) // no (more) row ready : the query has finished executing
        {
            mbOk = false;
            mbDone = true;
        }
        else
        {
            mbOk = false;
            mbDone = false;
            throw SQLite::Exception(sqlite3_errmsg(mStmtPtr));
        }
    }
    else
    {
        throw SQLite::Exception("Statement needs to be reset");
    }

    return mbOk; // true only if one row is accessible by getColumn(N)
}

// Execute a one-step query with no expected result
int Statement::exec()
{
    if (false == mbDone)
    {
        int ret = sqlite3_step(mStmtPtr);
        if (SQLITE_DONE == ret) // the statement has finished executing successfully
        {
            mbOk = false;
            mbDone = true;
        }
        else if (SQLITE_ROW == ret)
        {
            mbOk = false;
            mbDone = false;
            throw SQLite::Exception("exec() does not expect results");
        }
        else
        {
            mbOk = false;
            mbDone = false;
            throw SQLite::Exception(sqlite3_errmsg(mStmtPtr));
        }
    }
    else
    {
        throw SQLite::Exception("Statement need to be reseted");
    }

    // Return the number of rows modified by those SQL statements (INSERT, UPDATE or DELETE)
    return sqlite3_changes(mStmtPtr);
}

// Return a copy of the column data specified by its index starting at 0
// (use the Column copy-constructor)
Column Statement::getColumn(const int aIndex)
{
    if (false == mbOk)
    {
        throw SQLite::Exception("No row to get a column from");
    }
    else if ((aIndex < 0) || (aIndex >= mColumnCount))
    {
        throw SQLite::Exception("Column index out of range");
    }

    // Share the Statement Object handle with the new Column created
    return Column(mStmtPtr, aIndex);
}

// Return a copy of the column data specified by its column name starting at 0
// (use the Column copy-constructor)
Column  Statement::getColumn(const char* aName)
{
    int aIndex = -1;

    if (false == mbOk)
    {
        throw SQLite::Exception("No row to get a column from");
    }
    else
    {
        for (int i = 0; i < mColumnCount; ++i) {
            if (sqlite3_column_name(mStmtPtr, i) == aName)
                break;
        }

        if ((aIndex < 0) || (aIndex >= mColumnCount)) {
            throw SQLite::Exception("Column index out of range");
        }
    }

    // Share the Statement Object handle with the new Column created
    return Column(mStmtPtr, aIndex);
}

// Test if the column is NULL
bool Statement::isColumnNull(const int aIndex) const
{
    if (false == mbOk)
    {
        throw SQLite::Exception("No row to get a column from");
    }
    else if ((aIndex < 0) || (aIndex >= mColumnCount))
    {
        throw SQLite::Exception("Column index out of range");
    }

    return (SQLITE_NULL == sqlite3_column_type(mStmtPtr, aIndex));
}

// Check if aRet equal SQLITE_OK, else throw a SQLite::Exception with the SQLite error message
void Statement::check(const int aRet)
{
    if (SQLITE_OK != aRet)
    {
        throw SQLite::Exception(sqlite3_errmsg(mStmtPtr));
    }
}

////////////////////////////////////////////////////////////////////////////////
// Internal class : shared pointer to the sqlite3_stmt SQLite Statement Object
////////////////////////////////////////////////////////////////////////////////

/**
 * @brief Prepare the statement and initialize its reference counter
 *
 * @param[in] apSQLite  The sqlite3 database connexion
 * @param[in] aQuery    The SQL query string to prepare
 */
Statement::Ptr::Ptr(sqlite3* apSQLite, std::string& aQuery) :
    mpSQLite(apSQLite),
    mpStmt(NULL),
    mpRefCount(NULL)
{
    int ret = sqlite3_prepare_v2(apSQLite, aQuery.c_str(), static_cast<int>(aQuery.size()), &mpStmt, NULL);
    if (SQLITE_OK != ret)
    {
        throw SQLite::Exception(sqlite3_errmsg(mpSQLite));
    }
    // Initialize the reference counter of the sqlite3_stmt :
    // used to share the mStmtPtr between Statement and Column objects;
    // This is needed to enable Column objects to live longer than the Statement objet it refers to.
    mpRefCount = new unsigned int(1);  // NOLINT(readability/casting)
}

/**
 * @brief Copy constructor increments the ref counter
 *
 * @param[in] aPtr Pointer to copy
 */
Statement::Ptr::Ptr(const Statement::Ptr& aPtr) :
    mpSQLite(aPtr.mpSQLite),
    mpStmt(aPtr.mpStmt),
    mpRefCount(aPtr.mpRefCount)
{
    assert(NULL != mpRefCount);
    assert(0 != *mpRefCount);

    // Increment the reference counter of the sqlite3_stmt,
    // asking not to finalize the sqlite3_stmt during the lifetime of the new objet
    ++(*mpRefCount);
}

/**
 * @brief Decrement the ref counter and finalize the sqlite3_stmt when it reaches 0
 */
Statement::Ptr::~Ptr() noexcept // nothrow
{
    assert(NULL != mpRefCount);
    assert(0 != *mpRefCount);

    // Decrement and check the reference counter of the sqlite3_stmt
    --(*mpRefCount);
    if (0 == *mpRefCount)
    {
        // If count reaches zero, finalize the sqlite3_stmt, as no Statement nor Column objet use it anymore.
        // No need to check the return code, as it is the same as the last statement evaluation.
        sqlite3_finalize(mpStmt);

        // and delete the reference counter
        delete mpRefCount;
        mpRefCount = NULL;
        mpStmt = NULL;
    }
    // else, the finalization will be done later, by the last object
}

}  // namespace SQLite
<|endoftext|>


<commit_before><commit_msg>Drop unused variable<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fontcfg.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-08 15:33:28 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _FONTCFG_HXX
#include <fontcfg.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SVTOOLS_LINGUCFG_HXX_
#include <svtools/lingucfg.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif

// #107253#
#ifndef _SWLINGUCONFIG_HXX
#include <swlinguconfig.hxx>
#endif

using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

#define C2S(cChar) String::CreateFromAscii(cChar)
#define C2U(cChar) OUString::createFromAscii(cChar)
/* -----------------07.10.2002 12:15-----------------
 *
 * --------------------------------------------------*/
inline LanguageType lcl_LanguageOfType(sal_Int16 nType, sal_Int16 eWestern, sal_Int16 eCJK, sal_Int16 eCTL)
{
    return LanguageType(
                nType < FONT_STANDARD_CJK ? eWestern :
                    nType >= FONT_STANDARD_CTL ? eCTL : eWestern);
}
/* -----------------------------08.09.00 15:52--------------------------------

 ---------------------------------------------------------------------------*/
Sequence<OUString> SwStdFontConfig::GetPropertyNames()
{
    static const char* aPropNames[] =
    {
        "DefaultFont/Standard",    // 0
        "DefaultFont/Heading",     // 1
        "DefaultFont/List",        // 2
        "DefaultFont/Caption",     // 3
        "DefaultFont/Index",       // 4
        "DefaultFontCJK/Standard", // 5
        "DefaultFontCJK/Heading",  // 6
        "DefaultFontCJK/List",     // 7
        "DefaultFontCJK/Caption",  // 8
        "DefaultFontCJK/Index",    // 9
        "DefaultFontCTL/Standard", // 10
        "DefaultFontCTL/Heading",  // 11
        "DefaultFontCTL/List",     // 12
        "DefaultFontCTL/Caption",  // 13
        "DefaultFontCTL/Index",    // 14
    };
    const int nCount = 15;
    Sequence<OUString> aNames(nCount);
    OUString* pNames = aNames.getArray();
    for(int i = 0; i < nCount; i++)
    {
        pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/*-----------------03.09.96 15.00-------------------

--------------------------------------------------*/

SwStdFontConfig::SwStdFontConfig() :
    utl::ConfigItem(C2U("Office.Writer"))
{
    SvtLinguOptions aLinguOpt;

    // #107253# Replaced SvtLinguConfig with SwLinguConfig wrapper with UsageCount
    SwLinguConfig().GetOptions( aLinguOpt );

    sal_Int16   eWestern = aLinguOpt.nDefaultLanguage,
                eCJK = aLinguOpt.nDefaultLanguage_CJK,
                eCTL = aLinguOpt.nDefaultLanguage_CTL;
    for(sal_Int16 i = 0; i < DEF_FONT_COUNT; i++)
        sDefaultFonts[i] = GetDefaultFor(i,
            lcl_LanguageOfType(i, eWestern, eCJK, eCTL));

    Sequence<OUString> aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                OUString sVal;
                pValues[nProp] >>= sVal;
                sDefaultFonts[nProp] = sVal;
            }
        }
    }
}
/* -----------------------------08.09.00 15:58--------------------------------

 ---------------------------------------------------------------------------*/
void    SwStdFontConfig::Commit()
{
    Sequence<OUString> aNames = GetPropertyNames();
    OUString* pNames = aNames.getArray();
    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();
    SvtLinguOptions aLinguOpt;

    // #107253# Replaced SvtLinguConfig with SwLinguConfig wrapper with UsageCount
    SwLinguConfig().GetOptions( aLinguOpt );

    sal_Int16   eWestern = aLinguOpt.nDefaultLanguage,
                eCJK = aLinguOpt.nDefaultLanguage_CJK,
                eCTL = aLinguOpt.nDefaultLanguage_CTL;
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        if(GetDefaultFor(nProp, lcl_LanguageOfType(nProp, eWestern, eCJK, eCTL)) != sDefaultFonts[nProp])
                pValues[nProp] <<= OUString(sDefaultFonts[nProp]);
    }
    PutProperties(aNames, aValues);
}
/* -----------------------------08.09.00 15:56--------------------------------

 ---------------------------------------------------------------------------*/
SwStdFontConfig::~SwStdFontConfig()
{}
/*-----------------18.01.97 10.05-------------------

--------------------------------------------------*/
BOOL SwStdFontConfig::IsFontDefault(USHORT nFontType) const
{
    BOOL bSame;
    SvtLinguOptions aLinguOpt;

    // #107253# Replaced SvtLinguConfig with SwLinguConfig wrapper with UsageCount
    SwLinguConfig().GetOptions( aLinguOpt );

    sal_Int16   eWestern = aLinguOpt.nDefaultLanguage,
                eCJK = aLinguOpt.nDefaultLanguage_CJK,
                eCTL = aLinguOpt.nDefaultLanguage_CTL;
    String sDefFont(GetDefaultFor(FONT_STANDARD, eWestern));
    String sDefFontCJK(GetDefaultFor(FONT_STANDARD_CJK, eCJK));
    String sDefFontCTL(GetDefaultFor(FONT_STANDARD_CTL, eCTL));
    LanguageType eLang = lcl_LanguageOfType(nFontType, eWestern, eCJK, eCTL);
    switch( nFontType )
    {
        case FONT_STANDARD:
            bSame = sDefaultFonts[nFontType] == sDefFont;
        break;
        case FONT_STANDARD_CJK:
            bSame = sDefaultFonts[nFontType] == sDefFontCJK;
        break;
        case FONT_STANDARD_CTL:
            bSame = sDefaultFonts[nFontType] == sDefFontCTL;
        break;
        case FONT_OUTLINE :
        case FONT_OUTLINE_CJK :
        case FONT_OUTLINE_CTL :
            bSame = sDefaultFonts[nFontType] ==
                GetDefaultFor(nFontType, eLang);
        break;
        case FONT_LIST    :
        case FONT_CAPTION :
        case FONT_INDEX   :
            bSame = sDefaultFonts[nFontType] == sDefFont &&
                    sDefaultFonts[FONT_STANDARD] == sDefFont;
        break;
        case FONT_LIST_CJK    :
        case FONT_CAPTION_CJK :
        case FONT_INDEX_CJK   :
        {
            BOOL b1 = sDefaultFonts[FONT_STANDARD_CJK] == sDefFontCJK;
            bSame = b1 && sDefaultFonts[nFontType] == sDefFontCJK;
        }
        break;
        case FONT_LIST_CTL    :
        case FONT_CAPTION_CTL :
        case FONT_INDEX_CTL   :
        {
            BOOL b1 = sDefaultFonts[FONT_STANDARD_CJK] == sDefFontCTL;
            bSame = b1 && sDefaultFonts[nFontType] == sDefFontCTL;
        }
        break;
    }
    return bSame;
}

/* -----------------11.01.99 13:16-------------------
 * Standards auslesen
 * --------------------------------------------------*/
String  SwStdFontConfig::GetDefaultFor(USHORT nFontType, LanguageType eLang)
{
    String sRet;
    USHORT nFontId;
    switch( nFontType )
    {
        case FONT_OUTLINE :
            nFontId = DEFAULTFONT_LATIN_HEADING;
        break;
        case FONT_OUTLINE_CJK :
            nFontId = DEFAULTFONT_CJK_HEADING;
        break;
        case FONT_OUTLINE_CTL :
            nFontId = DEFAULTFONT_CTL_HEADING;
        break;
        case FONT_STANDARD_CJK:
        case FONT_LIST_CJK    :
        case FONT_CAPTION_CJK :
        case FONT_INDEX_CJK   :
            nFontId = DEFAULTFONT_CJK_TEXT;
        break;
        case FONT_STANDARD_CTL:
        case FONT_LIST_CTL    :
        case FONT_CAPTION_CTL :
        case FONT_INDEX_CTL   :
            nFontId = DEFAULTFONT_CTL_TEXT;
        break;
//        case FONT_STANDARD:
//        case FONT_LIST    :
//        case FONT_CAPTION :
//        case FONT_INDEX   :
        default:
            nFontId = DEFAULTFONT_LATIN_TEXT;
    }
    Font aFont = OutputDevice::GetDefaultFont(nFontId, eLang, DEFAULTFONT_FLAGS_ONLYONE);
    return  aFont.GetName();
}
<commit_msg>INTEGRATION: CWS os8 (1.12.142); FILE MERGED 2003/04/03 07:13:44 os 1.12.142.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
 *
 *  $RCSfile: fontcfg.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:17:42 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _FONTCFG_HXX
#include <fontcfg.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SVTOOLS_LINGUCFG_HXX_
#include <svtools/lingucfg.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif

// #107253#
#ifndef _SWLINGUCONFIG_HXX
#include <swlinguconfig.hxx>
#endif

using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

#define C2S(cChar) String::CreateFromAscii(cChar)
#define C2U(cChar) OUString::createFromAscii(cChar)
/* -----------------07.10.2002 12:15-----------------
 *
 * --------------------------------------------------*/
inline LanguageType lcl_LanguageOfType(sal_Int16 nType, sal_Int16 eWestern, sal_Int16 eCJK, sal_Int16 eCTL)
{
    return LanguageType(
                nType < FONT_STANDARD_CJK ? eWestern :
                    nType >= FONT_STANDARD_CTL ? eCTL : eWestern);
}
/* -----------------------------08.09.00 15:52--------------------------------

 ---------------------------------------------------------------------------*/
Sequence<OUString> SwStdFontConfig::GetPropertyNames()
{
    static const char* aPropNames[] =
    {
        "DefaultFont/Standard",    // 0
        "DefaultFont/Heading",     // 1
        "DefaultFont/List",        // 2
        "DefaultFont/Caption",     // 3
        "DefaultFont/Index",       // 4
        "DefaultFontCJK/Standard", // 5
        "DefaultFontCJK/Heading",  // 6
        "DefaultFontCJK/List",     // 7
        "DefaultFontCJK/Caption",  // 8
        "DefaultFontCJK/Index",    // 9
        "DefaultFontCTL/Standard", // 10
        "DefaultFontCTL/Heading",  // 11
        "DefaultFontCTL/List",     // 12
        "DefaultFontCTL/Caption",  // 13
        "DefaultFontCTL/Index",    // 14
    };
    const int nCount = 15;
    Sequence<OUString> aNames(nCount);
    OUString* pNames = aNames.getArray();
    for(int i = 0; i < nCount; i++)
    {
        pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/*-----------------03.09.96 15.00-------------------

--------------------------------------------------*/

SwStdFontConfig::SwStdFontConfig() :
    utl::ConfigItem(C2U("Office.Writer"))
{
    SvtLinguOptions aLinguOpt;

    // #107253# Replaced SvtLinguConfig with SwLinguConfig wrapper with UsageCount
    SwLinguConfig().GetOptions( aLinguOpt );

    sal_Int16   eWestern = aLinguOpt.nDefaultLanguage,
                eCJK = aLinguOpt.nDefaultLanguage_CJK,
                eCTL = aLinguOpt.nDefaultLanguage_CTL;
    for(sal_Int16 i = 0; i < DEF_FONT_COUNT; i++)
        sDefaultFonts[i] = GetDefaultFor(i,
            lcl_LanguageOfType(i, eWestern, eCJK, eCTL));

    Sequence<OUString> aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                OUString sVal;
                pValues[nProp] >>= sVal;
                sDefaultFonts[nProp] = sVal;
            }
        }
    }
}
/* -----------------------------08.09.00 15:58--------------------------------

 ---------------------------------------------------------------------------*/
void    SwStdFontConfig::Commit()
{
    Sequence<OUString> aNames = GetPropertyNames();
    OUString* pNames = aNames.getArray();
    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();
    SvtLinguOptions aLinguOpt;

    // #107253# Replaced SvtLinguConfig with SwLinguConfig wrapper with UsageCount
    SwLinguConfig().GetOptions( aLinguOpt );

    sal_Int16   eWestern = aLinguOpt.nDefaultLanguage,
                eCJK = aLinguOpt.nDefaultLanguage_CJK,
                eCTL = aLinguOpt.nDefaultLanguage_CTL;
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        if(GetDefaultFor(nProp, lcl_LanguageOfType(nProp, eWestern, eCJK, eCTL)) != sDefaultFonts[nProp])
                pValues[nProp] <<= OUString(sDefaultFonts[nProp]);
    }
    PutProperties(aNames, aValues);
}
/* -----------------------------08.09.00 15:56--------------------------------

 ---------------------------------------------------------------------------*/
SwStdFontConfig::~SwStdFontConfig()
{}
/*-----------------18.01.97 10.05-------------------

--------------------------------------------------*/
BOOL SwStdFontConfig::IsFontDefault(USHORT nFontType) const
{
    BOOL bSame;
    SvtLinguOptions aLinguOpt;

    // #107253# Replaced SvtLinguConfig with SwLinguConfig wrapper with UsageCount
    SwLinguConfig().GetOptions( aLinguOpt );

    sal_Int16   eWestern = aLinguOpt.nDefaultLanguage,
                eCJK = aLinguOpt.nDefaultLanguage_CJK,
                eCTL = aLinguOpt.nDefaultLanguage_CTL;
    String sDefFont(GetDefaultFor(FONT_STANDARD, eWestern));
    String sDefFontCJK(GetDefaultFor(FONT_STANDARD_CJK, eCJK));
    String sDefFontCTL(GetDefaultFor(FONT_STANDARD_CTL, eCTL));
    LanguageType eLang = lcl_LanguageOfType(nFontType, eWestern, eCJK, eCTL);
    switch( nFontType )
    {
        case FONT_STANDARD:
            bSame = sDefaultFonts[nFontType] == sDefFont;
        break;
        case FONT_STANDARD_CJK:
            bSame = sDefaultFonts[nFontType] == sDefFontCJK;
        break;
        case FONT_STANDARD_CTL:
            bSame = sDefaultFonts[nFontType] == sDefFontCTL;
        break;
        case FONT_OUTLINE :
        case FONT_OUTLINE_CJK :
        case FONT_OUTLINE_CTL :
            bSame = sDefaultFonts[nFontType] ==
                GetDefaultFor(nFontType, eLang);
        break;
        case FONT_LIST    :
        case FONT_CAPTION :
        case FONT_INDEX   :
            bSame = sDefaultFonts[nFontType] == sDefFont &&
                    sDefaultFonts[FONT_STANDARD] == sDefFont;
        break;
        case FONT_LIST_CJK    :
        case FONT_CAPTION_CJK :
        case FONT_INDEX_CJK   :
        {
            BOOL b1 = sDefaultFonts[FONT_STANDARD_CJK] == sDefFontCJK;
            bSame = b1 && sDefaultFonts[nFontType] == sDefFontCJK;
        }
        break;
        case FONT_LIST_CTL    :
        case FONT_CAPTION_CTL :
        case FONT_INDEX_CTL   :
        {
            BOOL b1 = sDefaultFonts[FONT_STANDARD_CJK] == sDefFontCTL;
            bSame = b1 && sDefaultFonts[nFontType] == sDefFontCTL;
        }
        break;
    }
    return bSame;
}

/* -----------------11.01.99 13:16-------------------
 * Standards auslesen
 * --------------------------------------------------*/
String  SwStdFontConfig::GetDefaultFor(USHORT nFontType, LanguageType eLang)
{
    String sRet;
    USHORT nFontId;
    switch( nFontType )
    {
        case FONT_OUTLINE :
            nFontId = DEFAULTFONT_LATIN_HEADING;
        break;
        case FONT_OUTLINE_CJK :
            nFontId = DEFAULTFONT_CJK_HEADING;
        break;
        case FONT_OUTLINE_CTL :
            nFontId = DEFAULTFONT_CTL_HEADING;
        break;
        case FONT_STANDARD_CJK:
        case FONT_LIST_CJK    :
        case FONT_CAPTION_CJK :
        case FONT_INDEX_CJK   :
            nFontId = DEFAULTFONT_CJK_TEXT;
        break;
        case FONT_STANDARD_CTL:
        case FONT_LIST_CTL    :
        case FONT_CAPTION_CTL :
        case FONT_INDEX_CTL   :
            nFontId = DEFAULTFONT_CTL_TEXT;
        break;
//        case FONT_STANDARD:
//        case FONT_LIST    :
//        case FONT_CAPTION :
//        case FONT_INDEX   :
        default:
            nFontId = DEFAULTFONT_LATIN_TEXT;
    }
    Font aFont = OutputDevice::GetDefaultFont(nFontId, eLang, DEFAULTFONT_FLAGS_ONLYONE);
    return  aFont.GetName();
}
<|endoftext|>


<commit_before>#include <catch.hpp>
#include <zmq.hpp>
#ifdef ZMQ_CPP11

#ifdef ZMQ_CPP17
static_assert(std::is_nothrow_swappable_v<zmq::socket_ref>);
#endif
static_assert(sizeof(zmq::socket_ref) == sizeof(void *), "size mismatch");
static_assert(alignof(zmq::socket_ref) == alignof(void *), "alignment mismatch");
static_assert(std::is_trivially_copyable<zmq::socket_ref>::value,
              "needs to be trivially copyable");

TEST_CASE("socket_ref default init", "[socket_ref]")
{
    zmq::socket_ref sr;
    CHECK(!sr);
    CHECK(sr == nullptr);
    CHECK(nullptr == sr);
    CHECK(sr.handle() == nullptr);
}

TEST_CASE("socket_ref create from nullptr", "[socket_ref]")
{
    zmq::socket_ref sr = nullptr;
    CHECK(sr == nullptr);
    CHECK(sr.handle() == nullptr);
}

TEST_CASE("socket_ref create from handle", "[socket_ref]")
{
    void *np = nullptr;
    zmq::socket_ref sr{zmq::from_handle, np};
    CHECK(sr == nullptr);
    CHECK(sr.handle() == nullptr);
}

TEST_CASE("socket_ref compare", "[socket_ref]")
{
    zmq::socket_ref sr1;
    zmq::socket_ref sr2;
    CHECK(sr1 == sr2);
    CHECK(!(sr1 != sr2));
}

TEST_CASE("socket_ref compare from socket_t", "[socket_ref]")
{
    zmq::context_t context;
    zmq::socket_t s1(context, zmq::socket_type::router);
    zmq::socket_t s2(context, zmq::socket_type::dealer);
    zmq::socket_ref sr1 = s1;
    zmq::socket_ref sr2 = s2;
    CHECK(sr1);
    CHECK(sr2);
    CHECK(sr1 == s1);
    CHECK(sr2 == s2);
    CHECK(sr1.handle() == s1.handle());
    CHECK(sr1 != sr2);
    CHECK(sr1.handle() != sr2.handle());
    CHECK(sr1 != nullptr);
    CHECK(nullptr != sr1);
    CHECK(sr2 != nullptr);
    const bool comp1 = (sr1 < sr2) != (sr1 >= sr2);
    CHECK(comp1);
    const bool comp2 = (sr1 > sr2) != (sr1 <= sr2);
    CHECK(comp2);
    std::hash<zmq::socket_ref> hash;
    CHECK(hash(sr1) != hash(sr2));
    CHECK(hash(sr1) == hash(s1));
}

TEST_CASE("socket_ref assignment", "[socket_ref]")
{
    zmq::context_t context;
    zmq::socket_t s1(context, zmq::socket_type::router);
    zmq::socket_t s2(context, zmq::socket_type::dealer);
    zmq::socket_ref sr1 = s1;
    zmq::socket_ref sr2 = s2;
    sr1 = s2;
    CHECK(sr1 == sr2);
    CHECK(sr1.handle() == sr2.handle());
    sr1 = std::move(sr2);
    CHECK(sr1 == sr2);
    CHECK(sr1.handle() == sr2.handle());
    sr2 = nullptr;
    CHECK(sr1 != sr2);
    sr1 = nullptr;
    CHECK(sr1 == sr2);
}

TEST_CASE("socket_ref swap", "[socket_ref]")
{
    zmq::socket_ref sr1;
    zmq::socket_ref sr2;
    using std::swap;
    swap(sr1, sr2);
}

TEST_CASE("socket_ref reinterpret as void*", "[socket_ref]")
{
    struct SVP
    {
        void *p;
    };
    struct SSR
    {
        zmq::socket_ref sr;
    } ssr;

    zmq::context_t context;
    zmq::socket_t socket(context, zmq::socket_type::router);
    CHECK(socket.handle() != nullptr);
    reinterpret_cast<SVP *>(&ssr)->p = socket.handle();
    CHECK(ssr.sr == socket);
}

#endif
<commit_msg>Fix tests<commit_after>#include <catch.hpp>
#include <zmq.hpp>
#ifdef ZMQ_CPP11

#ifdef ZMQ_CPP17
static_assert(std::is_nothrow_swappable_v<zmq::socket_ref>);
#endif
static_assert(sizeof(zmq::socket_ref) == sizeof(void *), "size mismatch");
static_assert(alignof(zmq::socket_ref) == alignof(void *), "alignment mismatch");
static_assert(ZMQ_IS_TRIVIALLY_COPYABLE(zmq::socket_ref),
              "needs to be trivially copyable");

TEST_CASE("socket_ref default init", "[socket_ref]")
{
    zmq::socket_ref sr;
    CHECK(!sr);
    CHECK(sr == nullptr);
    CHECK(nullptr == sr);
    CHECK(sr.handle() == nullptr);
}

TEST_CASE("socket_ref create from nullptr", "[socket_ref]")
{
    zmq::socket_ref sr = nullptr;
    CHECK(sr == nullptr);
    CHECK(sr.handle() == nullptr);
}

TEST_CASE("socket_ref create from handle", "[socket_ref]")
{
    void *np = nullptr;
    zmq::socket_ref sr{zmq::from_handle, np};
    CHECK(sr == nullptr);
    CHECK(sr.handle() == nullptr);
}

TEST_CASE("socket_ref compare", "[socket_ref]")
{
    zmq::socket_ref sr1;
    zmq::socket_ref sr2;
    CHECK(sr1 == sr2);
    CHECK(!(sr1 != sr2));
}

TEST_CASE("socket_ref compare from socket_t", "[socket_ref]")
{
    zmq::context_t context;
    zmq::socket_t s1(context, zmq::socket_type::router);
    zmq::socket_t s2(context, zmq::socket_type::dealer);
    zmq::socket_ref sr1 = s1;
    zmq::socket_ref sr2 = s2;
    CHECK(sr1);
    CHECK(sr2);
    CHECK(sr1 == s1);
    CHECK(sr2 == s2);
    CHECK(sr1.handle() == s1.handle());
    CHECK(sr1 != sr2);
    CHECK(sr1.handle() != sr2.handle());
    CHECK(sr1 != nullptr);
    CHECK(nullptr != sr1);
    CHECK(sr2 != nullptr);
    const bool comp1 = (sr1 < sr2) != (sr1 >= sr2);
    CHECK(comp1);
    const bool comp2 = (sr1 > sr2) != (sr1 <= sr2);
    CHECK(comp2);
    std::hash<zmq::socket_ref> hash;
    CHECK(hash(sr1) != hash(sr2));
    CHECK(hash(sr1) == hash(s1));
}

TEST_CASE("socket_ref assignment", "[socket_ref]")
{
    zmq::context_t context;
    zmq::socket_t s1(context, zmq::socket_type::router);
    zmq::socket_t s2(context, zmq::socket_type::dealer);
    zmq::socket_ref sr1 = s1;
    zmq::socket_ref sr2 = s2;
    sr1 = s2;
    CHECK(sr1 == sr2);
    CHECK(sr1.handle() == sr2.handle());
    sr1 = std::move(sr2);
    CHECK(sr1 == sr2);
    CHECK(sr1.handle() == sr2.handle());
    sr2 = nullptr;
    CHECK(sr1 != sr2);
    sr1 = nullptr;
    CHECK(sr1 == sr2);
}

TEST_CASE("socket_ref swap", "[socket_ref]")
{
    zmq::socket_ref sr1;
    zmq::socket_ref sr2;
    using std::swap;
    swap(sr1, sr2);
}

TEST_CASE("socket_ref reinterpret as void*", "[socket_ref]")
{
    struct SVP
    {
        void *p;
    };
    struct SSR
    {
        zmq::socket_ref sr;
    } ssr;

    zmq::context_t context;
    zmq::socket_t socket(context, zmq::socket_type::router);
    CHECK(socket.handle() != nullptr);
    reinterpret_cast<SVP *>(&ssr)->p = socket.handle();
    CHECK(ssr.sr == socket);
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Test.util.h"

#include <stdarg.h>
#include <time.h>

#include <sstream>

#include <GL/freeglut.h>

#include <org/w3c/dom/Comment.h>
#include <org/w3c/dom/Element.h>
#include <org/w3c/dom/DocumentType.h>
#include <org/w3c/dom/Text.h>

#include "DOMImplementationImp.h"
#include "NodeImp.h"
#include "html/HTMLParser.h"
#include "css/Box.h"
#include "css/CSSInputStream.h"
#include "css/CSSParser.h"
#include "css/CSSStyleSheetImp.h"
#include "font/FontManager.h"
#include "utf.h"

using namespace org::w3c::dom::bootstrap;
using namespace org::w3c::dom;

namespace
{
    // 0: None
    // 1: Performance
    // 2: Harness
    // 3: Debug
    int logLevel = 3;
}

std::ostream& operator<<(std::ostream& stream, Node node)
{
    switch (node.getNodeType()) {
    case Node::DOCUMENT_TYPE_NODE:
        stream << "<!DOCTYPE " << node.getNodeName() << '>';
        break;
    case Node::COMMENT_NODE:
        stream << "<!-- " << interface_cast<Comment>(node).getData() << " -->";
        break;
    case Node::ELEMENT_NODE:
        stream << '<' << node.getNodeName() << '>';
        break;
    case Node::TEXT_NODE:
        stream << '"' << interface_cast<Text>(node).getData() << '"';
        break;
    default:
        stream << node.getNodeName();
        break;
    }
    return stream;
}

void dumpTree(std::ostream& result, Node node, std::string indent)
{
    while (node) {
        result << indent << node << '\n';
        Element element = interface_cast<Element>(node);
        if (element.getNodeType() == Node::ELEMENT_NODE) {
            ObjectArray<Attr> attrArray = element.getAttributes();
            assert(attrArray);
            for (unsigned int i = 0; i < attrArray.getLength(); ++i) {
                Attr attr = attrArray.getElement(i);
                assert(attr);
                result << indent << "  " << attr.getName() << "=\"" << attr.getValue() << "\"\n";
            }
        }
        if (node.hasChildNodes())
            dumpTree(result, node.getFirstChild(), indent + ((node.getNodeType() == Node::DOCUMENT_NODE) ? "| " : "  "));
        node = node.getNextSibling();
    }
}

void dumpStyleSheet(std::ostream& result, css::CSSStyleSheet sheet)
{
    css::CSSRuleList list = sheet.getCssRules();
    unsigned length = list.getLength();
    for (unsigned i = 0; i < length; ++i) {
        css::CSSRule rule = list.getElement(i);
        result << rule.getCssText() << '\n';
    }
}

void printComputedValues(Node node, ViewCSSImp* view, std::string indent)
{
    while (node) {
        if (node.getNodeType() == Node::ELEMENT_NODE) {
            Element element = interface_cast<Element>(node);
            std::cout << indent << '<' << element.getLocalName() << '>';
            if (css::CSSStyleDeclaration decl = view->getComputedStyle(element, Nullable<std::u16string>()))
                std::cout << ' ' << decl.getCssText();
            std::cout << '\n';
        }
        if (node.hasChildNodes())
            printComputedValues(node.getFirstChild(), view, indent + "  ");
        node = node.getNextSibling();
    }
}

css::CSSStyleSheet loadStyleSheet(std::istream& stream)
{
    CSSParser parser;
    CSSInputStream cssStream(stream, "utf-8");
    return parser.parse(0, cssStream);
}

css::CSSStyleSheet loadStyleSheet(const char* path)
{
    char url[PATH_MAX + 7];
    strcpy(url, "file://");
    realpath(path, url + 7);
    std::ifstream stream(path);
    if (!stream) {
        std::cerr << "error: cannot open " << path << ".\n";
        exit(EXIT_FAILURE);
    }
    CSSParser parser;
    CSSInputStream cssStream(stream, "utf-8");
    css::CSSStyleSheet sheet = parser.parse(0, cssStream);
    if (auto imp = dynamic_cast<CSSStyleSheetImp*>(sheet.self()))
        imp->setHref(toString(url));
    return sheet;
}

void eval(Node node)
{
    while (node) {
        if (node.hasChildNodes())
            eval(node.getFirstChild());
        dynamic_cast<NodeImp*>(node.self())->eval();;
        node = node.getNextSibling();
    }
}

Document loadDocument(std::istream& stream)
{
    HTMLInputStream htmlInputStream(stream, "utf-8");
    HTMLTokenizer tokenizer(&htmlInputStream);
    Document document = bootstrap::getDOMImplementation()->createDocument(u"", u"", 0);
    HTMLParser parser(document, &tokenizer);
    parser.mainLoop();
    return document;
}

Document loadDocument(const char* html)
{
    std::istringstream stream(html);
    return loadDocument(stream);
}

unsigned recordTime(const char* msg, ...)
{
    static timespec epoc{ 0, 0 };

    if (logLevel == 0)
        return 0.0;
    timespec tick;
    clock_gettime(CLOCK_REALTIME, &tick);
    if (epoc.tv_sec == 0 && epoc.tv_nsec == 0)
        epoc = tick;
    if (epoc.tv_nsec <= tick.tv_nsec)
        tick.tv_nsec -= epoc.tv_nsec ;
    else {
        --tick.tv_sec;
        tick.tv_nsec += 1000000000 - epoc.tv_nsec;
    }
    tick.tv_sec -= epoc.tv_sec;
    if (msg) {
        va_list ap;
        va_start(ap, msg);
        printf("%02u:%02u:%02u.%06u: ",
               tick.tv_sec / (60*60*60), tick.tv_sec / 60 % 60, tick.tv_sec % 60,
               tick.tv_nsec / 1000);
        vprintf(msg, ap);
        printf("\n");
        va_end(ap);
    }
    return tick.tv_sec * 100 + tick.tv_nsec / 10000000;
}

unsigned getTick()
{
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    return ts.tv_sec * 100 + ts.tv_nsec / 10000000;
}

void initLogLevel(int* argc, char* argv[], int defaultLevel)
{
    logLevel = defaultLevel;
    for (int i = 1; i < *argc; ++i) {
        if (strncmp(argv[i], "--v", 3) == 0) {
            if (argv[i][3] == '=')
                logLevel = atoi(argv[i] + 4);
            for (; i < *argc; ++i)
                argv[i] = argv[i + 1];
            --*argc;
            break;
        }
    }
}

int getLogLevel()
{
    return logLevel;
}

std::string getFileURL(const std::string& path)
{
    char url[PATH_MAX + 7];
    strcpy(url, "file://");
    realpath(path.c_str(), url + 7);
    return url;
}
<commit_msg>(recordTime) : Fix warnings<commit_after>/*
 * Copyright 2011-2013 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Test.util.h"

#include <stdarg.h>
#include <time.h>

#include <sstream>

#include <GL/freeglut.h>

#include <org/w3c/dom/Comment.h>
#include <org/w3c/dom/Element.h>
#include <org/w3c/dom/DocumentType.h>
#include <org/w3c/dom/Text.h>

#include "DOMImplementationImp.h"
#include "NodeImp.h"
#include "html/HTMLParser.h"
#include "css/Box.h"
#include "css/CSSInputStream.h"
#include "css/CSSParser.h"
#include "css/CSSStyleSheetImp.h"
#include "font/FontManager.h"
#include "utf.h"

using namespace org::w3c::dom::bootstrap;
using namespace org::w3c::dom;

namespace
{
    // 0: None
    // 1: Performance
    // 2: Harness
    // 3: Debug
    int logLevel = 3;
}

std::ostream& operator<<(std::ostream& stream, Node node)
{
    switch (node.getNodeType()) {
    case Node::DOCUMENT_TYPE_NODE:
        stream << "<!DOCTYPE " << node.getNodeName() << '>';
        break;
    case Node::COMMENT_NODE:
        stream << "<!-- " << interface_cast<Comment>(node).getData() << " -->";
        break;
    case Node::ELEMENT_NODE:
        stream << '<' << node.getNodeName() << '>';
        break;
    case Node::TEXT_NODE:
        stream << '"' << interface_cast<Text>(node).getData() << '"';
        break;
    default:
        stream << node.getNodeName();
        break;
    }
    return stream;
}

void dumpTree(std::ostream& result, Node node, std::string indent)
{
    while (node) {
        result << indent << node << '\n';
        Element element = interface_cast<Element>(node);
        if (element.getNodeType() == Node::ELEMENT_NODE) {
            ObjectArray<Attr> attrArray = element.getAttributes();
            assert(attrArray);
            for (unsigned int i = 0; i < attrArray.getLength(); ++i) {
                Attr attr = attrArray.getElement(i);
                assert(attr);
                result << indent << "  " << attr.getName() << "=\"" << attr.getValue() << "\"\n";
            }
        }
        if (node.hasChildNodes())
            dumpTree(result, node.getFirstChild(), indent + ((node.getNodeType() == Node::DOCUMENT_NODE) ? "| " : "  "));
        node = node.getNextSibling();
    }
}

void dumpStyleSheet(std::ostream& result, css::CSSStyleSheet sheet)
{
    css::CSSRuleList list = sheet.getCssRules();
    unsigned length = list.getLength();
    for (unsigned i = 0; i < length; ++i) {
        css::CSSRule rule = list.getElement(i);
        result << rule.getCssText() << '\n';
    }
}

void printComputedValues(Node node, ViewCSSImp* view, std::string indent)
{
    while (node) {
        if (node.getNodeType() == Node::ELEMENT_NODE) {
            Element element = interface_cast<Element>(node);
            std::cout << indent << '<' << element.getLocalName() << '>';
            if (css::CSSStyleDeclaration decl = view->getComputedStyle(element, Nullable<std::u16string>()))
                std::cout << ' ' << decl.getCssText();
            std::cout << '\n';
        }
        if (node.hasChildNodes())
            printComputedValues(node.getFirstChild(), view, indent + "  ");
        node = node.getNextSibling();
    }
}

css::CSSStyleSheet loadStyleSheet(std::istream& stream)
{
    CSSParser parser;
    CSSInputStream cssStream(stream, "utf-8");
    return parser.parse(0, cssStream);
}

css::CSSStyleSheet loadStyleSheet(const char* path)
{
    char url[PATH_MAX + 7];
    strcpy(url, "file://");
    realpath(path, url + 7);
    std::ifstream stream(path);
    if (!stream) {
        std::cerr << "error: cannot open " << path << ".\n";
        exit(EXIT_FAILURE);
    }
    CSSParser parser;
    CSSInputStream cssStream(stream, "utf-8");
    css::CSSStyleSheet sheet = parser.parse(0, cssStream);
    if (auto imp = dynamic_cast<CSSStyleSheetImp*>(sheet.self()))
        imp->setHref(toString(url));
    return sheet;
}

void eval(Node node)
{
    while (node) {
        if (node.hasChildNodes())
            eval(node.getFirstChild());
        dynamic_cast<NodeImp*>(node.self())->eval();;
        node = node.getNextSibling();
    }
}

Document loadDocument(std::istream& stream)
{
    HTMLInputStream htmlInputStream(stream, "utf-8");
    HTMLTokenizer tokenizer(&htmlInputStream);
    Document document = bootstrap::getDOMImplementation()->createDocument(u"", u"", 0);
    HTMLParser parser(document, &tokenizer);
    parser.mainLoop();
    return document;
}

Document loadDocument(const char* html)
{
    std::istringstream stream(html);
    return loadDocument(stream);
}

unsigned recordTime(const char* msg, ...)
{
    static timespec epoc{ 0, 0 };

    if (logLevel == 0)
        return 0.0;
    timespec tick;
    clock_gettime(CLOCK_REALTIME, &tick);
    if (epoc.tv_sec == 0 && epoc.tv_nsec == 0)
        epoc = tick;
    if (epoc.tv_nsec <= tick.tv_nsec)
        tick.tv_nsec -= epoc.tv_nsec ;
    else {
        --tick.tv_sec;
        tick.tv_nsec += 1000000000 - epoc.tv_nsec;
    }
    tick.tv_sec -= epoc.tv_sec;
    if (msg) {
        va_list ap;
        va_start(ap, msg);
        printf("%02lu:%02lu:%02lu.%06lu: ",
               tick.tv_sec / (60*60*60), tick.tv_sec / 60 % 60, tick.tv_sec % 60,
               tick.tv_nsec / 1000);
        vprintf(msg, ap);
        printf("\n");
        va_end(ap);
    }
    return tick.tv_sec * 100 + tick.tv_nsec / 10000000;
}

unsigned getTick()
{
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    return ts.tv_sec * 100 + ts.tv_nsec / 10000000;
}

void initLogLevel(int* argc, char* argv[], int defaultLevel)
{
    logLevel = defaultLevel;
    for (int i = 1; i < *argc; ++i) {
        if (strncmp(argv[i], "--v", 3) == 0) {
            if (argv[i][3] == '=')
                logLevel = atoi(argv[i] + 4);
            for (; i < *argc; ++i)
                argv[i] = argv[i + 1];
            --*argc;
            break;
        }
    }
}

int getLogLevel()
{
    return logLevel;
}

std::string getFileURL(const std::string& path)
{
    char url[PATH_MAX + 7];
    strcpy(url, "file://");
    realpath(path.c_str(), url + 7);
    return url;
}
<|endoftext|>


<commit_before><commit_msg>coverity#983200 Resource leak<commit_after><|endoftext|>