<commit_before>/*
 * DamageOverTimeList.cpp
 *
 *  Created on: 04/06/2010
 *      Author: victor
 */

#include "DamageOverTimeList.h"
#include "server/zone/objects/creature/CreatureObject.h"

uint64 DamageOverTimeList::activateDots(CreatureObject* victim) {
	uint64 states = 0;
	uint64 statesBefore = 0;

	Locker guardLocker(&guard);

	for (int i = 0; i < size(); ++i) {
		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); ++j) {
			DamageOverTime* dot = &vector->elementAt(j);
			statesBefore |= dot->getType();

			if (dot->nextTickPast()) {
				//guard.unlock();

				try {
					dot->applyDot(victim);
				} catch (...) {
					//guard.wlock();

					throw;
				}

				//guard.wlock();
			}

			Time nTime = dot->getNextTick();

			if (nextTick.isPast() || (!dot->isPast() && (nTime.compareTo(nextTick) > 0)))
				nextTick = nTime;

			if (!dot->isPast()) {
				states |= dot->getType();
			} else {
				vector->remove(j);
				--j;

				// Since the vector only seems to ever be of size one, this should always be true
				if (vector->size() == 0) {
					remove(i);
					--i;
				}
			}
		}
	}

	int statesRemoved = states ^ statesBefore;

	if( statesRemoved & CreatureState::BLEEDING )
		victim->clearState(CreatureState::BLEEDING);

	if( statesRemoved & CreatureState::POISONED )
		victim->clearState(CreatureState::POISONED);

	if( statesRemoved & CreatureState::DISEASED )
		victim->clearState(CreatureState::DISEASED);

	if( statesRemoved & CreatureState::ONFIRE )
		victim->clearState(CreatureState::ONFIRE);

	if (nextTick.isPast()) {
		dot = false;
		removeAll();

		states = 0;
	}

	return states;
}

int DamageOverTimeList::getStrength(uint8 pool, uint64 dotType) {
	Locker locker(&guard);

	Vector<DamageOverTime>* vector;
	int strength = 0;

	for(int i = 0; i < size(); i++)
	{
		vector = &elementAt(i).getValue();
		for(int j = 0; j < vector->size(); j++)
		{
			DamageOverTime* currentDot = &vector->elementAt(j);
			if(currentDot->getType() == dotType && (currentDot->getAttribute() == pool))
			{
				if (!currentDot->isPast()) {
					strength+=currentDot->getStrength();
				}
			}
		}
	}
	return strength;
}

uint32 DamageOverTimeList::addDot(CreatureObject* victim, CreatureObject* attacker, uint64 objectID, uint32 duration, uint64 dotType, uint8 pool, uint32 strength, float potency, uint32 defense, int secondaryStrength) {
	Locker locker(&guard);

	if (strength == 0 || duration == 0)
		return 0;

	// determine chance to hit, if no hit, just return 0. potency of less than 0 can't be resisted
	if (potency > 0 && System::random(100) >= MAX(5.f, MIN(potency * (80.f / (100.f + defense)), 95.f)))
		return 0;

	int oldStrength = getStrength(pool, dotType);

	int durationMod = 0;

	switch (dotType) {
	case CreatureState::POISONED:
		durationMod = victim->getSkillMod("dissipation_poison");
		break;
	case CreatureState::DISEASED:
		durationMod = victim->getSkillMod("dissipation_disease");
		break;
	case CreatureState::ONFIRE:
		durationMod = victim->getSkillMod("dissipation_fire");
		break;
	case CreatureState::BLEEDING:
		durationMod = victim->getSkillMod("dissipation_bleeding");
		break;
	default:
		break;
	}

	if (durationMod > 0) {
		if (durationMod > 90) durationMod = 90;
		duration = MAX(1, (int)(duration * (1.f - (durationMod / 100.f))));
	}

	//only 1 disease per bar allowed
	if(dotType == CreatureState::DISEASED)
		objectID = Long::hashCode(CreatureState::DISEASED);

	DamageOverTime newDot(attacker, dotType, pool, strength, duration, secondaryStrength);
	int dotPower = newDot.initDot(victim);

	uint64 key = generateKey(dotType, pool, objectID);

	if (contains(key)) {
		Vector<DamageOverTime>* vector = &get(key);
		Vector<DamageOverTime> newVec;

		// This seems to only ever put one value in the DOT vector. This needs to remain a vector to
		// maintain the integrity of the db.
		for (int i = 0; i < vector->size(); ++i) {
			DamageOverTime dot = vector->get(i);

			if (newDot.getStrength() >= dot.getStrength()) {
				newDot.setNextTick(dot.getNextTick());
				newVec.add(newDot);
			} else
				newVec.add(dot);

			drop(key);
			put(key, newVec);
		}
	} else {
		Vector<DamageOverTime> newVector;
		newVector.add(newDot);
		put(key, newVector);
	}

	Time nTime = newDot.getNextTick();

	if (isEmpty() || nextTick.isPast() || nTime.compareTo(nextTick) > 0)
		nextTick = nTime;

	if(oldStrength == 0)
		sendStartMessage(victim, dotType);
	else
		sendIncreaseMessage(victim, dotType);

	dot = true;

	locker.release();
	victim->setState(dotType);

	return dotPower;
}

bool DamageOverTimeList::healState(CreatureObject* victim, uint64 dotType, float reduction) {
	Locker locker(&guard);

	if (!hasDot())
		return reduction;

	VectorMap<uint64, DamageOverTime*> timeMap;

	for (int i = 0; i < size(); i++) {
		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); j++) {
			DamageOverTime* dot = &vector->elementAt(j);

			if (dot->getType() == dotType && !dot->isPast())
				timeMap.put(dot->getApplied().getMiliTime(), dot);
		}
	}

	bool expired = true;

	float reductionLeft = reduction;

	for (int i = 0; i < timeMap.size(); i++) {
		DamageOverTime* dot = timeMap.elementAt(i).getValue();

		if (!dot->isPast()) {
			if (reductionLeft >= dot->getStrength()) {
				reductionLeft -= dot->getStrength();
				dot->reduceTick(dot->getStrength());
				expired = expired && true;
			} else {
				dot->reduceTick(reductionLeft);
				reductionLeft = 0;
				expired = false;
				break;
			}
		}
	}

	if (expired) {
		locker.release();
		victim->clearState(dotType);
		return true;
	}

	sendDecreaseMessage(victim, dotType);

	return false;
}

bool DamageOverTimeList::hasDot(uint64 dotType) {
	Locker locker(&guard);

	bool hasDot = false;

	for (int i = 0; i < size(); ++i) {
		uint64 type = elementAt(i).getKey();

		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); ++j) {
			DamageOverTime* dot = &vector->elementAt(j);

			if (dot->getType() == dotType)
				hasDot = true;
		}
	}

	return hasDot;
}

void DamageOverTimeList::clear(CreatureObject* creature) {
	Locker locker(&guard);

	dot = false;

	for (int i = 0; i < size(); ++i) {
		uint64 type = elementAt(i).getKey();

		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); ++j) {
			DamageOverTime* dot = &vector->elementAt(j);

			creature->clearState(dot->getType());
		}
	}

	removeAll();
}

void DamageOverTimeList::sendStartMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:start_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:start_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:start_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:start_fire");
		break;
	}
}

void DamageOverTimeList::sendStopMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:stop_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:stop_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:stop_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:stop_fire");
		break;
	}
}

void DamageOverTimeList::sendIncreaseMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:increase_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:increase_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:increase_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:increase_fire");
		break;
	}
}

void DamageOverTimeList::sendDecreaseMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:decrease_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:decrease_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:decrease_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:decrease_fire");
		break;
	}
}

<commit_msg>[Fixed] dot list issue<commit_after>/*
 * DamageOverTimeList.cpp
 *
 *  Created on: 04/06/2010
 *      Author: victor
 */

#include "DamageOverTimeList.h"
#include "server/zone/objects/creature/CreatureObject.h"

uint64 DamageOverTimeList::activateDots(CreatureObject* victim) {
	uint64 states = 0;
	uint64 statesBefore = 0;

	Locker guardLocker(&guard);

	for (int i = size() - 1; i >= 0 ; --i) {
		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = vector->size() - 1; j >= 0 ; --j) {
			DamageOverTime* dot = &vector->elementAt(j);
			statesBefore |= dot->getType();

			if (dot->nextTickPast()) {
				//guard.unlock();

				try {
					dot->applyDot(victim);
				} catch (...) {
					//guard.wlock();

					throw;
				}

				//guard.wlock();
			}

			Time nTime = dot->getNextTick();

			if (nextTick.isPast() || (!dot->isPast() && (nTime.compareTo(nextTick) > 0)))
				nextTick = nTime;

			if (!dot->isPast()) {
				states |= dot->getType();
			} else {
				if (vector->size() == 1) {
					vector->remove(j);
					remove(i);
				} else {
					vector->remove(j);
				}
			}
		}
	}

	int statesRemoved = states ^ statesBefore;

	if( statesRemoved & CreatureState::BLEEDING )
		victim->clearState(CreatureState::BLEEDING);

	if( statesRemoved & CreatureState::POISONED )
		victim->clearState(CreatureState::POISONED);

	if( statesRemoved & CreatureState::DISEASED )
		victim->clearState(CreatureState::DISEASED);

	if( statesRemoved & CreatureState::ONFIRE )
		victim->clearState(CreatureState::ONFIRE);

	if (nextTick.isPast()) {
		dot = false;
		removeAll();

		states = 0;
	}

	return states;
}

int DamageOverTimeList::getStrength(uint8 pool, uint64 dotType) {
	Locker locker(&guard);

	Vector<DamageOverTime>* vector;
	int strength = 0;

	for(int i = 0; i < size(); i++)
	{
		vector = &elementAt(i).getValue();
		for(int j = 0; j < vector->size(); j++)
		{
			DamageOverTime* currentDot = &vector->elementAt(j);
			if(currentDot->getType() == dotType && (currentDot->getAttribute() == pool))
			{
				if (!currentDot->isPast()) {
					strength+=currentDot->getStrength();
				}
			}
		}
	}
	return strength;
}

uint32 DamageOverTimeList::addDot(CreatureObject* victim, CreatureObject* attacker, uint64 objectID, uint32 duration, uint64 dotType, uint8 pool, uint32 strength, float potency, uint32 defense, int secondaryStrength) {
	Locker locker(&guard);

	if (strength == 0 || duration == 0)
		return 0;

	// determine chance to hit, if no hit, just return 0. potency of less than 0 can't be resisted
	if (potency > 0 && System::random(100) >= MAX(5.f, MIN(potency * (80.f / (100.f + defense)), 95.f)))
		return 0;

	int oldStrength = getStrength(pool, dotType);

	int durationMod = 0;

	switch (dotType) {
	case CreatureState::POISONED:
		durationMod = victim->getSkillMod("dissipation_poison");
		break;
	case CreatureState::DISEASED:
		durationMod = victim->getSkillMod("dissipation_disease");
		break;
	case CreatureState::ONFIRE:
		durationMod = victim->getSkillMod("dissipation_fire");
		break;
	case CreatureState::BLEEDING:
		durationMod = victim->getSkillMod("dissipation_bleeding");
		break;
	default:
		break;
	}

	if (durationMod > 0) {
		if (durationMod > 90) durationMod = 90;
		duration = MAX(1, (int)(duration * (1.f - (durationMod / 100.f))));
	}

	//only 1 disease per bar allowed
	if(dotType == CreatureState::DISEASED)
		objectID = Long::hashCode(CreatureState::DISEASED);

	DamageOverTime newDot(attacker, dotType, pool, strength, duration, secondaryStrength);
	int dotPower = newDot.initDot(victim);

	uint64 key = generateKey(dotType, pool, objectID);

	if (contains(key)) {
		Vector<DamageOverTime>* vector = &get(key);
		Vector<DamageOverTime> newVec;

		// This seems to only ever put one value in the DOT vector. This needs to remain a vector to
		// maintain the integrity of the db.
		for (int i = 0; i < vector->size(); ++i) {
			DamageOverTime dot = vector->get(i);

			if (newDot.getStrength() >= dot.getStrength()) {
				newDot.setNextTick(dot.getNextTick());
				newVec.add(newDot);
			} else
				newVec.add(dot);

			drop(key);
			put(key, newVec);
		}
	} else {
		Vector<DamageOverTime> newVector;
		newVector.add(newDot);
		put(key, newVector);
	}

	Time nTime = newDot.getNextTick();

	if (isEmpty() || nextTick.isPast() || nTime.compareTo(nextTick) > 0)
		nextTick = nTime;

	if(oldStrength == 0)
		sendStartMessage(victim, dotType);
	else
		sendIncreaseMessage(victim, dotType);

	dot = true;

	locker.release();
	victim->setState(dotType);

	return dotPower;
}

bool DamageOverTimeList::healState(CreatureObject* victim, uint64 dotType, float reduction) {
	Locker locker(&guard);

	if (!hasDot())
		return reduction;

	VectorMap<uint64, DamageOverTime*> timeMap;

	for (int i = 0; i < size(); i++) {
		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); j++) {
			DamageOverTime* dot = &vector->elementAt(j);

			if (dot->getType() == dotType && !dot->isPast())
				timeMap.put(dot->getApplied().getMiliTime(), dot);
		}
	}

	bool expired = true;

	float reductionLeft = reduction;

	for (int i = 0; i < timeMap.size(); i++) {
		DamageOverTime* dot = timeMap.elementAt(i).getValue();

		if (!dot->isPast()) {
			if (reductionLeft >= dot->getStrength()) {
				reductionLeft -= dot->getStrength();
				dot->reduceTick(dot->getStrength());
				expired = expired && true;
			} else {
				dot->reduceTick(reductionLeft);
				reductionLeft = 0;
				expired = false;
				break;
			}
		}
	}

	if (expired) {
		locker.release();
		victim->clearState(dotType);
		return true;
	}

	sendDecreaseMessage(victim, dotType);

	return false;
}

bool DamageOverTimeList::hasDot(uint64 dotType) {
	Locker locker(&guard);

	bool hasDot = false;

	for (int i = 0; i < size(); ++i) {
		uint64 type = elementAt(i).getKey();

		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); ++j) {
			DamageOverTime* dot = &vector->elementAt(j);

			if (dot->getType() == dotType)
				hasDot = true;
		}
	}

	return hasDot;
}

void DamageOverTimeList::clear(CreatureObject* creature) {
	Locker locker(&guard);

	dot = false;

	for (int i = 0; i < size(); ++i) {
		uint64 type = elementAt(i).getKey();

		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = 0; j < vector->size(); ++j) {
			DamageOverTime* dot = &vector->elementAt(j);

			creature->clearState(dot->getType());
		}
	}

	removeAll();
}

void DamageOverTimeList::sendStartMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:start_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:start_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:start_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:start_fire");
		break;
	}
}

void DamageOverTimeList::sendStopMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:stop_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:stop_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:stop_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:stop_fire");
		break;
	}
}

void DamageOverTimeList::sendIncreaseMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:increase_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:increase_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:increase_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:increase_fire");
		break;
	}
}

void DamageOverTimeList::sendDecreaseMessage(CreatureObject* victim, uint64 type) {
	if (!victim->isPlayerCreature())
		return;

	switch(type) {
	case CreatureState::BLEEDING:
		victim->sendSystemMessage("@dot_message:decrease_bleeding");
		break;
	case CreatureState::POISONED:
		victim->sendSystemMessage("@dot_message:decrease_poisoned");
		break;
	case CreatureState::DISEASED:
		victim->sendSystemMessage("@dot_message:decrease_diseased");
		break;
	case CreatureState::ONFIRE:
		victim->sendSystemMessage("@dot_message:decrease_fire");
		break;
	}
}

<|endoftext|>


<commit_before>#include "TolonSpellCheck.h"
#include "tscModule.h"
#include "tscSession.h"

using namespace TolonSpellCheck;

HINSTANCE g_hInstDll;

// Error-handling Utils

static const char* s_szLastError;

// Error strings (to be localised)
static const char* const s_szErrIntNullModulePtr =
	"Internal Error, a null module pointer was encountered. Please contact technical support.";
static const char* const s_szErrParamWasNull =
	"Error, one or more parameters were null.";

/*static void Error_GetLastModuleError(CModule* pM)
{
	s_szLastError = pM->GetLastError();
}*/

static tsc_result Error_Internal_NullModulePtr()
{
	s_szLastError = s_szErrIntNullModulePtr;
	return TSC_E_FAIL;
}

static tsc_result Error_ParamWasNull()
{
	s_szLastError = s_szErrParamWasNull;
	return TSC_E_FAIL;
}

// The exported DLL functions

tsc_result TSC_CALLTYPE
	tscInit( TSC_INIT_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->Init(pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscUninit( void )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->Uninit();
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscGetVersion( TSC_VERSION_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->GetVersion(pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

/*tsc_result TSC_CALLTYPE
	tscGetLastError( const char ** ppszError )
{
	if (!ppszError)
		return Error_ParamWasNull();

	if (s_szLastError)
	{
		*ppszError = s_szLastError;
		return TSC_S_OK;
	}
	else
	{
		*ppszError = NULL;
		return TSC_S_FALSE;
	}
}*/

const char* TSC_CALLTYPE
	tscGetLastError()
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return s_szLastError;
	else
		return pM->GetLastError();
}

tsc_result TSC_CALLTYPE
	tscCreateSession( tsc_cookie* pSessionID,
					  TSC_CREATESESSION_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->CreateSession(pSessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscDestroySession( tsc_cookie SessionID )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->DestroySession(SessionID);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscGetSessionOptions( tsc_cookie SessionID,
						  TSC_SESSIONOPTIONS_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->GetSessionOptions(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscSetSessionOptions( tsc_cookie SessionID,
						  TSC_SESSIONOPTIONS_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->SetSessionOptions(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscShowOptionsWindow( tsc_cookie SessionID,
						  TSC_SHOWOPTIONSWINDOW_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->ShowOptionsWindow(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscCheckSpelling( tsc_cookie SessionID,
					  TSC_CHECKSPELLING_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->CheckSpelling(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscCheckWord( tsc_cookie SessionID,
				  TSC_CHECKWORD_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->CheckWord(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

BOOL WINAPI DllMain( HINSTANCE hinstDLL,  // handle to the DLL module
                     DWORD fdwReason,     // reason for calling function
                     LPVOID lpvReserved ) // reserved
{
    g_hInstDll = hinstDLL;
    return TRUE;
}
<commit_msg>defensive coding<commit_after>#include "TolonSpellCheck.h"
#include "tscModule.h"
#include "tscSession.h"

using namespace TolonSpellCheck;

HINSTANCE g_hInstDll;

// Error-handling Utils

static const char* s_szLastError;

// Error strings (to be localised)
static const char* const s_szErrIntNullModulePtr =
	"Internal Error, a null module pointer was encountered. Please contact technical support.";
static const char* const s_szErrParamWasNull =
	"Error, one or more parameters were null.";

/*static void Error_GetLastModuleError(CModule* pM)
{
	s_szLastError = pM->GetLastError();
}*/

static tsc_result Error_Internal_NullModulePtr()
{
	s_szLastError = s_szErrIntNullModulePtr;
	return TSC_E_FAIL;
}

static tsc_result Error_ParamWasNull()
{
	s_szLastError = s_szErrParamWasNull;
	return TSC_E_FAIL;
}

// The exported DLL functions

tsc_result TSC_CALLTYPE
	tscInit( TSC_INIT_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->Init(pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscUninit( void )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->Uninit();
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscGetVersion( TSC_VERSION_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->GetVersion(pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

/*tsc_result TSC_CALLTYPE
	tscGetLastError( const char ** ppszError )
{
	if (!ppszError)
		return Error_ParamWasNull();

	if (s_szLastError)
	{
		*ppszError = s_szLastError;
		return TSC_S_OK;
	}
	else
	{
		*ppszError = NULL;
		return TSC_S_FALSE;
	}
}*/

const char* TSC_CALLTYPE
	tscGetLastError()
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return s_szLastError;
	else
		return pM->GetLastError();
}

tsc_result TSC_CALLTYPE
	tscCreateSession( tsc_cookie* pSessionID,
					  TSC_CREATESESSION_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;

    if (pSessionID)
    {
	    r = pM->CreateSession(pSessionID, pData);

	    //if (TSC_FAILED(r))
		    //Error_GetLastModuleError(pM);
    }

	return r;
}

tsc_result TSC_CALLTYPE
	tscDestroySession( tsc_cookie SessionID )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->DestroySession(SessionID);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscGetSessionOptions( tsc_cookie SessionID,
						  TSC_SESSIONOPTIONS_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->GetSessionOptions(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscSetSessionOptions( tsc_cookie SessionID,
						  TSC_SESSIONOPTIONS_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->SetSessionOptions(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscShowOptionsWindow( tsc_cookie SessionID,
						  TSC_SHOWOPTIONSWINDOW_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->ShowOptionsWindow(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscCheckSpelling( tsc_cookie SessionID,
					  TSC_CHECKSPELLING_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->CheckSpelling(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

tsc_result TSC_CALLTYPE
	tscCheckWord( tsc_cookie SessionID,
				  TSC_CHECKWORD_DATA* pData )
{
	CModule* pM = CModule::GetInstance();
	if (!pM)
		return Error_Internal_NullModulePtr();

	tsc_result r = TSC_E_FAIL;
	r = pM->CheckWord(SessionID, pData);
	//if (TSC_FAILED(r))
		//Error_GetLastModuleError(pM);
	return r;
}

BOOL WINAPI DllMain( HINSTANCE hinstDLL,  // handle to the DLL module
                     DWORD fdwReason,     // reason for calling function
                     LPVOID lpvReserved ) // reserved
{
    g_hInstDll = hinstDLL;
    return TRUE;
}
<|endoftext|>


<commit_before>#include <cstdlib>

#include <tf_conversions/tf_eigen.h>
#include <moveit/kinematic_constraints/utils.h>

#include "c_container.h"
#include "moveit_container.hpp"

struct container *
container_create( const char *name_space, const char *robot_description )
{
    return new container(name_space, robot_description);
}

void
container_destroy( struct container * c)
{
    delete c;
}

int
container_set_start( struct container * c, const char *group, size_t n, const double *q )
{

    c->req.group_name = "right_arm";
    robot_state::RobotState start_state(c->robot_model);
    /* Zero positions because somebody's not inititializing their shit */
    {
        double *x = start_state.getVariablePositions();
        for( size_t i = 0; i < start_state.getVariableNames().size(); i++ ) {
            x[i] = 0;
        }
    }

    sensor_msgs::JointState start_joint_state;

    const robot_state::JointModelGroup* joint_model_group = start_state.getJointModelGroup(c->req.group_name);
    {
        std::vector<double> joint_values(n, 0.0);
        std::copy ( q, q+n, joint_values.begin() );
        start_state.setJointGroupPositions(joint_model_group, joint_values);
    }
    c->req.start_state.joint_state.name =  start_state.getVariableNames();
    {
        size_t n = c->req.start_state.joint_state.name.size();
        double *p = start_state.getVariablePositions();
        c->req.start_state.joint_state.position.resize( n );
        std::copy ( p, p+n,
                    c->req.start_state.joint_state.position.begin() );
    }

    // Print stuff
    {
        const std::vector<std::string> &link_names = joint_model_group->getLinkModelNames();
        std::string end_link =  link_names[ link_names.size()-1];
        fprintf(stderr, "Link: %s\n", end_link.c_str() );
        const Eigen::Affine3d estart_tf = start_state.getFrameTransform(end_link);

        tf::Transform start_pose;
        tf::poseEigenToTF(estart_tf, start_pose);
        tf::Quaternion start_q = start_pose.getRotation();
        tf::Vector3 start_v = start_pose.getOrigin();
        fprintf(stderr, "p_start[%lu] = {", n );
        for( size_t i = 0; i < n; i ++ ) {
            fprintf(stderr, "%f%s", q[i], (i+1==n) ? "};\n" : ", " );
        }
        fprintf(stderr,
                "r_start[4] = {%f, %f, %f, %f}\n"
                "v_start[3] = {%f, %f, %f}\n",
                start_q.x(),
                start_q.y(),
                start_q.z(),
                start_q.w(),
                start_v.x(),
                start_v.y(),
                start_v.z() );

    }

    //return c->set_start(group,n,q);
}

int
container_set_ws_goal( struct container * c, const char *name, const double quat[4], const double vec[3] )
{

    geometry_msgs::PoseStamped stamped_pose;
    stamped_pose.header.frame_id = "base";
    geometry_msgs::Pose &pose = stamped_pose.pose;

    pose.orientation.x = quat[0];
    pose.orientation.y = quat[1];
    pose.orientation.z = quat[2];
    pose.orientation.w = quat[3];
    pose.position.x = vec[0];
    pose.position.y = vec[1];
    pose.position.z = vec[2];

    robot_state::RobotState goal_state(c->robot_model);

    /* Zero positions because somebody's not inititializing their shit */
    {
        double *x = goal_state.getVariablePositions();
        for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
            x[i] = 0;
        }
    }

    const robot_state::JointModelGroup* joint_model_group = goal_state.getJointModelGroup("right_arm");
    bool got_ik = goal_state.setFromIK(joint_model_group,pose);
    fprintf(stderr, "IK: %s\n", got_ik ? "yes" : "no" );

    if( ! got_ik ) return -1;

    moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state,
                                                                                joint_model_group);
    c->req.goal_constraints.clear();
    c->req.goal_constraints.push_back(joint_goal);

    {
        double *x = goal_state.getVariablePositions();
        for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
            fprintf(stderr, "goal %lu: %f\n", i, x[i] );
        }
    }

}

int
container_plan( struct container * c )
{

    /**********/
    /*  PLAN  */
    /**********/
    moveit_msgs::MoveItErrorCodes err;
    planning_interface::MotionPlanResponse res;
    planning_interface::PlanningContextPtr context =
        c->planner_instance->getPlanningContext(c->planning_scene, c->req, err);
    context->solve(res);
    if(res.error_code_.val != res.error_code_.SUCCESS)
    {
        //TODO: Why is this 0 instead of SUCCESS?
        fprintf(stderr, "Planning failed: %d\n", res.error_code_.val );
        //return 0;
    }

    /************/
    /*  Result  */
    /************/
    moveit_msgs::MotionPlanResponse res_msg;
    res.getMessage(res_msg);
    for( auto itr = res_msg.trajectory.joint_trajectory.points.begin();
         itr != res_msg.trajectory.joint_trajectory.points.end();
         itr++ )
    {
         printf("foo: ");
         for( auto j = itr->positions.begin();
              j != itr->positions.end();
              j++ )
         {
             printf("%f\t", *j );
         }
         printf("\n");
    }

    // /***************/
    // /*  Visualize  */
    // /***************/
    // ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
    // moveit_msgs::DisplayTrajectory display_trajectory;

    // ROS_INFO("Visualizing plan 1 (again)");
    // display_trajectory.trajectory_start = res_msg.trajectory_start;
    // display_trajectory.trajectory.push_back(res_msg.trajectory);
    // display_publisher.publish(display_trajectory);
    // /* Sleep to give Rviz time to visualize the plan. */
    // sleep(5.0);
}

// int
// container_group_fk( struct container * c, const char *group, double q[4], double v[3]  )
// {
//     const robot_state::JointModelGroup* joint_model_group =
//         start_state.getJointModelGroup(group);
// }
<commit_msg>Add robot_state_zero()<commit_after>#include <cstdlib>

#include <tf_conversions/tf_eigen.h>
#include <moveit/kinematic_constraints/utils.h>

#include "c_container.h"
#include "moveit_container.hpp"

static void
robot_state_zero( robot_state::RobotState *state )
{
    double *x = state->getVariablePositions();
    size_t n = state->getVariableNames().size();
    memset(x, 0, n * sizeof(x[0]) );
}

struct container *
container_create( const char *name_space, const char *robot_description )
{
    return new container(name_space, robot_description);
}

void
container_destroy( struct container * c)
{
    delete c;
}

int
container_set_start( struct container * c, const char *group, size_t n, const double *q )
{

    c->req.group_name = "right_arm";
    robot_state::RobotState start_state(c->robot_model);
    /* Zero positions because somebody's not inititializing their shit */
    robot_state_zero( &start_state);

    sensor_msgs::JointState start_joint_state;

    const robot_state::JointModelGroup* joint_model_group = start_state.getJointModelGroup(c->req.group_name);
    {
        std::vector<double> joint_values(n, 0.0);
        std::copy ( q, q+n, joint_values.begin() );
        start_state.setJointGroupPositions(joint_model_group, joint_values);
    }
    c->req.start_state.joint_state.name =  start_state.getVariableNames();
    {
        size_t n = c->req.start_state.joint_state.name.size();
        double *p = start_state.getVariablePositions();
        c->req.start_state.joint_state.position.resize( n );
        std::copy ( p, p+n,
                    c->req.start_state.joint_state.position.begin() );
    }

    // Print stuff
    {
        const std::vector<std::string> &link_names = joint_model_group->getLinkModelNames();
        std::string end_link =  link_names[ link_names.size()-1];
        fprintf(stderr, "Link: %s\n", end_link.c_str() );
        const Eigen::Affine3d estart_tf = start_state.getFrameTransform(end_link);

        tf::Transform start_pose;
        tf::poseEigenToTF(estart_tf, start_pose);
        tf::Quaternion start_q = start_pose.getRotation();
        tf::Vector3 start_v = start_pose.getOrigin();
        fprintf(stderr, "p_start[%lu] = {", n );
        for( size_t i = 0; i < n; i ++ ) {
            fprintf(stderr, "%f%s", q[i], (i+1==n) ? "};\n" : ", " );
        }
        fprintf(stderr,
                "r_start[4] = {%f, %f, %f, %f}\n"
                "v_start[3] = {%f, %f, %f}\n",
                start_q.x(),
                start_q.y(),
                start_q.z(),
                start_q.w(),
                start_v.x(),
                start_v.y(),
                start_v.z() );

    }

    //return c->set_start(group,n,q);
}

int
container_set_ws_goal( struct container * c, const char *name, const double quat[4], const double vec[3] )
{
    geometry_msgs::PoseStamped stamped_pose;
    stamped_pose.header.frame_id = "base";
    geometry_msgs::Pose &pose = stamped_pose.pose;

    pose.orientation.x = quat[0];
    pose.orientation.y = quat[1];
    pose.orientation.z = quat[2];
    pose.orientation.w = quat[3];
    pose.position.x = vec[0];
    pose.position.y = vec[1];
    pose.position.z = vec[2];

    robot_state::RobotState goal_state(c->robot_model);
    /* Zero positions because somebody's not inititializing their shit */
    robot_state_zero( &goal_state);

    const robot_state::JointModelGroup* joint_model_group = goal_state.getJointModelGroup("right_arm");
    bool got_ik = goal_state.setFromIK(joint_model_group,pose);
    fprintf(stderr, "IK: %s\n", got_ik ? "yes" : "no" );

    if( ! got_ik ) return -1;

    moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state,
                                                                                joint_model_group);
    c->req.goal_constraints.clear();
    c->req.goal_constraints.push_back(joint_goal);

    {
        double *x = goal_state.getVariablePositions();
        for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
            fprintf(stderr, "goal %lu: %f\n", i, x[i] );
        }
    }
}

int
container_plan( struct container * c )
{

    /**********/
    /*  PLAN  */
    /**********/
    moveit_msgs::MoveItErrorCodes err;
    planning_interface::MotionPlanResponse res;
    planning_interface::PlanningContextPtr context =
        c->planner_instance->getPlanningContext(c->planning_scene, c->req, err);
    context->solve(res);
    if(res.error_code_.val != res.error_code_.SUCCESS)
    {
        //TODO: Why is this 0 instead of SUCCESS?
        fprintf(stderr, "Planning failed: %d\n", res.error_code_.val );
        //return 0;
    }

    /************/
    /*  Result  */
    /************/
    moveit_msgs::MotionPlanResponse res_msg;
    res.getMessage(res_msg);
    for( auto itr = res_msg.trajectory.joint_trajectory.points.begin();
         itr != res_msg.trajectory.joint_trajectory.points.end();
         itr++ )
    {
         printf("foo: ");
         for( auto j = itr->positions.begin();
              j != itr->positions.end();
              j++ )
         {
             printf("%f\t", *j );
         }
         printf("\n");
    }

    // /***************/
    // /*  Visualize  */
    // /***************/
    // ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
    // moveit_msgs::DisplayTrajectory display_trajectory;

    // ROS_INFO("Visualizing plan 1 (again)");
    // display_trajectory.trajectory_start = res_msg.trajectory_start;
    // display_trajectory.trajectory.push_back(res_msg.trajectory);
    // display_publisher.publish(display_trajectory);
    // /* Sleep to give Rviz time to visualize the plan. */
    // sleep(5.0);
}

// int
// container_group_fk( struct container * c, const char *group, size_t n, const double *q,
//                     double r[4], double v[3]  )
// {
//     robot_state::RobotState start_state(c->robot_model);
//     /* Zero positions because somebody's not inititializing their shit */
//     {
//         double *x = start_state.getVariablePositions();
//         for( size_t i = 0; i < start_state.getVariableNames().size(); i++ ) {
//             x[i] = 0;
//         }
//     }

//     sensor_msgs::JointState start_joint_state;

//     const robot_state::JointModelGroup* joint_model_group = start_state.getJointModelGroup(c->req.group_name);

//     const robot_state::JointModelGroup* joint_model_group =
//         start_state.getJointModelGroup(group);

//         const std::vector<std::string> &link_names = joint_model_group->getLinkModelNames();
//         std::string end_link =  link_names[ link_names.size()-1];
//         fprintf(stderr, "Link: %s\n", end_link.c_str() );
//         const Eigen::Affine3d estart_tf = start_state.getFrameTransform(end_link);

//         tf::Transform start_pose;
//         tf::poseEigenToTF(estart_tf, start_pose);
//         tf::Quaternion start_q = start_pose.getRotation();
//         tf::Vector3 start_v = start_pose.getOrigin();
//         fprintf(stderr, "p_start[%lu] = {", n );
//         for( size_t i = 0; i < n; i ++ ) {
//             fprintf(stderr, "%f%s", q[i], (i+1==n) ? "};\n" : ", " );
//         }
//         fprintf(stderr,
//                 "r_start[4] = {%f, %f, %f, %f}\n"
//                 "v_start[3] = {%f, %f, %f}\n",
//                 start_q.x(),
//                 start_q.y(),
//                 start_q.z(),
//                 start_q.w(),
//                 start_v.x(),
//                 start_v.y(),
//                 start_v.z() );

//     }

// }
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/examples/examples_main.h"

#include "app/app_paths.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "views/controls/button/text_button.h"
#include "views/controls/label.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/examples/button_example.h"
#include "views/examples/combobox_example.h"
#include "views/examples/link_example.h"
#include "views/examples/menu_example.h"
#include "views/examples/message_box_example.h"
#include "views/examples/native_theme_button_example.h"
#include "views/examples/native_theme_checkbox_example.h"
#include "views/examples/radio_button_example.h"
#include "views/examples/scroll_view_example.h"
#include "views/examples/single_split_view_example.h"
#include "views/examples/tabbed_pane_example.h"
#include "views/examples/table2_example.h"
#include "views/examples/textfield_example.h"
#include "views/examples/throbber_example.h"
#include "views/examples/widget_example.h"
#include "views/focus/accelerator_handler.h"
#include "views/layout/grid_layout.h"
#include "views/views_delegate.h"
#include "views/widget/root_view.h"
#include "views/window/window.h"
#include "views/test/test_views_delegate.h"

#if defined(OS_WIN)
// TableView is not yet ported to Linux.
#include "views/examples/table_example.h"
#endif

namespace examples {

ExamplesMain::ExamplesMain() : contents_(NULL), status_label_(NULL) {}

ExamplesMain::~ExamplesMain() {}

bool ExamplesMain::CanResize() const {
  return true;
}

views::View* ExamplesMain::GetContentsView() {
  return contents_;
}

void ExamplesMain::WindowClosing() {
  MessageLoopForUI::current()->Quit();
}

void ExamplesMain::SetStatus(const std::wstring& status) {
  status_label_->SetText(status);
}

void ExamplesMain::Run() {
  base::EnableTerminationOnHeapCorruption();

  // The exit manager is in charge of calling the dtors of singleton objects.
  base::AtExitManager exit_manager;

  app::RegisterPathProvider();
  ui::RegisterPathProvider();

  icu_util::Initialize();

  ResourceBundle::InitSharedInstance("en-US");

  MessageLoop main_message_loop(MessageLoop::TYPE_UI);

  // Creates a window with the tabbed pane for each examples, and
  // a label to print messages from each examples.
  DCHECK(contents_ == NULL) << "Run called more than once.";
  contents_ = new views::View();
  contents_->set_background(views::Background::CreateStandardPanelBackground());
  views::GridLayout* layout = new views::GridLayout(contents_);
  contents_->SetLayoutManager(layout);

  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                        views::GridLayout::USE_PREF, 0, 0);

  views::TabbedPane* tabbed_pane = new views::TabbedPane();
  status_label_ = new views::Label();

  layout->StartRow(1, 0);
  layout->AddView(tabbed_pane);
  layout->StartRow(0 /* no expand */, 0);
  layout->AddView(status_label_);

  // TODO(satorux): The window is getting wide.  Eventually, we would have
  // the second tabbed pane.
  views::Window* window =
      views::Window::CreateChromeWindow(NULL, gfx::Rect(0, 0, 850, 300), this);

  examples::NativeThemeCheckboxExample native_theme_checkbox_example(this);
  tabbed_pane->AddTab(native_theme_checkbox_example.GetExampleTitle(),
                      native_theme_checkbox_example.GetExampleView());

  examples::NativeThemeButtonExample native_theme_button_example(this);
  tabbed_pane->AddTab(native_theme_button_example.GetExampleTitle(),
                      native_theme_button_example.GetExampleView());

  examples::TextfieldExample textfield_example(this);
  tabbed_pane->AddTab(textfield_example.GetExampleTitle(),
                      textfield_example.GetExampleView());

  examples::ButtonExample button_example(this);
  tabbed_pane->AddTab(button_example.GetExampleTitle(),
                      button_example.GetExampleView());

  examples::ThrobberExample throbber_example(this);
  tabbed_pane->AddTab(throbber_example.GetExampleTitle(),
                      throbber_example.GetExampleView());

  examples::ComboboxExample combobox_example(this);
  tabbed_pane->AddTab(combobox_example.GetExampleTitle(),
                      combobox_example.GetExampleView());

  examples::LinkExample link_example(this);
  tabbed_pane->AddTab(link_example.GetExampleTitle(),
                      link_example.GetExampleView());

  examples::TabbedPaneExample tabbed_pane_example(this);
  tabbed_pane->AddTab(tabbed_pane_example.GetExampleTitle(),
                      tabbed_pane_example.GetExampleView());

  examples::MessageBoxExample message_box_example(this);
  tabbed_pane->AddTab(message_box_example.GetExampleTitle(),
                      message_box_example.GetExampleView());

  examples::RadioButtonExample radio_button_example(this);
  tabbed_pane->AddTab(radio_button_example.GetExampleTitle(),
                      radio_button_example.GetExampleView());

  examples::ScrollViewExample scroll_view_example(this);
  tabbed_pane->AddTab(scroll_view_example.GetExampleTitle(),
                      scroll_view_example.GetExampleView());

  examples::SingleSplitViewExample single_split_view_example(this);
  tabbed_pane->AddTab(single_split_view_example.GetExampleTitle(),
                      single_split_view_example.GetExampleView());

#if defined(OS_WIN)
  examples::TableExample table_example(this);
  tabbed_pane->AddTab(table_example.GetExampleTitle(),
                      table_example.GetExampleView());
#endif

  examples::Table2Example table2_example(this);
  tabbed_pane->AddTab(table2_example.GetExampleTitle(),
                      table2_example.GetExampleView());

  examples::WidgetExample widget_example(this);
  tabbed_pane->AddTab(widget_example.GetExampleTitle(),
                      widget_example.GetExampleView());

  examples::MenuExample menu_example(this);
  tabbed_pane->AddTab(menu_example.GetExampleTitle(),
                      menu_example.GetExampleView());

  window->Show();
  views::AcceleratorHandler accelerator_handler;
  MessageLoopForUI::current()->Run(&accelerator_handler);
}

}  // examples namespace

int main(int argc, char** argv) {
#if defined(OS_WIN)
  OleInitialize(NULL);
#elif defined(OS_LINUX)
  // Initializes gtk stuff.
  g_thread_init(NULL);
  g_type_init();
  gtk_init(&argc, &argv);
#endif
  TestViewsDelegate delegate;

  // The delegate needs to be set before any UI is created so that windows
  // display the correct icon.
  CommandLine::Init(argc, argv);

  // We do not this header: chrome/common/chrome_switches.h
  // because that would create a dependency back on Chrome
  views::RootView::SetPureViews(
        CommandLine::ForCurrentProcess()->HasSwitch("use-pure-views"));

  examples::ExamplesMain main;
  main.Run();

#if defined(OS_WIN)
  OleUninitialize();
#endif
  return 0;
}
<commit_msg>Reverting the unintentional change.  I accidentally included the change that I didn't intend, sorry about that.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/examples/examples_main.h"

#include "app/app_paths.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/process_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "views/controls/button/text_button.h"
#include "views/controls/label.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/examples/button_example.h"
#include "views/examples/combobox_example.h"
#include "views/examples/link_example.h"
#include "views/examples/menu_example.h"
#include "views/examples/message_box_example.h"
#include "views/examples/native_theme_button_example.h"
#include "views/examples/native_theme_checkbox_example.h"
#include "views/examples/radio_button_example.h"
#include "views/examples/scroll_view_example.h"
#include "views/examples/single_split_view_example.h"
#include "views/examples/tabbed_pane_example.h"
#include "views/examples/table2_example.h"
#include "views/examples/textfield_example.h"
#include "views/examples/throbber_example.h"
#include "views/examples/widget_example.h"
#include "views/focus/accelerator_handler.h"
#include "views/layout/grid_layout.h"
#include "views/widget/root_view.h"
#include "views/window/window.h"
#include "views/test/test_views_delegate.h"

#if defined(OS_WIN)
// TableView is not yet ported to Linux.
#include "views/examples/table_example.h"
#endif

namespace examples {

ExamplesMain::ExamplesMain() : contents_(NULL), status_label_(NULL) {}

ExamplesMain::~ExamplesMain() {}

bool ExamplesMain::CanResize() const {
  return true;
}

views::View* ExamplesMain::GetContentsView() {
  return contents_;
}

void ExamplesMain::WindowClosing() {
  MessageLoopForUI::current()->Quit();
}

void ExamplesMain::SetStatus(const std::wstring& status) {
  status_label_->SetText(status);
}

void ExamplesMain::Run() {
  base::EnableTerminationOnHeapCorruption();

  // The exit manager is in charge of calling the dtors of singleton objects.
  base::AtExitManager exit_manager;

  app::RegisterPathProvider();
  ui::RegisterPathProvider();

  icu_util::Initialize();

  ResourceBundle::InitSharedInstance("en-US");

  MessageLoop main_message_loop(MessageLoop::TYPE_UI);

  // Creates a window with the tabbed pane for each examples, and
  // a label to print messages from each examples.
  DCHECK(contents_ == NULL) << "Run called more than once.";
  contents_ = new views::View();
  contents_->set_background(views::Background::CreateStandardPanelBackground());
  views::GridLayout* layout = new views::GridLayout(contents_);
  contents_->SetLayoutManager(layout);

  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                        views::GridLayout::USE_PREF, 0, 0);

  views::TabbedPane* tabbed_pane = new views::TabbedPane();
  status_label_ = new views::Label();

  layout->StartRow(1, 0);
  layout->AddView(tabbed_pane);
  layout->StartRow(0 /* no expand */, 0);
  layout->AddView(status_label_);

  // TODO(satorux): The window is getting wide.  Eventually, we would have
  // the second tabbed pane.
  views::Window* window =
      views::Window::CreateChromeWindow(NULL, gfx::Rect(0, 0, 850, 300), this);

  examples::NativeThemeCheckboxExample native_theme_checkbox_example(this);
  tabbed_pane->AddTab(native_theme_checkbox_example.GetExampleTitle(),
                      native_theme_checkbox_example.GetExampleView());

  examples::NativeThemeButtonExample native_theme_button_example(this);
  tabbed_pane->AddTab(native_theme_button_example.GetExampleTitle(),
                      native_theme_button_example.GetExampleView());

  examples::TextfieldExample textfield_example(this);
  tabbed_pane->AddTab(textfield_example.GetExampleTitle(),
                      textfield_example.GetExampleView());

  examples::ButtonExample button_example(this);
  tabbed_pane->AddTab(button_example.GetExampleTitle(),
                      button_example.GetExampleView());

  examples::ThrobberExample throbber_example(this);
  tabbed_pane->AddTab(throbber_example.GetExampleTitle(),
                      throbber_example.GetExampleView());

  examples::ComboboxExample combobox_example(this);
  tabbed_pane->AddTab(combobox_example.GetExampleTitle(),
                      combobox_example.GetExampleView());

  examples::LinkExample link_example(this);
  tabbed_pane->AddTab(link_example.GetExampleTitle(),
                      link_example.GetExampleView());

  examples::TabbedPaneExample tabbed_pane_example(this);
  tabbed_pane->AddTab(tabbed_pane_example.GetExampleTitle(),
                      tabbed_pane_example.GetExampleView());

  examples::MessageBoxExample message_box_example(this);
  tabbed_pane->AddTab(message_box_example.GetExampleTitle(),
                      message_box_example.GetExampleView());

  examples::RadioButtonExample radio_button_example(this);
  tabbed_pane->AddTab(radio_button_example.GetExampleTitle(),
                      radio_button_example.GetExampleView());

  examples::ScrollViewExample scroll_view_example(this);
  tabbed_pane->AddTab(scroll_view_example.GetExampleTitle(),
                      scroll_view_example.GetExampleView());

  examples::SingleSplitViewExample single_split_view_example(this);
  tabbed_pane->AddTab(single_split_view_example.GetExampleTitle(),
                      single_split_view_example.GetExampleView());

#if defined(OS_WIN)
  examples::TableExample table_example(this);
  tabbed_pane->AddTab(table_example.GetExampleTitle(),
                      table_example.GetExampleView());
#endif

  examples::Table2Example table2_example(this);
  tabbed_pane->AddTab(table2_example.GetExampleTitle(),
                      table2_example.GetExampleView());

  examples::WidgetExample widget_example(this);
  tabbed_pane->AddTab(widget_example.GetExampleTitle(),
                      widget_example.GetExampleView());

  examples::MenuExample menu_example(this);
  tabbed_pane->AddTab(menu_example.GetExampleTitle(),
                      menu_example.GetExampleView());

  window->Show();
  views::AcceleratorHandler accelerator_handler;
  MessageLoopForUI::current()->Run(&accelerator_handler);
}

}  // examples namespace

int main(int argc, char** argv) {
#if defined(OS_WIN)
  OleInitialize(NULL);
#elif defined(OS_LINUX)
  // Initializes gtk stuff.
  g_thread_init(NULL);
  g_type_init();
  gtk_init(&argc, &argv);
#endif
  TestViewsDelegate delegate;

  CommandLine::Init(argc, argv);

  // We do not this header: chrome/common/chrome_switches.h
  // because that would create a dependency back on Chrome
  views::RootView::SetPureViews(
        CommandLine::ForCurrentProcess()->HasSwitch("use-pure-views"));

  examples::ExamplesMain main;
  main.Run();

#if defined(OS_WIN)
  OleUninitialize();
#endif
  return 0;
}
<|endoftext|>


<commit_before>#include <memory>
#include <cstdio>
#include <cstdint>
#include <string>
#include "../c/memory.h"

static void aligned_free_wrapper(void * ptr)
{
	printf("Calling aligned_free on ptr: %p\n", ptr);
	aligned_free(ptr);
}

/**
* Here we create aliases for our aligned pointer types.
* We are specifying that our alias has a fixed value: the deleter function type
* We use this for unique_ptr as it requires the type of the deleter in the declaration
*/
template<class T> using unique_ptr_aligned = std::unique_ptr<T, decltype(&aligned_free)>;

int main(void)
{
	/**
	* Using our unique_ptr_aligned type, we declare an aligned uint8_t unique ptr.
	* I use my wrapper function as the deleter to print values as things are getting freed
	* Note that rather than calling new(uint8_t), we call aligned_malloc to get our aligned memory
	*/
	unique_ptr_aligned<uint8_t[]> x(static_cast<uint8_t*>(aligned_malloc(8, 1024)), &aligned_free_wrapper);
	unique_ptr_aligned<uint8_t[]> y(static_cast<uint8_t*>(aligned_malloc(32, 1024)), &aligned_free_wrapper);

	/**
	* Why don't we need a shared pointer to also have an alias?
	* The deleter is not part of the type, simply the constructor
	*/
	std::shared_ptr<uint8_t> z(static_cast<uint8_t*>(aligned_malloc(32, 128)), &aligned_free_wrapper);

	printf("x (unique) has alignment 8: %p\n", x.get());
	printf("y (unique) has alignment 32: %p\n", y.get());
	printf("z (shared) has alignment 32: %p\n", z.get());

	/**
	* This will cause the deleter to be called (aligned_free)
	*/
	printf("Freeing y pointer by reset()\n");
	y.reset();

	/*
	* Since these pointers are allocated on the stack, they are bound by RAII
	* Once we leave main() the pointers will go out of scope and the deleter we specified
	* will be called automatically.
	*/
	printf("Leaving main. X and Z will be automatically destructed\n");

	return 0;
}
<commit_msg>Add a new templated allocation function for the unique_ptr aligned malloc example.<commit_after>#include <memory>
#include <cstdio>
#include <cstdint>
#include <string>
#include "../c/memory.h"

static void aligned_free_wrapper(void * ptr)
{
	printf("Calling aligned_free on ptr: %p\n", ptr);
	aligned_free(ptr);
}

/**
* Here we create aliases for our aligned pointer types.
* We are specifying that our alias has a fixed value: the deleter function type
* We use this for unique_ptr as it requires the type of the deleter in the declaration
*/
template<class T> using unique_ptr_aligned = std::unique_ptr<T, decltype(&aligned_free)>;

template<class T>
unique_ptr_aligned<T> aligned_ptr(size_t align, size_t size)
{
	return unique_ptr_aligned<T>(static_cast<T*>(aligned_malloc(align, size)), &aligned_free_wrapper);
}

int main(void)
{
	/**
	* Using our unique_ptr_aligned type, we declare an aligned uint8_t unique ptr.
	* I use my wrapper function as the deleter to print values as things are getting freed
	* Note that rather than calling new(uint8_t), we call aligned_malloc to get our aligned memory
	*/
	unique_ptr_aligned<uint8_t[]> x(static_cast<uint8_t*>(aligned_malloc(8, 1024)), &aligned_free_wrapper);
	auto y = aligned_ptr<uint8_t>(32, 100);

	/**
	* Why don't we need a shared pointer to also have an alias?
	* The deleter is not part of the type, simply the constructor
	*/
	std::shared_ptr<uint8_t> z(static_cast<uint8_t*>(aligned_malloc(32, 128)), &aligned_free_wrapper);

	printf("x (unique) has alignment 8: %p\n", x.get());
	printf("y (unique) has alignment 32: %p\n", y.get());
	printf("z (shared) has alignment 32: %p\n", z.get());

	/**
	* This will cause the deleter to be called (aligned_free)
	*/
	printf("Freeing y pointer by reset()\n");
	y.reset();

	/*
	* Since these pointers are allocated on the stack, they are bound by RAII
	* Once we leave main() the pointers will go out of scope and the deleter we specified
	* will be called automatically.
	*/
	printf("Leaving main. X and Z will be automatically destructed\n");

	return 0;
}
<|endoftext|>


<commit_before>#include <memory>
#include <cstdio>
#include <cstdint>
#include <string>
#include "../c/memory.h"

static void aligned_free_wrapper(void * ptr)
{
	printf("Calling aligned_free on ptr: %p\n", ptr);
	aligned_free(ptr);
}

/**
* Here we create aliases for our aligned pointer types.
* We are specifying that our alias has a fixed value: the deleter function type
* We use this for unique_ptr as it requires the type of the deleter in the declaration
*/
template<class T> using unique_ptr_aligned = std::unique_ptr<T, decltype(&aligned_free)>;

template<class T>
unique_ptr_aligned<T> aligned_uptr(size_t align, size_t size)
{
	return unique_ptr_aligned<T>(static_cast<T*>(aligned_malloc(align, size)), &aligned_free_wrapper);
}

template<class T>
std::shared_ptr<T> aligned_sptr(size_t align, size_t size)
{
	return std::shared_ptr<T>(static_cast<T*>(aligned_malloc(align, size)), &aligned_free_wrapper);
}

int main(void)
{
	/**
	* Using our unique_ptr_aligned type, we declare an aligned uint8_t unique ptr.
	* I use my wrapper function as the deleter to print values as things are getting freed
	* Note that rather than calling new(uint8_t), we call aligned_malloc to get our aligned memory
	*/
	unique_ptr_aligned<uint8_t[]> x(static_cast<uint8_t*>(aligned_malloc(8, 1024)), &aligned_free_wrapper);
	auto y = aligned_uptr<uint8_t>(32, 100);

	/**
	* Why don't we need a shared pointer to also have an alias?
	* The deleter is not part of the type, simply the constructor
	*/
	std::shared_ptr<uint8_t> z(static_cast<uint8_t*>(aligned_malloc(32, 128)), &aligned_free_wrapper);
	auto a = aligned_sptr<uint8_t>(64, 100);

	printf("x (unique) has alignment 8: %p\n", x.get());
	printf("y (unique) has alignment 32: %p\n", y.get());
	printf("z (shared) has alignment 32: %p\n", z.get());
	printf("a (shared) has alignment 64: %p\n", a.get());

	/**
	* This will cause the deleter to be called (aligned_free)
	*/
	printf("Freeing y pointer by reset()\n");
	y.reset();

	/*
	* Since these pointers are allocated on the stack, they are bound by RAII
	* Once we leave main() the pointers will go out of scope and the deleter we specified
	* will be called automatically.
	*/
	printf("Leaving main. Remaining pointers will be automatically destructed\n");

	return 0;
}
<commit_msg>Comment new code in aligned pointer example<commit_after>#include <memory>
#include <cstdio>
#include <cstdint>
#include <string>
#include "../c/memory.h"

static void aligned_free_wrapper(void * ptr)
{
	printf("Calling aligned_free on ptr: %p\n", ptr);
	aligned_free(ptr);
}

/**
* Here we create aliases for our aligned pointer types.
* We are specifying that our alias has a fixed value: the deleter function type
* We use this for unique_ptr as it requires the type of the deleter in the declaration
*/
template<class T> using unique_ptr_aligned = std::unique_ptr<T, decltype(&aligned_free)>;

/**
* We can create a template function that simplifies our declarations of aligned
* unique pointers. Alignment and size are passed through to aligned malloc, and
* aligned free is always used as the deleter.  We then generate the correct pointer
* type based on the templated call
*/
template<class T>
unique_ptr_aligned<T> aligned_uptr(size_t align, size_t size)
{
	return unique_ptr_aligned<T>(static_cast<T*>(aligned_malloc(align, size)), &aligned_free_wrapper);
}

/**
* We can create a template function that simplifies our declarations of aligned
* shared pointers. Alignment and size are passed through to aligned malloc, and
* aligned free is always used as the deleter.  We then generate the correct pointer
* type based on the templated call
*
* Notice here that the shared pointer doesn't need a special type due to the deleter
* The deleter type is only required for the unique pointer.
*/
template<class T>
std::shared_ptr<T> aligned_sptr(size_t align, size_t size)
{
	return std::shared_ptr<T>(static_cast<T*>(aligned_malloc(align, size)), &aligned_free_wrapper);
}

int main(void)
{
	/**
	* Using our unique_ptr_aligned type, we declare an aligned uint8_t unique ptr.
	* I use my wrapper function as the deleter to print values as things are getting freed
	* Note that rather than calling new(uint8_t), we call aligned_malloc to get our aligned memory
	*/
	unique_ptr_aligned<uint8_t[]> x(static_cast<uint8_t*>(aligned_malloc(8, 1024)), &aligned_free_wrapper);

	/*
	* Instead of the lengthy declaration above, we can use our templated
	* aligned_uptr function for a much simpler declaration
	*/
	auto y = aligned_uptr<uint8_t>(32, 100);

	/**
	* Why don't we need a shared pointer to also have an alias?
	* The deleter is not part of the type, simply the constructor
	*/
	std::shared_ptr<uint8_t> z(static_cast<uint8_t*>(aligned_malloc(32, 128)), &aligned_free_wrapper);

	/*
	* Instead of the lengthy declaration above, we can use our templated
	* aligned_sptr function for a much simpler declaration
	*/
	auto a = aligned_sptr<uint8_t>(64, 100);

	printf("x (unique) has alignment 8: %p\n", x.get());
	printf("y (unique) has alignment 32: %p\n", y.get());
	printf("z (shared) has alignment 32: %p\n", z.get());
	printf("a (shared) has alignment 64: %p\n", a.get());

	/**
	* This will cause the deleter to be called (aligned_free)
	*/
	printf("Freeing y pointer by reset()\n");
	y.reset();

	/*
	* Since these pointers are allocated on the stack, they are bound by RAII
	* Once we leave main() the pointers will go out of scope and the deleter we specified
	* will be called automatically.
	*/
	printf("Leaving main. Remaining pointers will be automatically destructed\n");

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmpage.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-25 15:12:51 $
 *
 *  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 _SVX_FMPAGE_HXX
#define _SVX_FMPAGE_HXX

#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class StarBASIC;
class FmFormModel;
class FmFormPageImpl;   // haelt die Liste aller Forms

FORWARD_DECLARE_INTERFACE(container,XNameContainer)

class SdrView;
class SfxJSArray;
class HelpEvent;

class SVX_DLLPUBLIC FmFormPage : public SdrPage
{
    friend class FmFormObj;
    FmFormPageImpl*     m_pImpl;
    String              m_sPageName;
    StarBASIC*          m_pBasic;

public:
    TYPEINFO();

    FmFormPage(FmFormModel& rModel,StarBASIC*, FASTBOOL bMasterPage=sal_False);
    FmFormPage(const FmFormPage& rPage);
    ~FmFormPage();

    using SdrPage::NbcInsertObject;
    using SdrPage::NbcRemoveObject;
    using SdrPage::NbcReplaceObject;
    using SdrPage::ReplaceObject;

    virtual void    SetModel(SdrModel* pNewModel);

    virtual SdrPage* Clone() const;

    virtual void    InsertObject(SdrObject* pObj, ULONG nPos = CONTAINER_APPEND,
                                    const SdrInsertReason* pReason=NULL);

    virtual SdrObject* RemoveObject(ULONG nObjNum);

    // Zugriff auf alle Formulare
    const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer>& GetForms( bool _bForceCreate = true ) const;

    FmFormPageImpl*  GetImpl() const {return m_pImpl;}

public:
    const String&       GetName() const { return m_sPageName; }
    void                SetName( const String& rName ) { m_sPageName = rName; }
    StarBASIC*          GetBasic() const { return m_pBasic; }
    sal_Bool            RequestHelp(
                            Window* pWin,
                            SdrView* pView,
                            const HelpEvent& rEvt );
};

#endif          // _SVX_FMPAGE_HXX

<commit_msg>#i10000# 'using SdrPage::Clone' to avoid warning 'FmFormPage::Clone hides the virtual function SdrPage::Clone(SdrModel*) const'<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmpage.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-27 10:11:25 $
 *
 *  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 _SVX_FMPAGE_HXX
#define _SVX_FMPAGE_HXX

#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class StarBASIC;
class FmFormModel;
class FmFormPageImpl;   // haelt die Liste aller Forms

FORWARD_DECLARE_INTERFACE(container,XNameContainer)

class SdrView;
class SfxJSArray;
class HelpEvent;

class SVX_DLLPUBLIC FmFormPage : public SdrPage
{
    friend class FmFormObj;
    FmFormPageImpl*     m_pImpl;
    String              m_sPageName;
    StarBASIC*          m_pBasic;

public:
    TYPEINFO();

    FmFormPage(FmFormModel& rModel,StarBASIC*, FASTBOOL bMasterPage=sal_False);
    FmFormPage(const FmFormPage& rPage);
    ~FmFormPage();

    using SdrPage::NbcInsertObject;
    using SdrPage::NbcRemoveObject;
    using SdrPage::NbcReplaceObject;
    using SdrPage::ReplaceObject;

    virtual void    SetModel(SdrModel* pNewModel);

    virtual SdrPage* Clone() const;
    using SdrPage::Clone;

    virtual void    InsertObject(SdrObject* pObj, ULONG nPos = CONTAINER_APPEND,
                                    const SdrInsertReason* pReason=NULL);

    virtual SdrObject* RemoveObject(ULONG nObjNum);

    // Zugriff auf alle Formulare
    const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer>& GetForms( bool _bForceCreate = true ) const;

    FmFormPageImpl*  GetImpl() const {return m_pImpl;}

public:
    const String&       GetName() const { return m_sPageName; }
    void                SetName( const String& rName ) { m_sPageName = rName; }
    StarBASIC*          GetBasic() const { return m_pBasic; }
    sal_Bool            RequestHelp(
                            Window* pWin,
                            SdrView* pView,
                            const HelpEvent& rEvt );
};

#endif          // _SVX_FMPAGE_HXX

<|endoftext|>


<commit_before>#include <iostream>

#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
#include "restc-cpp/IteratorFromJsonSerializer.h"

using namespace std;
using namespace restc_cpp;

// C++ structure that match the Json entries received
// from http://jsonplaceholder.typicode.com/posts/{id}
struct Post {
    int userId = 0;
    int id = 0;
    string title;
    string body;
};

// Add C++ reflection to the Post structure.
// This allows our Json (de)serialization to do it's magic.
BOOST_FUSION_ADAPT_STRUCT(
    Post,
    (int, userId)
    (int, id)
    (string, title)
    (string, body)
)

// The C++ main function - the place where any adventure starts
void first() {

    // Create and instantiate a Post from data received from the server.
    Post my_post = RestClient::Create()->ProcessWithPromiseT<Post>([&](Context& ctx) {
        // This is a co-routine, running in a worker-thread

        // Instantiate a Post structure.
        Post post;

        // Serialize it asynchronously. The asynchronously part does not really matter
        // here, but it may if you receive huge data structures.
        SerializeFromJson(post,

            // Construct a request to the server
            RequestBuilder(ctx)
                .Get("http://jsonplaceholder.typicode.com/posts/1")

                // Add some headers for good taste
                .Header("X-Client", "RESTC_CPP")
                .Header("X-Client-Purpose", "Testing")

                // Send the request
                .Execute());

        // Return the post instance trough a C++ future<>
        return post;
    })

    // Get the Post instance from the future<>, or any C++ exception thrown
    // within the lambda.
    .get();

    // Print the result for everyone to see.
    cout << "Received post# " << my_post.id << ", title: " << my_post.title;
}

void DoSomethingInteresting(Context& ctx) {
    // Here we are again in a co-routine, running in a worker-thread.

    // Asynchronously connect to a server and fetch some data.
    auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");

    // Asynchronously fetch the entire data-set and return it as a string.
    auto json = reply->GetBodyAsString();

    // Just dump the data.
    cout << "Received data: " << json << endl;
}

void second() {
    auto rest_client = RestClient::Create();

    // Call DoSomethingInteresting as a co-routine in a worker-thread.
    rest_client->Process(DoSomethingInteresting);

    // Wait for the request to finish
    rest_client->CloseWhenReady(true);
}

void third() {

    auto rest_client = RestClient::Create();
    rest_client->ProcessWithPromise([&](Context& ctx) {
        // Here we are again in a co-routine, running in a worker-thread.

        // Asynchronously connect to a server and fetch some data.
        auto reply = RequestBuilder(ctx)
            .Get("http://localhost:3001/restricted/posts/1")

            // Authenticate as 'alice' with a very popular password
            .BasicAuthentication("alice", "12345")

            // Send the request.
            .Execute();

        // Dump the well protected data
        cout << "Got: " << reply->GetBodyAsString();

    }).get();
}

void forth() {

    // Add the proxy information to the properties used by the client
    Request::Properties properties;
    properties.proxy.type = Request::Proxy::Type::HTTP;
    properties.proxy.address = "http://127.0.0.1:3003";

    // Create the client with our configuration
    auto rest_client = RestClient::Create(properties);
    rest_client->ProcessWithPromise([&](Context& ctx) {
        // Here we are again in a co-routine, running in a worker-thread.

        // Asynchronously connect to a server trough a HTTP proxy and fetch some data.
        auto reply = RequestBuilder(ctx)
            .Get("http://api.example.com/normal/posts/1")

            // Send the request.
            .Execute();

        // Dump the data
        cout << "Got: " << reply->GetBodyAsString();

    }).get();
}

void fifth() {
    // Fetch a list of records asyncrouesly, one by one.
    // This allows us to process single items in a list
    // and fetching more data as we move forward.
    // This works basically as a database cursor, or
    // (literally) as a properly implemented C++ input iterator.

    // Create the REST clent
    auto rest_client = RestClient::Create();

    // Run our example in a lambda co-routine
    rest_client->Process([&](Context& ctx) {
        // This is the co-routine, running in a worker-thread

        // Construct a request to the server
        auto reply = RequestBuilder(ctx)
            .Get("http://jsonplaceholder.typicode.com/posts/")

            // Add some headers for good taste
            .Header("X-Client", "RESTC_CPP")
            .Header("X-Client-Purpose", "Testing")

            // Send the request
            .Execute();

        // Instatiate a serializer with begin() and end() methods that
        // allows us to work with the reply-data trough a C++
        // input iterator.
        IteratorFromJsonSerializer<Post> data{*reply};

        // Iterate over the data, fetch data asyncrounesly as we go.
        for(const auto& post : data) {
            cout << "Item #" << post.id << " Title: " << post.title << endl;
        }
    });

    // Wait for the request to finish
    rest_client->CloseWhenReady(true);
}

void Sixth() {
    Request::Properties properties;

    // Create the client without creating a worker thread
    auto rest_client = RestClient::Create(properties, true);

    // Add a request to the queue of the io-service in the rest client instance
    rest_client->Process([&](Context& ctx) {
        // Here we are again in a co-routine, now in our own thread.

        // Asynchronously connect to a server trough a HTTP proxy and fetch some data.
        auto reply = RequestBuilder(ctx)
            .Get("http://jsonplaceholder.typicode.com/posts/1")

            // Send the request.
            .Execute();

        // Dump the data
        cout << "Got: " << reply->GetBodyAsString();

        // Shut down the io-service. This will cause run() (below) to return.
        rest_client->CloseWhenReady();

    });

    // Start the io-service, using this thread.
    rest_client->GetIoService().run();

    cout << "Done. Exiting normally." << endl;
}

// Use our own RequestBody implementation to supply
// data to a POST request
void Seventh() {
    // Our own implementation of the raw data provider
    class MyBody : public RequestBody
    {
    public:
        MyBody() = default;

        Type GetType() const noexcept override {

            // This mode causes the request to use chunked data,
            // allowing us to send data without knowing the exact
            // size of the payload when we start.
            return Type::CHUNKED_LAZY_PULL;
        }

        std::uint64_t GetFixedSize() const override {
            throw runtime_error("Not implemented");
        }

        // This will be called until we return false to indicate
        // that we have no further data
        bool GetData(write_buffers_t& buffers) override {

            if (++count_ > 10) {

                // We are done.
                return false;
            }

            ostringstream data;
            data << "This is line #" << count_ << " of the payload.\r\n";

            // The buffer need to persist until we are called again, or the
            // instance is destroyed.
            data_buffer_ = data.str();

            buffers.emplace_back(data_buffer_.c_str(), data_buffer_.size());

            // We added data to buffers, so return true
            return true;
        }

        // Called if we get a HTTP redirect and need to start over again.
        void Reset() override {
            count_ = 0;
        }

    private:
        int count_ = 0;
        string data_buffer_;
    };

    // Create the REST clent
    auto rest_client = RestClient::Create();

    // Run our example in a lambda co-routine
    rest_client->Process([&](Context& ctx) {
        // This is the co-routine, running in a worker-thread

        // Construct a POST request to the server
        RequestBuilder(ctx)
            .Post("http://localhost:3001/upload_raw/")
            .Header("Content-Type", "text/text")
            .Body(make_unique<MyBody>())
            .Execute();
    });

    // Wait for the request to finish
    rest_client->CloseWhenReady(true);
}

int main() {
    try {
//         cout << "First: " << endl;
//         first();
//
//         cout << "Second: " << endl;
//         second();
//
//         cout << "Third: " << endl;
//         third();
//
//         cout << "Forth: " << endl;
//         forth();
//
//         cout << "Fifth: " << endl;
//         fifth();
//
//         cout << "Sixth: " << endl;
//         Sixth();
//
        cout << "Seventh: " << endl;
        Seventh();

    } catch(const exception& ex) {
        cerr << "Something threw up: " << ex.what() << endl;
        return 1;
    }
}
<commit_msg>Re-enabled all readme tests.<commit_after>#include <iostream>

#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
#include "restc-cpp/IteratorFromJsonSerializer.h"

using namespace std;
using namespace restc_cpp;

// C++ structure that match the Json entries received
// from http://jsonplaceholder.typicode.com/posts/{id}
struct Post {
    int userId = 0;
    int id = 0;
    string title;
    string body;
};

// Add C++ reflection to the Post structure.
// This allows our Json (de)serialization to do it's magic.
BOOST_FUSION_ADAPT_STRUCT(
    Post,
    (int, userId)
    (int, id)
    (string, title)
    (string, body)
)

// The C++ main function - the place where any adventure starts
void first() {

    // Create and instantiate a Post from data received from the server.
    Post my_post = RestClient::Create()->ProcessWithPromiseT<Post>([&](Context& ctx) {
        // This is a co-routine, running in a worker-thread

        // Instantiate a Post structure.
        Post post;

        // Serialize it asynchronously. The asynchronously part does not really matter
        // here, but it may if you receive huge data structures.
        SerializeFromJson(post,

            // Construct a request to the server
            RequestBuilder(ctx)
                .Get("http://jsonplaceholder.typicode.com/posts/1")

                // Add some headers for good taste
                .Header("X-Client", "RESTC_CPP")
                .Header("X-Client-Purpose", "Testing")

                // Send the request
                .Execute());

        // Return the post instance trough a C++ future<>
        return post;
    })

    // Get the Post instance from the future<>, or any C++ exception thrown
    // within the lambda.
    .get();

    // Print the result for everyone to see.
    cout << "Received post# " << my_post.id << ", title: " << my_post.title;
}

void DoSomethingInteresting(Context& ctx) {
    // Here we are again in a co-routine, running in a worker-thread.

    // Asynchronously connect to a server and fetch some data.
    auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");

    // Asynchronously fetch the entire data-set and return it as a string.
    auto json = reply->GetBodyAsString();

    // Just dump the data.
    cout << "Received data: " << json << endl;
}

void second() {
    auto rest_client = RestClient::Create();

    // Call DoSomethingInteresting as a co-routine in a worker-thread.
    rest_client->Process(DoSomethingInteresting);

    // Wait for the request to finish
    rest_client->CloseWhenReady(true);
}

void third() {

    auto rest_client = RestClient::Create();
    rest_client->ProcessWithPromise([&](Context& ctx) {
        // Here we are again in a co-routine, running in a worker-thread.

        // Asynchronously connect to a server and fetch some data.
        auto reply = RequestBuilder(ctx)
            .Get("http://localhost:3001/restricted/posts/1")

            // Authenticate as 'alice' with a very popular password
            .BasicAuthentication("alice", "12345")

            // Send the request.
            .Execute();

        // Dump the well protected data
        cout << "Got: " << reply->GetBodyAsString();

    }).get();
}

void forth() {

    // Add the proxy information to the properties used by the client
    Request::Properties properties;
    properties.proxy.type = Request::Proxy::Type::HTTP;
    properties.proxy.address = "http://127.0.0.1:3003";

    // Create the client with our configuration
    auto rest_client = RestClient::Create(properties);
    rest_client->ProcessWithPromise([&](Context& ctx) {
        // Here we are again in a co-routine, running in a worker-thread.

        // Asynchronously connect to a server trough a HTTP proxy and fetch some data.
        auto reply = RequestBuilder(ctx)
            .Get("http://api.example.com/normal/posts/1")

            // Send the request.
            .Execute();

        // Dump the data
        cout << "Got: " << reply->GetBodyAsString();

    }).get();
}

void fifth() {
    // Fetch a list of records asyncrouesly, one by one.
    // This allows us to process single items in a list
    // and fetching more data as we move forward.
    // This works basically as a database cursor, or
    // (literally) as a properly implemented C++ input iterator.

    // Create the REST clent
    auto rest_client = RestClient::Create();

    // Run our example in a lambda co-routine
    rest_client->Process([&](Context& ctx) {
        // This is the co-routine, running in a worker-thread

        // Construct a request to the server
        auto reply = RequestBuilder(ctx)
            .Get("http://jsonplaceholder.typicode.com/posts/")

            // Add some headers for good taste
            .Header("X-Client", "RESTC_CPP")
            .Header("X-Client-Purpose", "Testing")

            // Send the request
            .Execute();

        // Instatiate a serializer with begin() and end() methods that
        // allows us to work with the reply-data trough a C++
        // input iterator.
        IteratorFromJsonSerializer<Post> data{*reply};

        // Iterate over the data, fetch data asyncrounesly as we go.
        for(const auto& post : data) {
            cout << "Item #" << post.id << " Title: " << post.title << endl;
        }
    });

    // Wait for the request to finish
    rest_client->CloseWhenReady(true);
}

void Sixth() {
    Request::Properties properties;

    // Create the client without creating a worker thread
    auto rest_client = RestClient::Create(properties, true);

    // Add a request to the queue of the io-service in the rest client instance
    rest_client->Process([&](Context& ctx) {
        // Here we are again in a co-routine, now in our own thread.

        // Asynchronously connect to a server trough a HTTP proxy and fetch some data.
        auto reply = RequestBuilder(ctx)
            .Get("http://jsonplaceholder.typicode.com/posts/1")

            // Send the request.
            .Execute();

        // Dump the data
        cout << "Got: " << reply->GetBodyAsString();

        // Shut down the io-service. This will cause run() (below) to return.
        rest_client->CloseWhenReady();

    });

    // Start the io-service, using this thread.
    rest_client->GetIoService().run();

    cout << "Done. Exiting normally." << endl;
}

// Use our own RequestBody implementation to supply
// data to a POST request
void Seventh() {
    // Our own implementation of the raw data provider
    class MyBody : public RequestBody
    {
    public:
        MyBody() = default;

        Type GetType() const noexcept override {

            // This mode causes the request to use chunked data,
            // allowing us to send data without knowing the exact
            // size of the payload when we start.
            return Type::CHUNKED_LAZY_PULL;
        }

        std::uint64_t GetFixedSize() const override {
            throw runtime_error("Not implemented");
        }

        // This will be called until we return false to indicate
        // that we have no further data
        bool GetData(write_buffers_t& buffers) override {

            if (++count_ > 10) {

                // We are done.
                return false;
            }

            ostringstream data;
            data << "This is line #" << count_ << " of the payload.\r\n";

            // The buffer need to persist until we are called again, or the
            // instance is destroyed.
            data_buffer_ = data.str();

            buffers.emplace_back(data_buffer_.c_str(), data_buffer_.size());

            // We added data to buffers, so return true
            return true;
        }

        // Called if we get a HTTP redirect and need to start over again.
        void Reset() override {
            count_ = 0;
        }

    private:
        int count_ = 0;
        string data_buffer_;
    };

    // Create the REST clent
    auto rest_client = RestClient::Create();

    // Run our example in a lambda co-routine
    rest_client->Process([&](Context& ctx) {
        // This is the co-routine, running in a worker-thread

        // Construct a POST request to the server
        RequestBuilder(ctx)
            .Post("http://localhost:3001/upload_raw/")
            .Header("Content-Type", "text/text")
            .Body(make_unique<MyBody>())
            .Execute();
    });

    // Wait for the request to finish
    rest_client->CloseWhenReady(true);
}

int main() {
    try {
        cout << "First: " << endl;
        first();

        cout << "Second: " << endl;
        second();

        cout << "Third: " << endl;
        third();

        cout << "Forth: " << endl;
        forth();

        cout << "Fifth: " << endl;
        fifth();

        cout << "Sixth: " << endl;
        Sixth();

        cout << "Seventh: " << endl;
        Seventh();

    } catch(const exception& ex) {
        cerr << "Something threw up: " << ex.what() << endl;
        return 1;
    }
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "dll/rbm/rbm.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"

int main(int /*argc*/, char* /*argv*/ []) {
    // Load the dataset
    auto ae_dataset = dll::make_mnist_ae_dataset(dll::batch_size<50>{}, dll::binarize_pre<30>{});
    auto dataset = dll::make_mnist_dataset(dll::batch_size<50>{}, dll::binarize_pre<30>{});

    // Build the network

    using network_t = dll::network_desc<
        dll::network_layers<
            dll::rbm<28 * 28, 500, dll::batch_size<50>, dll::momentum>,
            dll::rbm<500, 250, dll::batch_size<50>, dll::momentum>,
            dll::rbm<250, 10, dll::batch_size<50>, dll::hidden<dll::unit_type::SOFTMAX>>
        >
        , dll::batch_size<50>                       // The mini-batch size
        , dll::shuffle                               // Shuffle before each epoch
    >::network_t;

    auto net = std::make_unique<network_t>();

    // Display the network and dataset
    net->display_pretty();
    dataset.display_pretty();

    // Pretrain the network with contrastive divergence
    net->pretrain(ae_dataset.train(), 10);

    // Train the network for performance sake
    net->fine_tune(dataset.train(), 50);

    // Test the network on test set
    net->evaluate(dataset.test());

    // Show where the time was spent
    dll::dump_timers_pretty();

    return 0;
}
<commit_msg>Unify examples<commit_after>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "dll/rbm/rbm.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"

int main(int /*argc*/, char* /*argv*/ []) {
    // Load the dataset
    auto ae_dataset = dll::make_mnist_ae_dataset(dll::batch_size<100>{}, dll::binarize_pre<30>{});
    auto dataset = dll::make_mnist_dataset(dll::batch_size<100>{}, dll::binarize_pre<30>{});

    // Build the network

    using network_t = dll::network_desc<
        dll::network_layers<
            dll::rbm<28 * 28, 500, dll::batch_size<100>, dll::momentum>,
            dll::rbm<500, 250, dll::batch_size<100>, dll::momentum>,
            dll::rbm<250, 10, dll::batch_size<100>, dll::hidden<dll::unit_type::SOFTMAX>>
        >
        , dll::updater<dll::updater_type::NADAM>     // Nesterov Adam (NADAM)
        , dll::batch_size<100>                       // The mini-batch size
        , dll::shuffle                               // Shuffle before each epoch
    >::network_t;

    auto net = std::make_unique<network_t>();

    // Display the network and dataset
    net->display_pretty();
    dataset.display_pretty();

    // Pretrain the network with contrastive divergence
    net->pretrain(ae_dataset.train(), 10);

    // Train the network for performance sake
    net->fine_tune(dataset.train(), 50);

    // Test the network on test set
    net->evaluate(dataset.test());

    // Show where the time was spent
    dll::dump_timers_pretty();

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>add languages/program_on_cpp/In_Depth_C++_11/chapter3-type_traits/variable_template.cpp<commit_after><|endoftext|>