<commit_before>
#if !( defined(_PSVITA) || defined(_XBOXONE) )

//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include <thread>
#include "Effekseer.ServerImplemented.h"
#include "Effekseer.Effect.h"

#include <string.h>

#if defined(_WIN32) && !defined(_PS4)
#else
#include <unistd.h>
#endif

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer {
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::InternalClient::RecvAsync( void* data )
{
	InternalClient* client = (InternalClient*)data;

	while(true)
	{
		client->m_recvBuffer.clear();

		int32_t size = 0;
		int32_t restSize = 0;

		restSize = 4;
		while(restSize > 0)
		{
			auto recvSize = ::recv( client->m_socket, (char*)(&size), restSize, 0 );
			restSize -= recvSize;

			if( recvSize == 0 || recvSize == -1 )
			{
				// Failed
				client->m_server->RemoveClient( client );
				client->ShutDown();
				return;
			}
		}

		restSize = size;
		while(restSize > 0)
		{
			uint8_t buf[256];

			auto recvSize = ::recv( client->m_socket, (char*)(buf), Min(restSize,256), 0 );
			restSize -= recvSize;

			if( recvSize == 0 || recvSize == -1 )
			{
				// Failed
				client->m_server->RemoveClient( client );
				client->ShutDown();
				return;
			}

			for( int32_t i = 0; i < recvSize; i++ )
			{
				client->m_recvBuffer.push_back( buf[i] );
			}
		}

		// recieve buffer
		client->m_ctrlRecvBuffers.lock();
		client->m_recvBuffers.push_back(client->m_recvBuffer);
		client->m_ctrlRecvBuffers.unlock();
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::InternalClient::InternalClient( EfkSocket socket_, ServerImplemented* server )
	: m_socket	( socket_ )
	, m_server	( server )
	, m_active	( true )
{
	m_threadRecv = std::thread(
		[this]()
	{
		RecvAsync(this);
	});
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::InternalClient::~InternalClient()
{
	m_threadRecv.join();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::InternalClient::ShutDown()
{
	if ( m_socket != InvalidSocket )
	{
		Socket::Shutsown( m_socket );
		Socket::Close( m_socket );
		m_socket = InvalidSocket;
		m_active = false;
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::ServerImplemented()
	: m_running		( false )
{
	Socket::Initialize();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::~ServerImplemented()
{
	Stop();

	Socket::Finalize();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
Server* Server::Create()
{
	return new ServerImplemented();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::AddClient( InternalClient* client )
{
	std::lock_guard<std::mutex> lock(m_ctrlClients);
	m_clients.insert( client );
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::RemoveClient( InternalClient* client )
{
	std::lock_guard<std::mutex> lock(m_ctrlClients);
	if( m_clients.count( client ) > 0 )
	{
		m_clients.erase( client );
		m_removedClients.insert( client );
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::AcceptAsync( void* data )
{
	ServerImplemented* server = (ServerImplemented*)data;

	while(true)
	{
		SOCKADDR_IN socketAddrIn;
		int32_t Size = sizeof(SOCKADDR_IN);

		EfkSocket socket_ = ::accept(
			server->m_socket,
			(SOCKADDR*)(&socketAddrIn),
			(SOCKLEN*)(&Size) );

		if ( server->m_socket == InvalidSocket || socket_ == InvalidSocket )
		{
			break;
		}

		// Accept and add an internal client
		server->AddClient( new InternalClient( socket_, server ) );

		EffekseerPrintDebug("Server : AcceptClient\n");

	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
bool ServerImplemented::Start( uint16_t port )
{
	if( m_running )
	{
		Stop();
	}

	int32_t returnCode;
	sockaddr_in sockAddr = { AF_INET };

	// Create a socket
	EfkSocket socket_ = Socket::GenSocket();
	if ( socket_ == InvalidSocket )
	{
		return false;
	}

	memset( &sockAddr, 0, sizeof(SOCKADDR_IN));
	sockAddr.sin_family	= AF_INET;
	sockAddr.sin_port	= htons( port );

	returnCode = ::bind( socket_, (sockaddr*)&sockAddr, sizeof(sockaddr_in) );
	if ( returnCode == SocketError )
	{
		if ( socket_ != InvalidSocket )
		{
			Socket::Close( socket_ );
		}
		return false;
	}

	// Connect
	if ( !Socket::Listen( socket_, 30 ) )
	{
		if ( socket_ != InvalidSocket )
		{
			Socket::Close( socket_ );
		}
		return false;
	}

	m_running = true;
	m_socket = socket_;
	m_port = port;

	m_thread = std::thread(
		[this]()
	{
		AcceptAsync(this);
	});

	EffekseerPrintDebug("Server : Start\n");

	return true;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Stop()
{
	if( !m_running ) return;

	Socket::Shutsown( m_socket );
	Socket::Close( m_socket );
	m_socket = InvalidSocket;

	m_running = false;

	m_thread.join();

	// Stop clients
	m_ctrlClients.lock();
	for( std::set<InternalClient*>::iterator it = m_clients.begin(); it != m_clients.end(); ++it )
	{
		(*it)->ShutDown();
	}
	m_ctrlClients.unlock();

	// Wait clients to be removed
	while(true)
	{
		m_ctrlClients.lock();
		int32_t size = (int32_t)m_clients.size();
		m_ctrlClients.unlock();

		if( size == 0 ) break;

		std::this_thread::sleep_for(std::chrono::milliseconds(1));
	}

	// Delete clients
	for( std::set<InternalClient*>::iterator it = m_removedClients.begin(); it != m_removedClients.end(); ++it )
	{
		while( (*it)->m_active )
		{
			std::this_thread::sleep_for(std::chrono::milliseconds(1));
		}
		delete (*it);
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Register( const EFK_CHAR* key, Effect* effect )
{
	if( effect == NULL ) return;

	std::u16string key_( (const char16_t*)key );

	if( m_effects.count( key_ ) > 0 )
	{
		m_effects[key_]->Release();
	}

	m_effects[key_] = effect;
	m_effects[key_]->AddRef();

	if( m_data.count( key_ ) > 0 )
	{
		if( m_materialPath.size() > 1 )
		{
			m_effects[key_]->Reload( &(m_data[key_][0]), (int32_t)m_data.size(), &(m_materialPath[0]) );
		}
		else
		{
			m_effects[key_]->Reload( &(m_data[key_][0]), (int32_t)m_data.size() );
		}
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Unregister( Effect* effect )
{
	if( effect == NULL ) return;

	auto it = m_effects.begin();
	auto it_end = m_effects.end();

	while( it != it_end )
	{
		if( (*it).second == effect )
		{
			(*it).second->Release();
			m_effects.erase( it );
			return;
		}

		it++;
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Update(Manager** managers, int32_t managerCount, ReloadingThreadType reloadingThreadType)
{
	m_ctrlClients.lock();

	for( std::set<InternalClient*>::iterator it = m_removedClients.begin(); it != m_removedClients.end(); ++it )
	{
		while( (*it)->m_active )
		{
			std::this_thread::sleep_for(std::chrono::milliseconds(1));
		}
		delete (*it);
	}
	m_removedClients.clear();

	for( std::set<InternalClient*>::iterator it = m_clients.begin(); it != m_clients.end(); ++it )
	{
		(*it)->m_ctrlRecvBuffers.lock();

		for( size_t i = 0; i < (*it)->m_recvBuffers.size(); i++ )
		{
			std::vector<uint8_t>& buf = (*it)->m_recvBuffers[i];

			uint8_t* p = &(buf[0]);

			int32_t keylen = 0;
			memcpy( &keylen, p, sizeof(int32_t) );
			p += sizeof(int32_t);

			std::u16string key;
			for( int32_t k = 0; k < keylen; k++ )
			{
				key.push_back( ((char16_t*)p)[0] );
				p += sizeof(char16_t);
			}

			uint8_t* data = p;
			auto datasize = (int32_t)buf.size() - (p-&(buf[0]));

			if( m_data.count( key ) > 0 )
			{
				m_data[key].clear();
			}

			for( int32_t d = 0; d < datasize; d++ )
			{
				m_data[key].push_back( data[d] );
			}

			if( m_effects.count( key ) > 0 )
			{
				if (managers != nullptr)
				{
					auto& data = m_data[key];

					if (m_materialPath.size() > 1)
					{
						m_effects[key]->Reload(managers, managerCount, data.data(), (int32_t)data.size(), &(m_materialPath[0]), reloadingThreadType);
					}
					else
					{
						m_effects[key]->Reload(managers, managerCount, data.data(), (int32_t)data.size(), nullptr, reloadingThreadType);
					}
				}
				else
				{
					auto& data = m_data[key];

					if (m_materialPath.size() > 1)
					{
						m_effects[key]->Reload(data.data(), (int32_t)data.size(), &(m_materialPath[0]), reloadingThreadType);
					}
					else
					{
						m_effects[key]->Reload(data.data(), (int32_t)data.size(), nullptr, reloadingThreadType);
					}
				}

			}
		}

		(*it)->m_recvBuffers.clear();
		(*it)->m_ctrlRecvBuffers.unlock();

	}
	m_ctrlClients.unlock();

}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::SetMaterialPath( const EFK_CHAR* materialPath )
{
	m_materialPath.clear();

	int32_t pos = 0;
	while( materialPath[pos] != 0 )
	{
		m_materialPath.push_back( materialPath[pos] );
		pos++;
	}
	m_materialPath.push_back(0);
}

void ServerImplemented::Regist(const EFK_CHAR* key, Effect* effect)
{
	Register(key, effect);
}

void ServerImplemented::Unregist(Effect* effect)
{
	Unregister(effect);
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------

#endif	// #if !( defined(_PSVITA) || defined(_XBOXONE) )<commit_msg>fixed warnings<commit_after>
#if !( defined(_PSVITA) || defined(_XBOXONE) )

//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include <thread>
#include "Effekseer.ServerImplemented.h"
#include "Effekseer.Effect.h"

#include <string.h>

#if defined(_WIN32) && !defined(_PS4)
#else
#include <unistd.h>
#endif

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer {
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::InternalClient::RecvAsync( void* data )
{
	InternalClient* client = (InternalClient*)data;

	while(true)
	{
		client->m_recvBuffer.clear();

		int32_t size = 0;
		int32_t restSize = 0;

		restSize = 4;
		while(restSize > 0)
		{
			auto recvSize = ::recv( client->m_socket, (char*)(&size), restSize, 0 );
			restSize -= recvSize;

			if( recvSize == 0 || recvSize == -1 )
			{
				// Failed
				client->m_server->RemoveClient( client );
				client->ShutDown();
				return;
			}
		}

		restSize = size;
		while(restSize > 0)
		{
			uint8_t buf[256];

			auto recvSize = ::recv( client->m_socket, (char*)(buf), Min(restSize,256), 0 );
			restSize -= recvSize;

			if( recvSize == 0 || recvSize == -1 )
			{
				// Failed
				client->m_server->RemoveClient( client );
				client->ShutDown();
				return;
			}

			for( int32_t i = 0; i < recvSize; i++ )
			{
				client->m_recvBuffer.push_back( buf[i] );
			}
		}

		// recieve buffer
		client->m_ctrlRecvBuffers.lock();
		client->m_recvBuffers.push_back(client->m_recvBuffer);
		client->m_ctrlRecvBuffers.unlock();
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::InternalClient::InternalClient( EfkSocket socket_, ServerImplemented* server )
	: m_socket	( socket_ )
	, m_server	( server )
	, m_active	( true )
{
	m_threadRecv = std::thread(
		[this]()
	{
		RecvAsync(this);
	});
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::InternalClient::~InternalClient()
{
	m_threadRecv.join();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::InternalClient::ShutDown()
{
	if ( m_socket != InvalidSocket )
	{
		Socket::Shutsown( m_socket );
		Socket::Close( m_socket );
		m_socket = InvalidSocket;
		m_active = false;
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::ServerImplemented()
	: m_running		( false )
{
	Socket::Initialize();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ServerImplemented::~ServerImplemented()
{
	Stop();

	Socket::Finalize();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
Server* Server::Create()
{
	return new ServerImplemented();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::AddClient( InternalClient* client )
{
	std::lock_guard<std::mutex> lock(m_ctrlClients);
	m_clients.insert( client );
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::RemoveClient( InternalClient* client )
{
	std::lock_guard<std::mutex> lock(m_ctrlClients);
	if( m_clients.count( client ) > 0 )
	{
		m_clients.erase( client );
		m_removedClients.insert( client );
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::AcceptAsync( void* data )
{
	ServerImplemented* server = (ServerImplemented*)data;

	while(true)
	{
		SOCKADDR_IN socketAddrIn;
		int32_t Size = sizeof(SOCKADDR_IN);

		EfkSocket socket_ = ::accept(
			server->m_socket,
			(SOCKADDR*)(&socketAddrIn),
			(SOCKLEN*)(&Size) );

		if ( server->m_socket == InvalidSocket || socket_ == InvalidSocket )
		{
			break;
		}

		// Accept and add an internal client
		server->AddClient( new InternalClient( socket_, server ) );

		EffekseerPrintDebug("Server : AcceptClient\n");

	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
bool ServerImplemented::Start( uint16_t port )
{
	if( m_running )
	{
		Stop();
	}

	int32_t returnCode;
	sockaddr_in sockAddr = { AF_INET };

	// Create a socket
	EfkSocket socket_ = Socket::GenSocket();
	if ( socket_ == InvalidSocket )
	{
		return false;
	}

	memset( &sockAddr, 0, sizeof(SOCKADDR_IN));
	sockAddr.sin_family	= AF_INET;
	sockAddr.sin_port	= htons( port );

	returnCode = ::bind( socket_, (sockaddr*)&sockAddr, sizeof(sockaddr_in) );
	if ( returnCode == SocketError )
	{
		if ( socket_ != InvalidSocket )
		{
			Socket::Close( socket_ );
		}
		return false;
	}

	// Connect
	if ( !Socket::Listen( socket_, 30 ) )
	{
		if ( socket_ != InvalidSocket )
		{
			Socket::Close( socket_ );
		}
		return false;
	}

	m_running = true;
	m_socket = socket_;
	m_port = port;

	m_thread = std::thread(
		[this]()
	{
		AcceptAsync(this);
	});

	EffekseerPrintDebug("Server : Start\n");

	return true;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Stop()
{
	if( !m_running ) return;

	Socket::Shutsown( m_socket );
	Socket::Close( m_socket );
	m_socket = InvalidSocket;

	m_running = false;

	m_thread.join();

	// Stop clients
	m_ctrlClients.lock();
	for( std::set<InternalClient*>::iterator it = m_clients.begin(); it != m_clients.end(); ++it )
	{
		(*it)->ShutDown();
	}
	m_ctrlClients.unlock();

	// Wait clients to be removed
	while(true)
	{
		m_ctrlClients.lock();
		int32_t size = (int32_t)m_clients.size();
		m_ctrlClients.unlock();

		if( size == 0 ) break;

		std::this_thread::sleep_for(std::chrono::milliseconds(1));
	}

	// Delete clients
	for( std::set<InternalClient*>::iterator it = m_removedClients.begin(); it != m_removedClients.end(); ++it )
	{
		while( (*it)->m_active )
		{
			std::this_thread::sleep_for(std::chrono::milliseconds(1));
		}
		delete (*it);
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Register( const EFK_CHAR* key, Effect* effect )
{
	if( effect == NULL ) return;

	std::u16string key_( (const char16_t*)key );

	if( m_effects.count( key_ ) > 0 )
	{
		m_effects[key_]->Release();
	}

	m_effects[key_] = effect;
	m_effects[key_]->AddRef();

	if( m_data.count( key_ ) > 0 )
	{
		if( m_materialPath.size() > 1 )
		{
			m_effects[key_]->Reload( &(m_data[key_][0]), (int32_t)m_data.size(), &(m_materialPath[0]) );
		}
		else
		{
			m_effects[key_]->Reload( &(m_data[key_][0]), (int32_t)m_data.size() );
		}
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Unregister( Effect* effect )
{
	if( effect == NULL ) return;

	auto it = m_effects.begin();
	auto it_end = m_effects.end();

	while( it != it_end )
	{
		if( (*it).second == effect )
		{
			(*it).second->Release();
			m_effects.erase( it );
			return;
		}

		it++;
	}
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::Update(Manager** managers, int32_t managerCount, ReloadingThreadType reloadingThreadType)
{
	m_ctrlClients.lock();

	for( std::set<InternalClient*>::iterator it = m_removedClients.begin(); it != m_removedClients.end(); ++it )
	{
		while( (*it)->m_active )
		{
			std::this_thread::sleep_for(std::chrono::milliseconds(1));
		}
		delete (*it);
	}
	m_removedClients.clear();

	for( std::set<InternalClient*>::iterator it = m_clients.begin(); it != m_clients.end(); ++it )
	{
		(*it)->m_ctrlRecvBuffers.lock();

		for( size_t i = 0; i < (*it)->m_recvBuffers.size(); i++ )
		{
			std::vector<uint8_t>& buf = (*it)->m_recvBuffers[i];

			uint8_t* p = &(buf[0]);

			int32_t keylen = 0;
			memcpy( &keylen, p, sizeof(int32_t) );
			p += sizeof(int32_t);

			std::u16string key;
			for( int32_t k = 0; k < keylen; k++ )
			{
				key.push_back( ((char16_t*)p)[0] );
				p += sizeof(char16_t);
			}

			uint8_t* recv_data = p;
			auto datasize = (int32_t)buf.size() - (p-&(buf[0]));

			if( m_data.count( key ) > 0 )
			{
				m_data[key].clear();
			}

			for( int32_t d = 0; d < datasize; d++ )
			{
				m_data[key].push_back( recv_data[d] );
			}

			if( m_effects.count( key ) > 0 )
			{
				if (managers != nullptr)
				{
					auto& data_ = m_data[key];

					if (m_materialPath.size() > 1)
					{
						m_effects[key]->Reload(managers, managerCount, data_.data(), (int32_t)data_.size(), &(m_materialPath[0]), reloadingThreadType);
					}
					else
					{
						m_effects[key]->Reload(managers, managerCount, data_.data(), (int32_t)data_.size(), nullptr, reloadingThreadType);
					}
				}
				else
				{
					auto& data_ = m_data[key];

					if (m_materialPath.size() > 1)
					{
						m_effects[key]->Reload(data_.data(), (int32_t)data_.size(), &(m_materialPath[0]), reloadingThreadType);
					}
					else
					{
						m_effects[key]->Reload(data_.data(), (int32_t)data_.size(), nullptr, reloadingThreadType);
					}
				}

			}
		}

		(*it)->m_recvBuffers.clear();
		(*it)->m_ctrlRecvBuffers.unlock();

	}
	m_ctrlClients.unlock();

}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void ServerImplemented::SetMaterialPath( const EFK_CHAR* materialPath )
{
	m_materialPath.clear();

	int32_t pos = 0;
	while( materialPath[pos] != 0 )
	{
		m_materialPath.push_back( materialPath[pos] );
		pos++;
	}
	m_materialPath.push_back(0);
}

void ServerImplemented::Regist(const EFK_CHAR* key, Effect* effect)
{
	Register(key, effect);
}

void ServerImplemented::Unregist(Effect* effect)
{
	Unregister(effect);
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------

#endif	// #if !( defined(_PSVITA) || defined(_XBOXONE) )<|endoftext|>


<commit_before><commit_msg>coverity#984145 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: precompiled_canvas.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:16:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): Generated on 2006-09-01 17:49:32.389803

#ifdef PRECOMPILED_HEADERS
#endif

<commit_msg>INTEGRATION: CWS pchfix04 (1.2.32); FILE MERGED 2007/02/08 12:50:05 hjs 1.2.32.2: #i72801# gcc 3.4.1 dies on empty pch - windows here on the previous include... 2007/02/08 12:11:21 hjs 1.2.32.1: #i72801# gcc 3.4.1 dies on empty pch<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: precompiled_canvas.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 14:12:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): Generated on 2006-09-01 17:49:32.389803

#ifdef PRECOMPILED_HEADERS
#include <sal/macros.h>
#endif

<|endoftext|>


<commit_before>//
//  Copyright Silvin Lubecki 2010
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
#define OPENCLAM_CONTEXT_HPP_INCLUDED

#include <memory>
#include <boost/noncopyable.hpp>

namespace openclam
{

class context : private boost::noncopyable
{
public:
    enum device_type
    {
        default     = CL_DEVICE_TYPE_DEFAULT,
        cpu         = CL_DEVICE_TYPE_CPU,
        gpu         = CL_DEVICE_TYPE_GPU,
        accelerator = CL_DEVICE_TYPE_ACCELERATOR,
        all         = CL_DEVICE_TYPE_ALL
    };

    explicit context( device_type type = default )
    {
        ERROR_HANDLER( context_ = clCreateContextFromType( 0, type, NULL, NULL, &ERROR ) );
        unsigned int size;
        ERROR_HANDLER( ERROR = clGetContextInfo( context_, CL_CONTEXT_DEVICES, 0, NULL, &size ) );
        devices_.reset( new cl_device_id[ size ] );
        ERROR_HANDLER( ERROR = clGetContextInfo( context_, CL_CONTEXT_DEVICES, size, devices_.get(), NULL ) );
    }
    virtual ~context() {}

private:
    cl_context context_;
    std::auto_ptr< cl_device_id > devices_;
};

}

#endif // #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
<commit_msg>raise an error if no devices are available<commit_after>//
//  Copyright Silvin Lubecki 2010
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
#define OPENCLAM_CONTEXT_HPP_INCLUDED

#include <memory>
#include <boost/noncopyable.hpp>

namespace openclam
{

class context : private boost::noncopyable
{
public:
    enum device_type
    {
        default     = CL_DEVICE_TYPE_DEFAULT,
        cpu         = CL_DEVICE_TYPE_CPU,
        gpu         = CL_DEVICE_TYPE_GPU,
        accelerator = CL_DEVICE_TYPE_ACCELERATOR,
        all         = CL_DEVICE_TYPE_ALL
    };

    explicit context( device_type type = default )
    {
        ERROR_HANDLER( context_ = clCreateContextFromType( 0, type, NULL, NULL, &ERROR ) );
        unsigned int size;
        ERROR_HANDLER( ERROR = clGetContextInfo( context_, CL_CONTEXT_DEVICES, 0, NULL, &size ) );
        ERROR_HANDLER( ERROR = size > 0 ? CL_SUCCESS : CL_DEVICE_NOT_AVAILABLE );
        devices_.reset( new cl_device_id[ size ] );
        ERROR_HANDLER( ERROR = clGetContextInfo( context_, CL_CONTEXT_DEVICES, size, devices_.get(), NULL ) );
    }
    virtual ~context() {}

private:
    cl_context context_;
    std::auto_ptr< cl_device_id > devices_;
};

}

#endif // #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
<|endoftext|>


<commit_before><commit_msg>More Windows define whack-a-mole<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlotStateListener.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:04:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_TOOLS_SLOT_STATE_LISTENER_HXX
#define SD_TOOLS_SLOT_STATE_LISTENER_HXX

#include "MutexOwner.hxx"

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_
#include <com/sun/star/frame/FeatureStateEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHP_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTIOIN_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#include <tools/link.hxx>

namespace sd { namespace tools {

typedef cppu::WeakComponentImplHelper1<
    ::com::sun::star::frame::XStatusListener
    > SlotStateListenerInterfaceBase;

/** Listen for state changes of slots.  This class has been created in order
    to be informed when the support for vertical writing changes but it can
    be used to relay state changes of other slots as well.
*/
class SlotStateListener
    : protected MutexOwner,
      public SlotStateListenerInterfaceBase
{
public:
    /** Create a new object that has yet to be told about the the frame and
        slots to listen to and the callback that state changes are relayed
        to.  When you want to listen to one single slot then you can use the
        three argument variant of this constructor.
    */
    SlotStateListener (void);

    /** This convenience version of the constructor takes all parameters
        that are necessary to observe a single slot.  See descriptions of
        the SetCallback(), ConnectToFrame(), and ObserveSlot() methods for
        explanations about the parameters.
    */
    SlotStateListener (
        Link& rCallback,
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame> xFrame,
        const ::rtl::OUString& rSlotName);

    /** The constructor de-registers all remaining listeners.  Usually a prior
        dispose() call should have done that already.
    */
    virtual ~SlotStateListener (void);

    /** Set the callback to the given value.  Whenever one of the observed
        slots changes its state this callback is informed about it.
        Changing the callback does not release the listeners.
        @throws DisposedException
    */
    void SetCallback (const Link& rCallback);

    /** Set the frame whose slots shall be observed.  When an object of this
        class is already observing slots of another frame then these
        listeners are released first.
        @throws DisposedException
    */
    void ConnectToFrame (::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame> xFrame);

    /** Observe the slot specified by the given name.  Note that
        ConnectToFrame() has to have been called earlier.
        @param rSlotName
            The name of the slot to observe.  An example is
            ".uno:VerticalTextState".
        @throws DisposedException
    */
    void ObserveSlot (const ::rtl::OUString& rSlotName);

    //=====  frame::XStatusListener  ==========================================

    /** Called by slot state change broadcasters.  In turn the callback is
        informed about the state chage.
        @throws DisposedException
    */
    virtual void SAL_CALL
        statusChanged (
            const ::com::sun::star::frame::FeatureStateEvent& rState)
        throw (::com::sun::star::uno::RuntimeException);

    //=====  lang::XEventListener  ============================================

    virtual void SAL_CALL
        disposing(const com::sun::star::lang::EventObject& rEvent)
        throw(com::sun::star::uno::RuntimeException);

protected:
    /** This method is called by the WeakComponentImplHelper base class in
        reaction to a XComponent::dispose() call.  It releases all currently
        active listeners.
    */
    virtual void SAL_CALL disposing (void);

private:
    Link maCallback;

    /** Remember the URLs that describe slots whose state changes we are
        listening to.
    */
    typedef ::std::vector<com::sun::star::util::URL> RegisteredURLList;
    RegisteredURLList maRegisteredURLList;

    ::com::sun::star::uno::WeakReference<
        ::com::sun::star::frame::XFrame> mxFrameWeak;

    /** Deregister all currently active state change listeners.
    */
    void ReleaseListeners (void);

    /** This method throws a DisposedException when the object has already been
        disposed.
    */
    void ThrowIfDisposed (void)
        throw (::com::sun::star::lang::DisposedException);

    /** Transform the given string into a URL object.
    */
    ::com::sun::star::util::URL MakeURL (const ::rtl::OUString& rSlotName) const;

    /** Return an XDispatch object for the given URL.
    */
    ::com::sun::star::uno::Reference<com::sun::star::frame::XDispatch>
        GetDispatch (
            const ::com::sun::star::util::URL& rURL) const;
};

} } // end of namespace ::sd::tools

#endif
<commit_msg>INTEGRATION: CWS components1 (1.3.234); FILE MERGED 2007/02/16 14:07:28 af 1.3.234.1: #i68075# Specialized the XFrame argument to XDispatchProvider.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlotStateListener.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:15:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_TOOLS_SLOT_STATE_LISTENER_HXX
#define SD_TOOLS_SLOT_STATE_LISTENER_HXX

#include "MutexOwner.hxx"

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_
#include <com/sun/star/frame/FeatureStateEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTIOIN_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#include <tools/link.hxx>

namespace sd { namespace tools {

typedef cppu::WeakComponentImplHelper1<
    ::com::sun::star::frame::XStatusListener
    > SlotStateListenerInterfaceBase;

/** Listen for state changes of slots.  This class has been created in order
    to be informed when the support for vertical writing changes but it can
    be used to relay state changes of other slots as well.
*/
class SlotStateListener
    : protected MutexOwner,
      public SlotStateListenerInterfaceBase
{
public:
    /** Create a new object that has yet to be told about the the frame and
        slots to listen to and the callback that state changes are relayed
        to.  When you want to listen to one single slot then you can use the
        three argument variant of this constructor.
    */
    SlotStateListener (void);

    /** This convenience version of the constructor takes all parameters
        that are necessary to observe a single slot.  See descriptions of
        the SetCallback(), ConnectToFrame(), and ObserveSlot() methods for
        explanations about the parameters.
    */
    SlotStateListener (
        Link& rCallback,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XDispatchProvider>& rxDispatchProvider,
        const ::rtl::OUString& rSlotName);

    /** The constructor de-registers all remaining listeners.  Usually a prior
        dispose() call should have done that already.
    */
    virtual ~SlotStateListener (void);

    /** Set the callback to the given value.  Whenever one of the observed
        slots changes its state this callback is informed about it.
        Changing the callback does not release the listeners.
        @throws DisposedException
    */
    void SetCallback (const Link& rCallback);

    /** Set the frame whose slots shall be observed.  When an object of this
        class is already observing slots of another frame then these
        listeners are released first.
        @throws DisposedException
    */
    void ConnectToDispatchProvider (
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XDispatchProvider>& rxDispatchProvider);

    /** Observe the slot specified by the given name.  Note that
        ConnectToFrame() has to have been called earlier.
        @param rSlotName
            The name of the slot to observe.  An example is
            ".uno:VerticalTextState".
        @throws DisposedException
    */
    void ObserveSlot (const ::rtl::OUString& rSlotName);

    /** Return whether the called SlotStateListener is connected to a slot.
        One reason for returning <FALSE/> is that the SlotStateListener has
        been created before the controller and frame have been properly
        initialized.
    */
    bool IsValid (void) const;

    //=====  frame::XStatusListener  ==========================================

    /** Called by slot state change broadcasters.  In turn the callback is
        informed about the state chage.
        @throws DisposedException
    */
    virtual void SAL_CALL
        statusChanged (
            const ::com::sun::star::frame::FeatureStateEvent& rState)
        throw (::com::sun::star::uno::RuntimeException);

    //=====  lang::XEventListener  ============================================

    virtual void SAL_CALL
        disposing(const com::sun::star::lang::EventObject& rEvent)
        throw(com::sun::star::uno::RuntimeException);

protected:
    /** This method is called by the WeakComponentImplHelper base class in
        reaction to a XComponent::dispose() call.  It releases all currently
        active listeners.
    */
    virtual void SAL_CALL disposing (void);

private:
    Link maCallback;

    /** Remember the URLs that describe slots whose state changes we are
        listening to.
    */
    typedef ::std::vector<com::sun::star::util::URL> RegisteredURLList;
    RegisteredURLList maRegisteredURLList;

    ::com::sun::star::uno::WeakReference<
        ::com::sun::star::frame::XDispatchProvider> mxDispatchProviderWeak;

    /** Deregister all currently active state change listeners.
    */
    void ReleaseListeners (void);

    /** This method throws a DisposedException when the object has already been
        disposed.
    */
    void ThrowIfDisposed (void)
        throw (::com::sun::star::lang::DisposedException);

    /** Transform the given string into a URL object.
    */
    ::com::sun::star::util::URL MakeURL (const ::rtl::OUString& rSlotName) const;

    /** Return an XDispatch object for the given URL.
    */
    ::com::sun::star::uno::Reference<com::sun::star::frame::XDispatch>
        GetDispatch (
            const ::com::sun::star::util::URL& rURL) const;
};

} } // end of namespace ::sd::tools

#endif
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------

#include "windowManager/sdl/sdlWindowMgr.h"
#include "platformSDL/sdlInputManager.h"
#include "gfx/gfxDevice.h"
#include "core/util/journal/process.h"
#include "core/strings/unicode.h"
#include "gfx/bitmap/gBitmap.h"

#include "SDL.h"

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

void sdl_CloseSplashWindow(void* hinst);

#ifdef TORQUE_SDL

PlatformWindowManager * CreatePlatformWindowManager()
{
   return new PlatformWindowManagerSDL();
}

#endif

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

PlatformWindowManagerSDL::PlatformWindowManagerSDL()
{
   // Register in the process list.
   mOnProcessSignalSlot.setDelegate( this, &PlatformWindowManagerSDL::_process );
   Process::notify( mOnProcessSignalSlot, PROCESS_INPUT_ORDER );

   // Init our list of allocated windows.
   mWindowListHead = NULL;

   // By default, we have no parent window.
   mParentWindow = NULL;

   mCurtainWindow = NULL;

   mDisplayWindow = true;
   mOffscreenRender = false;

   mInputState = KeyboardInputState::NONE;
}

PlatformWindowManagerSDL::~PlatformWindowManagerSDL()
{
   // Kill all our windows first.
   while(mWindowListHead)
      // The destructors update the list, so this works just fine.
      delete mWindowListHead;
}

RectI PlatformWindowManagerSDL::getPrimaryDesktopArea()
{
   // Primary is monitor 0
   return getMonitorRect(0);
}

Point2I PlatformWindowManagerSDL::getDesktopResolution()
{
   SDL_DisplayMode mode;
   SDL_GetDesktopDisplayMode(0, &mode);

   // Return Resolution
   return Point2I(mode.w, mode.h);
}

S32 PlatformWindowManagerSDL::getDesktopBitDepth()
{
   // Return Bits per Pixel
   SDL_DisplayMode mode;
   SDL_GetDesktopDisplayMode(0, &mode);
   int bbp;
   unsigned int r,g,b,a;
   SDL_PixelFormatEnumToMasks(mode.format, &bbp, &r, &g, &b, &a);
   return bbp;
}

S32 PlatformWindowManagerSDL::findFirstMatchingMonitor(const char* name)
{
   S32 count = SDL_GetNumVideoDisplays();
   for (U32 index = 0; index < count; ++index)
   {
      if (dStrstr(name, SDL_GetDisplayName(index)) == name)
         return index;
   }

   return 0;
}

U32 PlatformWindowManagerSDL::getMonitorCount()
{
   S32 monitorCount = SDL_GetNumVideoDisplays();
   if (monitorCount < 0)
   {
      Con::errorf("SDL_GetNumVideoDisplays() failed: %s", SDL_GetError());
      monitorCount = 0;
   }

   return (U32)monitorCount;
}

const char* PlatformWindowManagerSDL::getMonitorName(U32 index)
{
   const char* monitorName = SDL_GetDisplayName(index);
   if (monitorName == NULL)
      Con::errorf("SDL_GetDisplayName() failed: %s", SDL_GetError());

   return monitorName;
}

RectI PlatformWindowManagerSDL::getMonitorRect(U32 index)
{
   SDL_Rect sdlRect;
   if (0 != SDL_GetDisplayBounds(index, &sdlRect))
   {
      Con::errorf("SDL_GetDisplayBounds() failed: %s", SDL_GetError());
      return RectI(0, 0, 0, 0);
   }

   return RectI(sdlRect.x, sdlRect.y, sdlRect.w, sdlRect.h);
}

void PlatformWindowManagerSDL::getMonitorRegions(Vector<RectI> &regions)
{
   SDL_Rect sdlRect;
   S32 monitorCount = SDL_GetNumVideoDisplays();
   for (S32 index = 0; index < monitorCount; ++index)
   {
      if (0 == SDL_GetDisplayBounds(index, &sdlRect))
         regions.push_back(RectI(sdlRect.x, sdlRect.y, sdlRect.w, sdlRect.h));
   }
}

void PlatformWindowManagerSDL::getWindows(VectorPtr<PlatformWindow*> &windows)
{
   PlatformWindowSDL *win = mWindowListHead;
   while(win)
   {
      windows.push_back(win);
      win = win->mNextWindow;
   }
}

PlatformWindow *PlatformWindowManagerSDL::createWindow(GFXDevice *device, const GFXVideoMode &mode)
{
   // Do the allocation.
   PlatformWindowSDL *window = new PlatformWindowSDL();
   U32 windowFlags = /*SDL_WINDOW_SHOWN |*/ SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN;

   if(GFX->getAdapterType() == OpenGL)
       windowFlags |= SDL_WINDOW_OPENGL;

   window->mWindowHandle = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.resolution.x, mode.resolution.y, windowFlags );
   window->mWindowId = SDL_GetWindowID( window->mWindowHandle );
   window->mOwningManager = this;
   mWindowMap[ window->mWindowId ] = window;

   //Now, fetch our window icon, if any
   Torque::Path iconPath = Torque::Path(Con::getVariable( "$Core::windowIcon" ));

   if (iconPath.getExtension() == String("bmp"))
   {
      Con::errorf("Unable to use bmp format images for the window icon. Please use a different format.");
   }
   else
   {
      Resource<GBitmap> img = GBitmap::load(iconPath);
      if (img != NULL)
      {
         U32 pitch;
         U32 width = img->getWidth();
         bool hasAlpha = img->getHasTransparency();
         U32 depth;

         if (hasAlpha)
         {
            pitch = 4 * width;
            depth = 32;
         }
         else
         {
            pitch = 3 * width;
            depth = 24;
         }

         Uint32 rmask, gmask, bmask, amask;
         if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
         {
            S32 shift = hasAlpha ? 8 : 0;
            rmask = 0xff000000 >> shift;
            gmask = 0x00ff0000 >> shift;
            bmask = 0x0000ff00 >> shift;
            amask = 0x000000ff >> shift;
         }
         else
         {
            rmask = 0x000000ff;
            gmask = 0x0000ff00;
            bmask = 0x00ff0000;
            amask = hasAlpha ? 0xff000000 : 0;
         }

         SDL_Surface* iconSurface = SDL_CreateRGBSurfaceFrom(img->getAddress(0, 0), img->getWidth(), img->getHeight(), depth, pitch, rmask, gmask, bmask, amask);

         SDL_SetWindowIcon(window->mWindowHandle, iconSurface);

         SDL_FreeSurface(iconSurface);
      }
   }

   if(device)
   {
      window->mDevice = device;
      window->mTarget = device->allocWindowTarget(window);
      AssertISV(window->mTarget, "PlatformWindowManagerSDL::createWindow - failed to get a window target back from the device.");
   }
   else
   {
      Con::warnf("PlatformWindowManagerSDL::createWindow - created a window with no device!");
   }

   //Set it up for drag-n-drop events
#ifdef TORQUE_TOOLS
   SDL_EventState(SDL_DROPBEGIN, SDL_ENABLE);
   SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
   SDL_EventState(SDL_DROPCOMPLETE, SDL_ENABLE);
#endif

   linkWindow(window);

   return window;
}

void PlatformWindowManagerSDL::setParentWindow(void* newParent)
{

}

void* PlatformWindowManagerSDL::getParentWindow()
{
   return NULL;
}

void PlatformWindowManagerSDL::_process()
{
   SDL_Event evt;
   while( SDL_PollEvent(&evt) )
   {
      if (evt.type >= SDL_JOYAXISMOTION && evt.type <= SDL_CONTROLLERDEVICEREMAPPED)
      {
         SDLInputManager* mgr = static_cast<SDLInputManager*>(Input::getManager());
         if (mgr)
            mgr->processEvent(evt);
         continue;
      }
      switch(evt.type)
      {
          case SDL_QUIT:
          {
             PlatformWindowSDL *window = static_cast<PlatformWindowSDL*>( getFirstWindow() );
             if(window)
               window->appEvent.trigger( window->getWindowId(), WindowClose );
             break;
          }

         case SDL_KEYDOWN:
         case SDL_KEYUP:
         {
            PlatformWindowSDL *window = mWindowMap[evt.key.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_MOUSEWHEEL:
         {
            PlatformWindowSDL *window = mWindowMap[evt.wheel.windowID];
            if (window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_MOUSEMOTION:
         {
            PlatformWindowSDL *window = mWindowMap[evt.motion.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_MOUSEBUTTONDOWN:
         case SDL_MOUSEBUTTONUP:
         {
            PlatformWindowSDL *window = mWindowMap[evt.button.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_TEXTINPUT:
         {
            PlatformWindowSDL *window = mWindowMap[evt.text.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_WINDOWEVENT:
         {
            PlatformWindowSDL *window = mWindowMap[evt.window.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case(SDL_DROPBEGIN):
         {
            if (!Con::isFunction("onDropBegin"))
               break;

            Con::executef("onDropBegin");
         }

         case (SDL_DROPFILE):
         {
            // In case if dropped file
            if (!Con::isFunction("onDropFile"))
               break;

            char* fileName = evt.drop.file;

            if (!Platform::isFile(fileName))
               break;

            Con::executef("onDropFile", StringTable->insert(fileName));

            SDL_free(fileName);    // Free dropped_filedir memory
            break;
         }

         case(SDL_DROPCOMPLETE):
         {
            if (Con::isFunction("onDropEnd"))
               Con::executef("onDropEnd");
            break;
         }

         default:
         {
#ifdef TORQUE_DEBUG
            Con::warnf("Unhandled SDL input event: 0x%04x", evt.type);
#endif
         }
      }
   }

   // After the event loop is processed, we can now see if we have to notify
   // SDL that we want text based events. This fixes a bug where text based
   // events would be generated while key presses would still be happening.
   // See KeyboardInputState for further documentation.
   if (mInputState != KeyboardInputState::NONE)
   {
      // Update text mode toggling.
      if (mInputState == KeyboardInputState::TEXT_INPUT)
         SDL_StartTextInput();
      else
         SDL_StopTextInput();

      // Done until we need to update it again.
      mInputState = KeyboardInputState::NONE;
   }
}

PlatformWindow * PlatformWindowManagerSDL::getWindowById( WindowId id )
{
   // Walk the list and find the matching id, if any.
   PlatformWindowSDL *win = mWindowListHead;
   while(win)
   {
      if(win->getWindowId() == id)
         return win;

      win = win->mNextWindow;
   }

   return NULL;
}

PlatformWindow * PlatformWindowManagerSDL::getFirstWindow()
{
   return mWindowListHead != NULL ? mWindowListHead : NULL;
}

PlatformWindow* PlatformWindowManagerSDL::getFocusedWindow()
{
   PlatformWindowSDL* window = mWindowListHead;
   while( window )
   {
      if( window->isFocused() )
         return window;

      window = window->mNextWindow;
   }

   return NULL;
}

void PlatformWindowManagerSDL::linkWindow( PlatformWindowSDL *w )
{
   w->mNextWindow = mWindowListHead;
   mWindowListHead = w;
}

void PlatformWindowManagerSDL::unlinkWindow( PlatformWindowSDL *w )
{
   PlatformWindowSDL **walk = &mWindowListHead;
   while(*walk)
   {
      if(*walk != w)
      {
         // Advance to next item in list.
         walk = &(*walk)->mNextWindow;
         continue;
      }

      // Got a match - unlink and return.
      *walk = (*walk)->mNextWindow;
      return;
   }
}

void PlatformWindowManagerSDL::_processCmdLineArgs( const S32 argc, const char **argv )
{
   // TODO SDL
}

void PlatformWindowManagerSDL::lowerCurtain()
{
   if(mCurtainWindow)
      return;

   // TODO SDL
}

void PlatformWindowManagerSDL::raiseCurtain()
{
   if(!mCurtainWindow)
      return;

   // TODO SDL
}

void PlatformWindowManagerSDL::updateSDLTextInputState(KeyboardInputState state)
{
   // Force update state. This will respond at the end of the event loop.
   mInputState = state;
}

void Platform::openFolder(const char* path )
{
    AssertFatal(0, "Not Implemented");
}

void Platform::openFile(const char* path )
{
    AssertFatal(0, "Not Implemented");
}

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

namespace GL
{
   void gglPerformBinds();
}

void InitWindowingSystem()
{

}

AFTER_MODULE_INIT(gfx)
{
   int res = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS | SDL_INIT_NOPARACHUTE);
   AssertFatal(res != -1, avar("SDL error:%s", SDL_GetError()));

   // By default, SDL enables text input. We disable it on initialization, and
   // we will enable it whenever the time is right.
   SDL_StopTextInput();
}
<commit_msg>Fixes a crash that occurs on linux headless servers<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------

#include "windowManager/sdl/sdlWindowMgr.h"
#include "platformSDL/sdlInputManager.h"
#include "gfx/gfxDevice.h"
#include "core/util/journal/process.h"
#include "core/strings/unicode.h"
#include "gfx/bitmap/gBitmap.h"

#include "SDL.h"

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

void sdl_CloseSplashWindow(void* hinst);

#ifdef TORQUE_SDL

PlatformWindowManager * CreatePlatformWindowManager()
{
   return new PlatformWindowManagerSDL();
}

#endif

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

PlatformWindowManagerSDL::PlatformWindowManagerSDL()
{
   // Register in the process list.
   mOnProcessSignalSlot.setDelegate( this, &PlatformWindowManagerSDL::_process );
   Process::notify( mOnProcessSignalSlot, PROCESS_INPUT_ORDER );

   // Init our list of allocated windows.
   mWindowListHead = NULL;

   // By default, we have no parent window.
   mParentWindow = NULL;

   mCurtainWindow = NULL;

   mDisplayWindow = true;
   mOffscreenRender = false;

   mInputState = KeyboardInputState::NONE;
}

PlatformWindowManagerSDL::~PlatformWindowManagerSDL()
{
   // Kill all our windows first.
   while(mWindowListHead)
      // The destructors update the list, so this works just fine.
      delete mWindowListHead;
}

RectI PlatformWindowManagerSDL::getPrimaryDesktopArea()
{
   // Primary is monitor 0
   return getMonitorRect(0);
}

Point2I PlatformWindowManagerSDL::getDesktopResolution()
{
   SDL_DisplayMode mode;
   SDL_GetDesktopDisplayMode(0, &mode);

   // Return Resolution
   return Point2I(mode.w, mode.h);
}

S32 PlatformWindowManagerSDL::getDesktopBitDepth()
{
   // Return Bits per Pixel
   SDL_DisplayMode mode;
   SDL_GetDesktopDisplayMode(0, &mode);
   int bbp;
   unsigned int r,g,b,a;
   SDL_PixelFormatEnumToMasks(mode.format, &bbp, &r, &g, &b, &a);
   return bbp;
}

S32 PlatformWindowManagerSDL::findFirstMatchingMonitor(const char* name)
{
   S32 count = SDL_GetNumVideoDisplays();
   for (U32 index = 0; index < count; ++index)
   {
      if (dStrstr(name, SDL_GetDisplayName(index)) == name)
         return index;
   }

   return 0;
}

U32 PlatformWindowManagerSDL::getMonitorCount()
{
   S32 monitorCount = SDL_GetNumVideoDisplays();
   if (monitorCount < 0)
   {
      Con::errorf("SDL_GetNumVideoDisplays() failed: %s", SDL_GetError());
      monitorCount = 0;
   }

   return (U32)monitorCount;
}

const char* PlatformWindowManagerSDL::getMonitorName(U32 index)
{
   const char* monitorName = SDL_GetDisplayName(index);
   if (monitorName == NULL)
      Con::errorf("SDL_GetDisplayName() failed: %s", SDL_GetError());

   return monitorName;
}

RectI PlatformWindowManagerSDL::getMonitorRect(U32 index)
{
   SDL_Rect sdlRect;
   if (0 != SDL_GetDisplayBounds(index, &sdlRect))
   {
      Con::errorf("SDL_GetDisplayBounds() failed: %s", SDL_GetError());
      return RectI(0, 0, 0, 0);
   }

   return RectI(sdlRect.x, sdlRect.y, sdlRect.w, sdlRect.h);
}

void PlatformWindowManagerSDL::getMonitorRegions(Vector<RectI> &regions)
{
   SDL_Rect sdlRect;
   S32 monitorCount = SDL_GetNumVideoDisplays();
   for (S32 index = 0; index < monitorCount; ++index)
   {
      if (0 == SDL_GetDisplayBounds(index, &sdlRect))
         regions.push_back(RectI(sdlRect.x, sdlRect.y, sdlRect.w, sdlRect.h));
   }
}

void PlatformWindowManagerSDL::getWindows(VectorPtr<PlatformWindow*> &windows)
{
   PlatformWindowSDL *win = mWindowListHead;
   while(win)
   {
      windows.push_back(win);
      win = win->mNextWindow;
   }
}

PlatformWindow *PlatformWindowManagerSDL::createWindow(GFXDevice *device, const GFXVideoMode &mode)
{
   // Do the allocation.
   PlatformWindowSDL *window = new PlatformWindowSDL();
   U32 windowFlags = /*SDL_WINDOW_SHOWN |*/ SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN;

   if(GFX->getAdapterType() == OpenGL)
       windowFlags |= SDL_WINDOW_OPENGL;

   window->mWindowHandle = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.resolution.x, mode.resolution.y, windowFlags );
   window->mWindowId = SDL_GetWindowID( window->mWindowHandle );
   window->mOwningManager = this;
   mWindowMap[ window->mWindowId ] = window;

   //Now, fetch our window icon, if any
   Torque::Path iconPath = Torque::Path(Con::getVariable( "$Core::windowIcon" ));

   if (iconPath.getExtension() == String("bmp"))
   {
      Con::errorf("Unable to use bmp format images for the window icon. Please use a different format.");
   }
   else
   {
      Resource<GBitmap> img = GBitmap::load(iconPath);
      if (img != NULL)
      {
         U32 pitch;
         U32 width = img->getWidth();
         bool hasAlpha = img->getHasTransparency();
         U32 depth;

         if (hasAlpha)
         {
            pitch = 4 * width;
            depth = 32;
         }
         else
         {
            pitch = 3 * width;
            depth = 24;
         }

         Uint32 rmask, gmask, bmask, amask;
         if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
         {
            S32 shift = hasAlpha ? 8 : 0;
            rmask = 0xff000000 >> shift;
            gmask = 0x00ff0000 >> shift;
            bmask = 0x0000ff00 >> shift;
            amask = 0x000000ff >> shift;
         }
         else
         {
            rmask = 0x000000ff;
            gmask = 0x0000ff00;
            bmask = 0x00ff0000;
            amask = hasAlpha ? 0xff000000 : 0;
         }

         SDL_Surface* iconSurface = SDL_CreateRGBSurfaceFrom(img->getAddress(0, 0), img->getWidth(), img->getHeight(), depth, pitch, rmask, gmask, bmask, amask);

         SDL_SetWindowIcon(window->mWindowHandle, iconSurface);

         SDL_FreeSurface(iconSurface);
      }
   }

   if(device)
   {
      window->mDevice = device;
      window->mTarget = device->allocWindowTarget(window);
      AssertISV(window->mTarget, "PlatformWindowManagerSDL::createWindow - failed to get a window target back from the device.");
   }
   else
   {
      Con::warnf("PlatformWindowManagerSDL::createWindow - created a window with no device!");
   }

   //Set it up for drag-n-drop events
#ifdef TORQUE_TOOLS
   SDL_EventState(SDL_DROPBEGIN, SDL_ENABLE);
   SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
   SDL_EventState(SDL_DROPCOMPLETE, SDL_ENABLE);
#endif

   linkWindow(window);

   return window;
}

void PlatformWindowManagerSDL::setParentWindow(void* newParent)
{

}

void* PlatformWindowManagerSDL::getParentWindow()
{
   return NULL;
}

void PlatformWindowManagerSDL::_process()
{
   SDL_Event evt;
   while( SDL_PollEvent(&evt) )
   {
      if (evt.type >= SDL_JOYAXISMOTION && evt.type <= SDL_CONTROLLERDEVICEREMAPPED)
      {
         SDLInputManager* mgr = static_cast<SDLInputManager*>(Input::getManager());
         if (mgr)
            mgr->processEvent(evt);
         continue;
      }
      switch(evt.type)
      {
          case SDL_QUIT:
          {
             PlatformWindowSDL *window = static_cast<PlatformWindowSDL*>( getFirstWindow() );
             if(window)
               window->appEvent.trigger( window->getWindowId(), WindowClose );
             break;
          }

         case SDL_KEYDOWN:
         case SDL_KEYUP:
         {
            PlatformWindowSDL *window = mWindowMap[evt.key.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_MOUSEWHEEL:
         {
            PlatformWindowSDL *window = mWindowMap[evt.wheel.windowID];
            if (window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_MOUSEMOTION:
         {
            PlatformWindowSDL *window = mWindowMap[evt.motion.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_MOUSEBUTTONDOWN:
         case SDL_MOUSEBUTTONUP:
         {
            PlatformWindowSDL *window = mWindowMap[evt.button.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_TEXTINPUT:
         {
            PlatformWindowSDL *window = mWindowMap[evt.text.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case SDL_WINDOWEVENT:
         {
            PlatformWindowSDL *window = mWindowMap[evt.window.windowID];
            if(window)
               window->_processSDLEvent(evt);
            break;
         }

         case(SDL_DROPBEGIN):
         {
            if (!Con::isFunction("onDropBegin"))
               break;

            Con::executef("onDropBegin");
         }

         case (SDL_DROPFILE):
         {
            // In case if dropped file
            if (!Con::isFunction("onDropFile"))
               break;

            char* fileName = evt.drop.file;

            if (!Platform::isFile(fileName))
               break;

            Con::executef("onDropFile", StringTable->insert(fileName));

            SDL_free(fileName);    // Free dropped_filedir memory
            break;
         }

         case(SDL_DROPCOMPLETE):
         {
            if (Con::isFunction("onDropEnd"))
               Con::executef("onDropEnd");
            break;
         }

         default:
         {
#ifdef TORQUE_DEBUG
            Con::warnf("Unhandled SDL input event: 0x%04x", evt.type);
#endif
         }
      }
   }

   // After the event loop is processed, we can now see if we have to notify
   // SDL that we want text based events. This fixes a bug where text based
   // events would be generated while key presses would still be happening.
   // See KeyboardInputState for further documentation.
   if (mInputState != KeyboardInputState::NONE)
   {
      // Update text mode toggling.
      if (mInputState == KeyboardInputState::TEXT_INPUT)
         SDL_StartTextInput();
      else
         SDL_StopTextInput();

      // Done until we need to update it again.
      mInputState = KeyboardInputState::NONE;
   }
}

PlatformWindow * PlatformWindowManagerSDL::getWindowById( WindowId id )
{
   // Walk the list and find the matching id, if any.
   PlatformWindowSDL *win = mWindowListHead;
   while(win)
   {
      if(win->getWindowId() == id)
         return win;

      win = win->mNextWindow;
   }

   return NULL;
}

PlatformWindow * PlatformWindowManagerSDL::getFirstWindow()
{
   return mWindowListHead != NULL ? mWindowListHead : NULL;
}

PlatformWindow* PlatformWindowManagerSDL::getFocusedWindow()
{
   PlatformWindowSDL* window = mWindowListHead;
   while( window )
   {
      if( window->isFocused() )
         return window;

      window = window->mNextWindow;
   }

   return NULL;
}

void PlatformWindowManagerSDL::linkWindow( PlatformWindowSDL *w )
{
   w->mNextWindow = mWindowListHead;
   mWindowListHead = w;
}

void PlatformWindowManagerSDL::unlinkWindow( PlatformWindowSDL *w )
{
   PlatformWindowSDL **walk = &mWindowListHead;
   while(*walk)
   {
      if(*walk != w)
      {
         // Advance to next item in list.
         walk = &(*walk)->mNextWindow;
         continue;
      }

      // Got a match - unlink and return.
      *walk = (*walk)->mNextWindow;
      return;
   }
}

void PlatformWindowManagerSDL::_processCmdLineArgs( const S32 argc, const char **argv )
{
   // TODO SDL
}

void PlatformWindowManagerSDL::lowerCurtain()
{
   if(mCurtainWindow)
      return;

   // TODO SDL
}

void PlatformWindowManagerSDL::raiseCurtain()
{
   if(!mCurtainWindow)
      return;

   // TODO SDL
}

void PlatformWindowManagerSDL::updateSDLTextInputState(KeyboardInputState state)
{
   // Force update state. This will respond at the end of the event loop.
   mInputState = state;
}

void Platform::openFolder(const char* path )
{
    AssertFatal(0, "Not Implemented");
}

void Platform::openFile(const char* path )
{
    AssertFatal(0, "Not Implemented");
}

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

namespace GL
{
   void gglPerformBinds();
}

void InitWindowingSystem()
{

}

AFTER_MODULE_INIT(gfx)
{
#if !defined(TORQUE_DEDICATED)
   int res = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS | SDL_INIT_NOPARACHUTE);
   AssertFatal(res != -1, avar("SDL error:%s", SDL_GetError()));

   // By default, SDL enables text input. We disable it on initialization, and
   // we will enable it whenever the time is right.
   SDL_StopTextInput();
#endif
}
<|endoftext|>


<commit_before>/*
 * build_book_uncross.cpp
 *
 *  Created on: Mar 26, 2014
 *      Author: deepan

  Contains the main routine
 */
#include "book_routines.h"
#include "compute_routines.h"
#include "read_and_update.h"
#include "read_next_message.h"
#include "perform_execution.h"

/*
   Remove "dead orders" when execution messages disobey priorities.
   To run, pass command line parameters for the ticker file and the \delta

*/

using namespace std;

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

 fstream input_file;
 executionSpecifications o_execSpecs;
 //Parameters to be read from command line
 string ticker; uint64_t jumpTime;
 if(argc == 6)
  {
   ticker = argv[1];
   o_execSpecs.initialize(ticker, *argv[2], atoi(argv[3]), atoi(argv[4]),0,0,0,0,atoi(argv[5]));

   jumpTime = atoi(argv[5]);
  }
 else
  {
    cerr<<endl<<"Need to specify parameters: ./build_book_uncross <ticker_file> <delta>";
    exit(1);
  }
 char *buffer; unsigned long buffer_length;
 vector<levelOneBook> closingBooks;
 vector<levelOneBook> closingConditionalBooks;
 vector<oneDState> positiveStates, negativeStates;
 positiveStates.resize(MAX_IMBALANCE+1);
 negativeStates.resize(MAX_IMBALANCE+1);
 oneDState balancedState;

 closingBooks.resize(static_cast<int>(jumpTime+1));
 unsigned int closingBookIndex = 0;
 globalTime o_globalTime, o_nextGlobalTime;

 map<uint64_t, order> orderID_to_properties;
 map<uint32_t, map<uint64_t, order> > bidBook;
 map<uint32_t, map<uint64_t, order> > askBook;
 input_file.open(ticker.c_str(),ios::in | ios::binary);

 if(input_file == NULL)
   {
     exit(1);
   }
  else
   {
     input_file.seekg (0, input_file.end);
     buffer_length = input_file.tellg();
     input_file.seekg (0, input_file.beg);
     buffer = new char[buffer_length];
     input_file.read (buffer,buffer_length);
     input_file.close();
     int buffer_index = 0;

     bool end_of_day = 0;
     bool start_of_trading = 0;

     while(!end_of_day)
      {
       char typeOfMessage = buffer[buffer_index];
       read_and_update(typeOfMessage, buffer, buffer_index, bidBook, askBook, orderID_to_properties,o_globalTime);
       start_of_trading = (o_globalTime.second == NINE_THIRTY_AM || start_of_trading);
       o_nextGlobalTime = o_globalTime;
       read_next_message(buffer[buffer_index], buffer, buffer_index, o_nextGlobalTime);//Simply reads the next msg. Pointer is not moved

       if(start_of_trading && o_globalTime.second < TWO_THIRTY_PM && o_nextGlobalTime.second < TWO_THIRTY_PM)
        {
    	   if(o_globalTime.timeStampToMs() != o_nextGlobalTime.timeStampToMs())
             {
    		   	   int numMultiples = o_nextGlobalTime.timeStampToMs() - o_globalTime.timeStampToMs()+(o_globalTime.nanoSecond%(MS_TO_NS) == 0);
    		   	   levelOneBook lob = bookToLevelOne(bidBook,askBook);
    		   	   marketOrder t_MO;

    		   	   for(int i = 0; i< numMultiples; i++)
    		   	   {
    		   		   predictions o_pred;
    		   		   o_pred = predict(lob, positiveStates, negativeStates, balancedState,jumpTime);
    		   		   closingBooks[closingBookIndex].initialize(lob.bidShares, lob.askShares, lob.bidPrice, lob.askPrice, o_pred);
    		   		   closingConditionalBooks.push_back(closingBooks[closingBookIndex]);
    		   		   closingBookIndex = ((closingBookIndex == (jumpTime))? 0: (closingBookIndex+1));
    		   	   }
    		   	   int conditionalFutureIndex = closingConditionalBooks.size()-numMultiples;
    		   	   if(o_globalTime.second > NINE_THIRTY_AM + jumpTime/(S_TO_MS))
    		   	   {
    		   		  int pastIndex = ((closingBookIndex == jumpTime)?0:(closingBookIndex+1));
    		   		  levelOneBook pastLevelOneBook = closingBooks[pastIndex];
    		   		  levelOneBook currentLevelOneBook = closingBooks[closingBookIndex];
    		   		  updateFeatures(positiveStates,negativeStates,balancedState,currentLevelOneBook,pastLevelOneBook);
    		   	   }//Update features that look ahead for a constant time interval
    		   	   if(closingConditionalBooks.begin()->bidPrice != closingConditionalBooks.rbegin()->bidPrice ||
						closingConditionalBooks.begin()->askPrice != closingConditionalBooks.rbegin()->askPrice)//Mid price has changed
    		   	   {
    		   		   updateConditionalFeatures(closingConditionalBooks,positiveStates, negativeStates, balancedState, conditionalFutureIndex);
    		   	   }

          	}//If for sampling time
        }

		 if(start_of_trading && o_globalTime.second == TWO_THIRTY_PM && typeOfMessage == 'T')
        {
		   cerr<<endl<<"Calling perform execution";
           perform_execution(bidBook, askBook, orderID_to_properties, o_globalTime, positiveStates, negativeStates, balancedState, buffer, buffer_index, o_execSpecs);
        }
       end_of_day = (o_globalTime.second == FOUR_PM);
     }

   }

 delete[] buffer;
 return 0;
}

<commit_msg>commit on may 9<commit_after>/*
 * build_book_uncross.cpp
 *
 *  Created on: Mar 26, 2014
 *      Author: deepan

  Contains the main routine
 */
#include "book_routines.h"
#include "compute_routines.h"
#include "read_and_update.h"
#include "read_next_message.h"
#include "perform_execution.h"

/*
   Remove "dead orders" when execution messages disobey priorities.
   To run, pass command line parameters for the ticker file and the \delta

   Need to introduce a parameter for error rate threshold.

*/

using namespace std;

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

 fstream input_file;
 executionSpecifications o_execSpecs;
 //Parameters to be read from command line
 string ticker; uint64_t jumpTime;
 if(argc == 6)
  {
   ticker = argv[1];
   o_execSpecs.initialize(ticker, *argv[2], atoi(argv[3]), atoi(argv[4]),0,0,0,0,atoi(argv[5]));

   jumpTime = atoi(argv[5]);
  }
 else
  {
    cerr<<endl<<"Need to specify parameters: ./build_book_uncross <ticker_file> <delta>";
    exit(1);
  }
 char *buffer; unsigned long buffer_length;
 vector<levelOneBook> closingBooks;
 vector<levelOneBook> closingConditionalBooks;
 vector<oneDState> positiveStates, negativeStates;
 positiveStates.resize(MAX_IMBALANCE+1);
 negativeStates.resize(MAX_IMBALANCE+1);
 oneDState balancedState;

 closingBooks.resize(static_cast<int>(jumpTime+1));
 unsigned int closingBookIndex = 0;
 globalTime o_globalTime, o_nextGlobalTime;

 map<uint64_t, order> orderID_to_properties;
 map<uint32_t, map<uint64_t, order> > bidBook;
 map<uint32_t, map<uint64_t, order> > askBook;
 input_file.open(ticker.c_str(),ios::in | ios::binary);

 if(input_file == NULL)
   {
     exit(1);
   }
  else
   {
     input_file.seekg (0, input_file.end);
     buffer_length = input_file.tellg();
     input_file.seekg (0, input_file.beg);
     buffer = new char[buffer_length];
     input_file.read (buffer,buffer_length);
     input_file.close();
     int buffer_index = 0;

     bool end_of_day = 0;
     bool start_of_trading = 0;

     while(!end_of_day)
      {
       char typeOfMessage = buffer[buffer_index];
       read_and_update(typeOfMessage, buffer, buffer_index, bidBook, askBook, orderID_to_properties,o_globalTime);
       start_of_trading = (o_globalTime.second == NINE_THIRTY_AM || start_of_trading);
       o_nextGlobalTime = o_globalTime;
       read_next_message(buffer[buffer_index], buffer, buffer_index, o_nextGlobalTime);//Simply reads the next msg. Pointer is not moved

       if(start_of_trading && o_globalTime.second < TWO_THIRTY_PM && o_nextGlobalTime.second < TWO_THIRTY_PM)
        {
    	   if(o_globalTime.timeStampToMs() != o_nextGlobalTime.timeStampToMs())
             {
    		   	   int numMultiples = o_nextGlobalTime.timeStampToMs() - o_globalTime.timeStampToMs()+(o_globalTime.nanoSecond%(MS_TO_NS) == 0);
    		   	   levelOneBook lob = bookToLevelOne(bidBook,askBook);
    		   	   marketOrder t_MO;

    		   	   for(int i = 0; i< numMultiples; i++)
    		   	   {
    		   		   predictions o_pred;
    		   		   o_pred = predict(lob, positiveStates, negativeStates, balancedState,jumpTime);
    		   		   closingBooks[closingBookIndex].initialize(lob.bidShares, lob.askShares, lob.bidPrice, lob.askPrice, o_pred);
    		   		   closingConditionalBooks.push_back(closingBooks[closingBookIndex]);
    		   		   closingBookIndex = ((closingBookIndex == (jumpTime))? 0: (closingBookIndex+1));
    		   	   }
    		   	   int conditionalFutureIndex = closingConditionalBooks.size()-numMultiples;
    		   	   if(o_globalTime.second > NINE_THIRTY_AM + jumpTime/(S_TO_MS))
    		   	   {
    		   		  int pastIndex = ((closingBookIndex == jumpTime)?0:(closingBookIndex+1));
    		   		  levelOneBook pastLevelOneBook = closingBooks[pastIndex];
    		   		  levelOneBook currentLevelOneBook = closingBooks[closingBookIndex];
    		   		  updateFeatures(positiveStates,negativeStates,balancedState,currentLevelOneBook,pastLevelOneBook);
    		   	   }//Update features that look ahead for a constant time interval
    		   	   if(closingConditionalBooks.begin()->bidPrice != closingConditionalBooks.rbegin()->bidPrice ||
						closingConditionalBooks.begin()->askPrice != closingConditionalBooks.rbegin()->askPrice)//Mid price has changed
    		   	   {
    		   		   updateConditionalFeatures(closingConditionalBooks,positiveStates, negativeStates, balancedState, conditionalFutureIndex);
    		   	   }

          	}//If for sampling time
        }

		 if(start_of_trading && o_globalTime.second == TWO_THIRTY_PM && typeOfMessage == 'T')
        {
		   cerr<<endl<<"Calling perform execution";
           perform_execution(bidBook, askBook, orderID_to_properties, o_globalTime, positiveStates, negativeStates, balancedState, buffer, buffer_index, o_execSpecs);
        }
       end_of_day = (o_globalTime.second == FOUR_PM);
     }

   }

 delete[] buffer;
 return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dlgname.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:35:05 $
 *
 *  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 SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#include <tools/ref.hxx>
#include <tools/list.hxx>
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#pragma hdrstop

#include "dialogs.hrc"

#include "dlgname.hxx"
#include "defdlgname.hxx" //CHINA001
#include "dlgname.hrc"
#include "dialmgr.hxx"

/*************************************************************************
|*
|* Dialog zum Editieren eines Namens
|*
\************************************************************************/

SvxNameDialog::SvxNameDialog( Window* pWindow, const String& rName, const String& rDesc ) :
    ModalDialog     ( pWindow, ResId( RID_SVXDLG_NAME, DIALOG_MGR() ) ),
    aFtDescription      ( this, ResId( FT_DESCRIPTION ) ),
    aEdtName            ( this, ResId( EDT_STRING ) ),
    aBtnOK              ( this, ResId( BTN_OK ) ),
    aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
    aBtnHelp            ( this, ResId( BTN_HELP ) )
{
    FreeResource();

    aFtDescription.SetText( rDesc );
    aEdtName.SetText( rName );
    aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX));
    ModifyHdl(&aEdtName);
    aEdtName.SetModifyHdl(LINK(this, SvxNameDialog, ModifyHdl));
}
/* -----------------------------27.02.2002 15:22------------------------------

 ---------------------------------------------------------------------------*/
IMPL_LINK(SvxNameDialog, ModifyHdl, Edit*, pEdit)
{
    if(aCheckNameHdl.IsSet())
        aBtnOK.Enable(aCheckNameHdl.Call(this) > 0);
    return 0;
}

/*************************************************************************
|*
|* Dialog zum Abbrechen, Speichern oder Hinzufuegen
|*
\************************************************************************/

SvxMessDialog::SvxMessDialog( Window* pWindow, const String& rText, const String& rDesc, Image* pImg ) :
    ModalDialog     ( pWindow, ResId( RID_SVXDLG_MESSBOX, DIALOG_MGR() ) ),
    aFtDescription      ( this, ResId( FT_DESCRIPTION ) ),
    aBtn1               ( this, ResId( BTN_1 ) ),
    aBtn2               ( this, ResId( BTN_2 ) ),
    aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
    aFtImage            ( this )
{
    FreeResource();

    if( pImg )
    {
        pImage = new Image( *pImg );
        aFtImage.SetImage( *pImage );
        aFtImage.SetStyle( ( aFtImage.GetStyle()/* | WB_NOTABSTOP */) & ~WB_3DLOOK );
        aFtImage.SetPosSizePixel( LogicToPixel( Point( 3, 6 ), MAP_APPFONT ),
                                  aFtImage.GetImage().GetSizePixel() );
        aFtImage.Show();
    }

    SetText( rText );
    aFtDescription.SetText( rDesc );

    aBtn1.SetClickHdl( LINK( this, SvxMessDialog, Button1Hdl ) );
    aBtn2.SetClickHdl( LINK( this, SvxMessDialog, Button2Hdl ) );
}

SvxMessDialog::~SvxMessDialog()
{
    if( pImage )
        delete pImage;
}

/*************************************************************************/

IMPL_LINK_INLINE_START( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )
{
    EndDialog( RET_BTN_1 );
    return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )

/*************************************************************************/

IMPL_LINK_INLINE_START( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )
{
    EndDialog( RET_BTN_2 );
    return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )

/*************************************************************************/

void SvxMessDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt )
{
    switch ( nBtnId )
    {
        case MESS_BTN_1:
            aBtn1.SetText( rNewTxt );
            break;

        case MESS_BTN_2:
            aBtn2.SetText( rNewTxt );
            break;

        default:
            DBG_ERROR( "Falsche Button-Nummer!!!" );
    }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.430); FILE MERGED 2005/09/05 14:19:23 rt 1.5.430.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgname.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:59:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#include <tools/ref.hxx>
#include <tools/list.hxx>
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#pragma hdrstop

#include "dialogs.hrc"

#include "dlgname.hxx"
#include "defdlgname.hxx" //CHINA001
#include "dlgname.hrc"
#include "dialmgr.hxx"

/*************************************************************************
|*
|* Dialog zum Editieren eines Namens
|*
\************************************************************************/

SvxNameDialog::SvxNameDialog( Window* pWindow, const String& rName, const String& rDesc ) :
    ModalDialog     ( pWindow, ResId( RID_SVXDLG_NAME, DIALOG_MGR() ) ),
    aFtDescription      ( this, ResId( FT_DESCRIPTION ) ),
    aEdtName            ( this, ResId( EDT_STRING ) ),
    aBtnOK              ( this, ResId( BTN_OK ) ),
    aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
    aBtnHelp            ( this, ResId( BTN_HELP ) )
{
    FreeResource();

    aFtDescription.SetText( rDesc );
    aEdtName.SetText( rName );
    aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX));
    ModifyHdl(&aEdtName);
    aEdtName.SetModifyHdl(LINK(this, SvxNameDialog, ModifyHdl));
}
/* -----------------------------27.02.2002 15:22------------------------------

 ---------------------------------------------------------------------------*/
IMPL_LINK(SvxNameDialog, ModifyHdl, Edit*, pEdit)
{
    if(aCheckNameHdl.IsSet())
        aBtnOK.Enable(aCheckNameHdl.Call(this) > 0);
    return 0;
}

/*************************************************************************
|*
|* Dialog zum Abbrechen, Speichern oder Hinzufuegen
|*
\************************************************************************/

SvxMessDialog::SvxMessDialog( Window* pWindow, const String& rText, const String& rDesc, Image* pImg ) :
    ModalDialog     ( pWindow, ResId( RID_SVXDLG_MESSBOX, DIALOG_MGR() ) ),
    aFtDescription      ( this, ResId( FT_DESCRIPTION ) ),
    aBtn1               ( this, ResId( BTN_1 ) ),
    aBtn2               ( this, ResId( BTN_2 ) ),
    aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
    aFtImage            ( this )
{
    FreeResource();

    if( pImg )
    {
        pImage = new Image( *pImg );
        aFtImage.SetImage( *pImage );
        aFtImage.SetStyle( ( aFtImage.GetStyle()/* | WB_NOTABSTOP */) & ~WB_3DLOOK );
        aFtImage.SetPosSizePixel( LogicToPixel( Point( 3, 6 ), MAP_APPFONT ),
                                  aFtImage.GetImage().GetSizePixel() );
        aFtImage.Show();
    }

    SetText( rText );
    aFtDescription.SetText( rDesc );

    aBtn1.SetClickHdl( LINK( this, SvxMessDialog, Button1Hdl ) );
    aBtn2.SetClickHdl( LINK( this, SvxMessDialog, Button2Hdl ) );
}

SvxMessDialog::~SvxMessDialog()
{
    if( pImage )
        delete pImage;
}

/*************************************************************************/

IMPL_LINK_INLINE_START( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )
{
    EndDialog( RET_BTN_1 );
    return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button1Hdl, Button *, EMPTYARG )

/*************************************************************************/

IMPL_LINK_INLINE_START( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )
{
    EndDialog( RET_BTN_2 );
    return 0;
}
IMPL_LINK_INLINE_END( SvxMessDialog, Button2Hdl, Button *, EMPTYARG )

/*************************************************************************/

void SvxMessDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt )
{
    switch ( nBtnId )
    {
        case MESS_BTN_1:
            aBtn1.SetText( rNewTxt );
            break;

        case MESS_BTN_2:
            aBtn2.SetText( rNewTxt );
            break;

        default:
            DBG_ERROR( "Falsche Button-Nummer!!!" );
    }
}

<|endoftext|>