<commit_before>/*
 * BPLayer.cpp
 *
 *  Created on: 02.06.2009
 *      Author: Xerces
 */

#include <cassert>
//own classes
#include <math/ANFunctions.h>
#include <basic/ANEdge.h>
#include <basic/ANAbsNeuron.h>
#include <ANBPNeuron.h>
#include <ANBPLayer.h>

#include <containers/ANConTable.h>

using namespace ANN;

BPLayer::BPLayer(int iZLayer) {
	m_pBiasNeuron = NULL;
	m_iZLayer = iZLayer;
}

BPLayer::BPLayer(const BPLayer *pLayer, int iZLayer) {
	int iNumber 			= pLayer->GetNeurons().size();
	LayerTypeFlag fType 	= pLayer->GetFlag();
	m_pBiasNeuron 			= NULL;

	m_iZLayer = iZLayer;

	Resize(iNumber);
	SetFlag(fType);
}

BPLayer::BPLayer(const unsigned int &iNumber, LayerTypeFlag fType, int iZLayer) {
	Resize(iNumber);
	m_pBiasNeuron = NULL;
	SetFlag(fType);

	m_iZLayer = iZLayer;
}

void BPLayer::SetZLayer(int iZLayer) {
	m_iZLayer = iZLayer;
}

int BPLayer::GetZLayer() {
	return m_iZLayer;
}

BPLayer::~BPLayer() {
	if(m_pBiasNeuron) {
		delete m_pBiasNeuron;
	}
}

void BPLayer::Resize(const unsigned int &iSize) {
	EraseAll();
	AddNeurons(iSize);
}

void BPLayer::AddNeurons(const unsigned int &iSize) {
	for(unsigned int i = 0; i < iSize; i++) {
		AbsNeuron *pNeuron = new BPNeuron(this);
		m_lNeurons.push_back(pNeuron);
		pNeuron->SetID(m_lNeurons.size()-1);
	}
}

void BPLayer::ConnectLayer(AbsLayer *pDestLayer, const bool &bAllowAdapt) {
	AbsNeuron *pSrcNeuron;

	/*
	 * Vernetze jedes Neuron dieser Schicht mit jedem Neuron in "destLayer"
	 */
	for(unsigned int i = 0; i < m_lNeurons.size(); i++) {
		pSrcNeuron = m_lNeurons[i];
		Connect(pSrcNeuron, pDestLayer, bAllowAdapt);
	}

	if(m_pBiasNeuron) {
		Connect(m_pBiasNeuron, pDestLayer, true);
	}
}

void BPLayer::ConnectLayer(
		AbsLayer *pDestLayer,
		std::vector<std::vector<int> > Connections,
		const bool bAllowAdapt)
{
	AbsNeuron *pSrcNeuron;

	assert( Connections.size() != m_lNeurons.size() );
	for(unsigned int i = 0; i < Connections.size(); i++) {
		std::vector<int> subArray = Connections.at(i);
		pSrcNeuron = GetNeuron(i);
		assert(i != pSrcNeuron->GetID() );

		for(unsigned int j = 0; j < subArray.size(); j++) {
			assert( j < pDestLayer->GetNeurons().size() );
			AbsNeuron *pDestNeuron = pDestLayer->GetNeuron(j);
			assert( j < pDestNeuron->GetID() );
			Connect(pSrcNeuron, pDestNeuron, bAllowAdapt);
		}
	}

	if(m_pBiasNeuron) {
		Connect(m_pBiasNeuron, pDestLayer, true);
	}
}

BPNeuron *BPLayer::GetBiasNeuron() const {
	return m_pBiasNeuron;
}

void BPLayer::SetFlag(const LayerTypeFlag &fType) {
	m_fTypeFlag = fType;
	if( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {
		m_pBiasNeuron = new BPNeuron(this);
		m_pBiasNeuron->SetValue(1.0f);
	}
}

void BPLayer::AddFlag(const LayerTypeFlag &fType) {
	if( !(m_fTypeFlag & fType) )
	m_fTypeFlag |= fType;
	if( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {
		m_pBiasNeuron = new BPNeuron(this);
		m_pBiasNeuron->SetValue(1.0f);
	}
}

void BPLayer::SetLearningRate(const float &fVal) {
	#pragma omp parallel for
	for(int j = 0; j < static_cast<int>( m_lNeurons.size() ); j++) {
		((BPNeuron*)m_lNeurons[j])->SetLearningRate(fVal);
	}
}

void BPLayer::SetMomentum(const float &fVal) {
	#pragma omp parallel for
	for(int j = 0; j < static_cast<int>( m_lNeurons.size() ); j++) {
		((BPNeuron*)m_lNeurons[j])->SetMomentum(fVal);
	}
}

void BPLayer::SetWeightDecay(const float &fVal) {
	#pragma omp parallel for
	for(int j = 0; j < static_cast<int>( m_lNeurons.size() ); j++) {
		((BPNeuron*)m_lNeurons[j])->SetWeightDecay(fVal);
	}
}

void BPLayer::ExpToFS(BZFILE* bz2out, int iBZ2Error) {
	std::cout<<"Save BPLayer to FS()"<<std::endl;
	AbsLayer::ExpToFS(bz2out, iBZ2Error);

	unsigned int iNmbOfConnects 	= 0;
	float fEdgeValue 	= 0.0f;
	int iDstLayerID 	= -1;
	int iDstNeurID 		= -1;

	bool bHasBias 		= false;
	int iZLayer 		= m_iZLayer;

	(GetBiasNeuron() == NULL) ? bHasBias = false : bHasBias = true;
	BZ2_bzWrite( &iBZ2Error, bz2out, &bHasBias, sizeof(bool) );
	BZ2_bzWrite( &iBZ2Error, bz2out, &iZLayer, sizeof(int) );

	if(bHasBias) {
		AbsNeuron *pCurNeur = GetBiasNeuron();
		iNmbOfConnects = pCurNeur->GetConsO().size();
		BZ2_bzWrite( &iBZ2Error, bz2out, &iNmbOfConnects, sizeof(int) );
		for(unsigned int k = 0; k < iNmbOfConnects; k++) {
			Edge *pCurEdge = pCurNeur->GetConO(k);
			iDstLayerID = pCurEdge->GetDestination(pCurNeur)->GetParent()->GetID();
			iDstNeurID = pCurEdge->GetDestinationID(pCurNeur);
			fEdgeValue = pCurEdge->GetValue();
			BZ2_bzWrite( &iBZ2Error, bz2out, &iDstLayerID, sizeof(int) );
			BZ2_bzWrite( &iBZ2Error, bz2out, &iDstNeurID, sizeof(int) );
			BZ2_bzWrite( &iBZ2Error, bz2out, &fEdgeValue, sizeof(float) );
		}
	}
}

int BPLayer::ImpFromFS(BZFILE* bz2in, int iBZ2Error, ConTable &Table) {
	std::cout<<"Load BPLayer from FS()"<<std::endl;
	int iLayerID = AbsLayer::ImpFromFS(bz2in, iBZ2Error, Table);

	unsigned int iNmbOfConnects 	= 0;
	float fEdgeValue 	= 0.0f;
	int iDstLayerID 	= -1;
	int iDstNeurID 		= -1;

	bool bHasBias 		= false;
	int iZLayer 		= -1;

	BZ2_bzRead( &iBZ2Error, bz2in, &bHasBias, sizeof(bool) );
	BZ2_bzRead( &iBZ2Error, bz2in, &iZLayer, sizeof(int) );
	Table.ZValOfLayer.push_back(iZLayer);

	if(bHasBias) {
		BZ2_bzRead( &iBZ2Error, bz2in, &iNmbOfConnects, sizeof(int) );
		for(unsigned int j = 0; j < iNmbOfConnects; j++) {
			BZ2_bzRead( &iBZ2Error, bz2in, &iDstLayerID, sizeof(int) );
			BZ2_bzRead( &iBZ2Error, bz2in, &iDstNeurID, sizeof(int) );
			BZ2_bzRead( &iBZ2Error, bz2in, &fEdgeValue, sizeof(float) );
			ConDescr	cCurCon;
			cCurCon.m_fVal 			= fEdgeValue;
			cCurCon.m_iDstNeurID 	= iDstNeurID;
			cCurCon.m_iSrcLayerID 	= iLayerID;
			cCurCon.m_iDstLayerID 	= iDstLayerID;
			Table.BiasCons.push_back(cCurCon);
		}
	}

	return iLayerID;
}

F2DArray BPLayer::ExpBiasEdgesOut() const {
	unsigned int iHeight 	= 1;
	unsigned int iWidth 	= m_pBiasNeuron->GetConsO().size();

	assert(iWidth > 0);

	F2DArray vRes;
	vRes.Alloc(iWidth, iHeight);

	for(int x = 0; x < static_cast<int>(iWidth); x++) {
		vRes[0][x] = m_pBiasNeuron->GetConO(x)->GetValue();
	}
	return vRes;
}

void BPLayer::ImpBiasEdgesOut(const F2DArray &mat) const {
	unsigned int iWidth 	= m_pBiasNeuron->GetConsO().size();

	assert(iWidth == mat.getW() );

	for(int x = 0; x < static_cast<int>(iWidth); x++) {
		//std::cout<<"mat: "<<mat[0][x]<<std::endl;
		m_pBiasNeuron->GetConO(x)->SetValue(mat[0][x]);
		//std::cout<<"val: "<<m_pBiasNeuron->GetConO(x)->GetValue()<<std::endl;
	}
}

void BPLayer::ImpMomentumsEdgesIn(const F2DArray &mat) {
	unsigned int iHeight 	= m_lNeurons.at(0)->GetConsI().size();
	unsigned int iWidth 	= m_lNeurons.size();

	assert(iHeight == mat.GetH() );
	assert(iWidth == mat.GetW() );

	#pragma omp parallel for
	for(int y = 0; y < static_cast<int>(iHeight); y++) {
		for(unsigned int x = 0; x < iWidth; x++) {
			m_lNeurons.at(x)->GetConI(y)->SetMomentum(mat[y][x]);
		}
	}
}

void BPLayer::ImpMomentumsEdgesOut(const F2DArray &mat) {
	unsigned int iHeight 	= m_lNeurons.at(0)->GetConsO().size();
	unsigned int iWidth 	= m_lNeurons.size();

	assert(iHeight == mat.GetH() );
	assert(iWidth == mat.GetW() );

	#pragma omp parallel for
	for(int y = 0; y < static_cast<int>(iHeight); y++) {
		for(unsigned int x = 0; x < iWidth; x++) {
			m_lNeurons.at(x)->GetConO(y)->SetMomentum(mat[y][x]);
		}
	}
}

/*
 * AUSGABEOPERATOR
 * OSTREAM
 */
std::ostream& operator << (std::ostream &os, BPLayer &op)
{
	if(op.GetBiasNeuron() != 0)
	os << "Bias neuron: \t" << op.GetBiasNeuron()->GetValue() 	<< std::endl;
    os << "Nr. neurons: \t" << op.GetNeurons().size() 					<< std::endl;
    return os;     // Ref. auf Stream
}

std::ostream& operator << (std::ostream &os, BPLayer *op)
{
	if(op->GetBiasNeuron() != 0)
	os << "Bias neuron: \t" << op->GetBiasNeuron()->GetValue()	<< std::endl;
    os << "Nr. neurons: \t" << op->GetNeurons().size() 					<< std::endl;
    return os;     // Ref. auf Stream
}

<commit_msg>- Typo corrected<commit_after>/*
 * BPLayer.cpp
 *
 *  Created on: 02.06.2009
 *      Author: Xerces
 */

#include <cassert>
//own classes
#include <math/ANFunctions.h>
#include <basic/ANEdge.h>
#include <basic/ANAbsNeuron.h>
#include <ANBPNeuron.h>
#include <ANBPLayer.h>

#include <containers/ANConTable.h>

using namespace ANN;

BPLayer::BPLayer(int iZLayer) {
	m_pBiasNeuron = NULL;
	m_iZLayer = iZLayer;
}

BPLayer::BPLayer(const BPLayer *pLayer, int iZLayer) {
	int iNumber 			= pLayer->GetNeurons().size();
	LayerTypeFlag fType 	= pLayer->GetFlag();
	m_pBiasNeuron 			= NULL;

	m_iZLayer = iZLayer;

	Resize(iNumber);
	SetFlag(fType);
}

BPLayer::BPLayer(const unsigned int &iNumber, LayerTypeFlag fType, int iZLayer) {
	Resize(iNumber);
	m_pBiasNeuron = NULL;
	SetFlag(fType);

	m_iZLayer = iZLayer;
}

void BPLayer::SetZLayer(int iZLayer) {
	m_iZLayer = iZLayer;
}

int BPLayer::GetZLayer() {
	return m_iZLayer;
}

BPLayer::~BPLayer() {
	if(m_pBiasNeuron) {
		delete m_pBiasNeuron;
	}
}

void BPLayer::Resize(const unsigned int &iSize) {
	EraseAll();
	AddNeurons(iSize);
}

void BPLayer::AddNeurons(const unsigned int &iSize) {
	for(unsigned int i = 0; i < iSize; i++) {
		AbsNeuron *pNeuron = new BPNeuron(this);
		m_lNeurons.push_back(pNeuron);
		pNeuron->SetID(m_lNeurons.size()-1);
	}
}

void BPLayer::ConnectLayer(AbsLayer *pDestLayer, const bool &bAllowAdapt) {
	AbsNeuron *pSrcNeuron;

	/*
	 * Vernetze jedes Neuron dieser Schicht mit jedem Neuron in "destLayer"
	 */
	for(unsigned int i = 0; i < m_lNeurons.size(); i++) {
		pSrcNeuron = m_lNeurons[i];
		Connect(pSrcNeuron, pDestLayer, bAllowAdapt);
	}

	if(m_pBiasNeuron) {
		Connect(m_pBiasNeuron, pDestLayer, true);
	}
}

void BPLayer::ConnectLayer(
		AbsLayer *pDestLayer,
		std::vector<std::vector<int> > Connections,
		const bool bAllowAdapt)
{
	AbsNeuron *pSrcNeuron;

	assert( Connections.size() != m_lNeurons.size() );
	for(unsigned int i = 0; i < Connections.size(); i++) {
		std::vector<int> subArray = Connections.at(i);
		pSrcNeuron = GetNeuron(i);
		assert(i != pSrcNeuron->GetID() );

		for(unsigned int j = 0; j < subArray.size(); j++) {
			assert( j < pDestLayer->GetNeurons().size() );
			AbsNeuron *pDestNeuron = pDestLayer->GetNeuron(j);
			assert( j < pDestNeuron->GetID() );
			Connect(pSrcNeuron, pDestNeuron, bAllowAdapt);
		}
	}

	if(m_pBiasNeuron) {
		Connect(m_pBiasNeuron, pDestLayer, true);
	}
}

BPNeuron *BPLayer::GetBiasNeuron() const {
	return m_pBiasNeuron;
}

void BPLayer::SetFlag(const LayerTypeFlag &fType) {
	m_fTypeFlag = fType;
	if( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {
		m_pBiasNeuron = new BPNeuron(this);
		m_pBiasNeuron->SetValue(1.0f);
	}
}

void BPLayer::AddFlag(const LayerTypeFlag &fType) {
	if( !(m_fTypeFlag & fType) )
	m_fTypeFlag |= fType;
	if( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {
		m_pBiasNeuron = new BPNeuron(this);
		m_pBiasNeuron->SetValue(1.0f);
	}
}

void BPLayer::SetLearningRate(const float &fVal) {
	#pragma omp parallel for
	for(int j = 0; j < static_cast<int>( m_lNeurons.size() ); j++) {
		((BPNeuron*)m_lNeurons[j])->SetLearningRate(fVal);
	}
}

void BPLayer::SetMomentum(const float &fVal) {
	#pragma omp parallel for
	for(int j = 0; j < static_cast<int>( m_lNeurons.size() ); j++) {
		((BPNeuron*)m_lNeurons[j])->SetMomentum(fVal);
	}
}

void BPLayer::SetWeightDecay(const float &fVal) {
	#pragma omp parallel for
	for(int j = 0; j < static_cast<int>( m_lNeurons.size() ); j++) {
		((BPNeuron*)m_lNeurons[j])->SetWeightDecay(fVal);
	}
}

void BPLayer::ExpToFS(BZFILE* bz2out, int iBZ2Error) {
	std::cout<<"Save BPLayer to FS()"<<std::endl;
	AbsLayer::ExpToFS(bz2out, iBZ2Error);

	unsigned int iNmbOfConnects 	= 0;
	float fEdgeValue 	= 0.0f;
	int iDstLayerID 	= -1;
	int iDstNeurID 		= -1;

	bool bHasBias 		= false;
	int iZLayer 		= m_iZLayer;

	(GetBiasNeuron() == NULL) ? bHasBias = false : bHasBias = true;
	BZ2_bzWrite( &iBZ2Error, bz2out, &bHasBias, sizeof(bool) );
	BZ2_bzWrite( &iBZ2Error, bz2out, &iZLayer, sizeof(int) );

	if(bHasBias) {
		AbsNeuron *pCurNeur = GetBiasNeuron();
		iNmbOfConnects = pCurNeur->GetConsO().size();
		BZ2_bzWrite( &iBZ2Error, bz2out, &iNmbOfConnects, sizeof(int) );
		for(unsigned int k = 0; k < iNmbOfConnects; k++) {
			Edge *pCurEdge = pCurNeur->GetConO(k);
			iDstLayerID = pCurEdge->GetDestination(pCurNeur)->GetParent()->GetID();
			iDstNeurID = pCurEdge->GetDestinationID(pCurNeur);
			fEdgeValue = pCurEdge->GetValue();
			BZ2_bzWrite( &iBZ2Error, bz2out, &iDstLayerID, sizeof(int) );
			BZ2_bzWrite( &iBZ2Error, bz2out, &iDstNeurID, sizeof(int) );
			BZ2_bzWrite( &iBZ2Error, bz2out, &fEdgeValue, sizeof(float) );
		}
	}
}

int BPLayer::ImpFromFS(BZFILE* bz2in, int iBZ2Error, ConTable &Table) {
	std::cout<<"Load BPLayer from FS()"<<std::endl;
	int iLayerID = AbsLayer::ImpFromFS(bz2in, iBZ2Error, Table);

	unsigned int iNmbOfConnects 	= 0;
	float fEdgeValue 	= 0.0f;
	int iDstLayerID 	= -1;
	int iDstNeurID 		= -1;

	bool bHasBias 		= false;
	int iZLayer 		= -1;

	BZ2_bzRead( &iBZ2Error, bz2in, &bHasBias, sizeof(bool) );
	BZ2_bzRead( &iBZ2Error, bz2in, &iZLayer, sizeof(int) );
	Table.ZValOfLayer.push_back(iZLayer);

	if(bHasBias) {
		BZ2_bzRead( &iBZ2Error, bz2in, &iNmbOfConnects, sizeof(int) );
		for(unsigned int j = 0; j < iNmbOfConnects; j++) {
			BZ2_bzRead( &iBZ2Error, bz2in, &iDstLayerID, sizeof(int) );
			BZ2_bzRead( &iBZ2Error, bz2in, &iDstNeurID, sizeof(int) );
			BZ2_bzRead( &iBZ2Error, bz2in, &fEdgeValue, sizeof(float) );
			ConDescr	cCurCon;
			cCurCon.m_fVal 			= fEdgeValue;
			cCurCon.m_iDstNeurID 	= iDstNeurID;
			cCurCon.m_iSrcLayerID 	= iLayerID;
			cCurCon.m_iDstLayerID 	= iDstLayerID;
			Table.BiasCons.push_back(cCurCon);
		}
	}

	return iLayerID;
}

F2DArray BPLayer::ExpBiasEdgesOut() const {
	unsigned int iHeight 	= 1;
	unsigned int iWidth 	= m_pBiasNeuron->GetConsO().size();

	assert(iWidth > 0);

	F2DArray vRes;
	vRes.Alloc(iWidth, iHeight);

	for(int x = 0; x < static_cast<int>(iWidth); x++) {
		vRes[0][x] = m_pBiasNeuron->GetConO(x)->GetValue();
	}
	return vRes;
}

void BPLayer::ImpBiasEdgesOut(const F2DArray &mat) const {
	unsigned int iWidth 	= m_pBiasNeuron->GetConsO().size();

	assert(iWidth == mat.GetW() );

	for(int x = 0; x < static_cast<int>(iWidth); x++) {
		//std::cout<<"mat: "<<mat[0][x]<<std::endl;
		m_pBiasNeuron->GetConO(x)->SetValue(mat[0][x]);
		//std::cout<<"val: "<<m_pBiasNeuron->GetConO(x)->GetValue()<<std::endl;
	}
}

void BPLayer::ImpMomentumsEdgesIn(const F2DArray &mat) {
	unsigned int iHeight 	= m_lNeurons.at(0)->GetConsI().size();
	unsigned int iWidth 	= m_lNeurons.size();

	assert(iHeight == mat.GetH() );
	assert(iWidth == mat.GetW() );

	#pragma omp parallel for
	for(int y = 0; y < static_cast<int>(iHeight); y++) {
		for(unsigned int x = 0; x < iWidth; x++) {
			m_lNeurons.at(x)->GetConI(y)->SetMomentum(mat[y][x]);
		}
	}
}

void BPLayer::ImpMomentumsEdgesOut(const F2DArray &mat) {
	unsigned int iHeight 	= m_lNeurons.at(0)->GetConsO().size();
	unsigned int iWidth 	= m_lNeurons.size();

	assert(iHeight == mat.GetH() );
	assert(iWidth == mat.GetW() );

	#pragma omp parallel for
	for(int y = 0; y < static_cast<int>(iHeight); y++) {
		for(unsigned int x = 0; x < iWidth; x++) {
			m_lNeurons.at(x)->GetConO(y)->SetMomentum(mat[y][x]);
		}
	}
}

/*
 * AUSGABEOPERATOR
 * OSTREAM
 */
std::ostream& operator << (std::ostream &os, BPLayer &op)
{
	if(op.GetBiasNeuron() != 0)
	os << "Bias neuron: \t" << op.GetBiasNeuron()->GetValue() 	<< std::endl;
    os << "Nr. neurons: \t" << op.GetNeurons().size() 					<< std::endl;
    return os;     // Ref. auf Stream
}

std::ostream& operator << (std::ostream &os, BPLayer *op)
{
	if(op->GetBiasNeuron() != 0)
	os << "Bias neuron: \t" << op->GetBiasNeuron()->GetValue()	<< std::endl;
    os << "Nr. neurons: \t" << op->GetNeurons().size() 					<< std::endl;
    return os;     // Ref. auf Stream
}

<|endoftext|>


<commit_before>#include <unordered_map>

#include "AttributeModifierName.h"
#include "PrimaryAttribute.h"
#include "PrimaryAttributeName.h"
#include "../Math/Random.h"

#include "components/debug/Debug.h"

const std::unordered_map<PrimaryAttributeName, std::string> PrimaryAttributeDisplayNames =
{
	{ PrimaryAttributeName::Strength, "Strength" },
	{ PrimaryAttributeName::Intelligence, "Intelligence" },
	{ PrimaryAttributeName::Willpower, "Willpower" },
	{ PrimaryAttributeName::Agility, "Agility" },
	{ PrimaryAttributeName::Speed, "Speed" },
	{ PrimaryAttributeName::Endurance, "Endurance" },
	{ PrimaryAttributeName::Personality, "Personality" },
	{ PrimaryAttributeName::Luck, "Luck" }
};

const std::unordered_map<PrimaryAttributeName, std::vector<AttributeModifierName>> PrimaryAttributeModifierNames =
{
	{ PrimaryAttributeName::Strength, { AttributeModifierName::MeleeDamage } },
	{ PrimaryAttributeName::Intelligence, { } },
	{ PrimaryAttributeName::Willpower, { AttributeModifierName::MagicDefense } },
	{ PrimaryAttributeName::Agility, { AttributeModifierName::ToHit, AttributeModifierName::ToDefense } },
	{ PrimaryAttributeName::Speed, { } },
	{ PrimaryAttributeName::Endurance, { AttributeModifierName::HealthPerLevel,
	AttributeModifierName::HealModifier } },
	{ PrimaryAttributeName::Personality, { AttributeModifierName::Charisma } },
	{ PrimaryAttributeName::Luck, { } }
};

const int PrimaryAttribute::MIN_VALUE = 0;
const int PrimaryAttribute::MAX_VALUE = 100;

PrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int baseValue)
{
	DebugAssert(baseValue >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(baseValue <= PrimaryAttribute::MAX_VALUE);

	this->attributeName = attributeName;
	this->baseValue = baseValue;
}

PrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int raceID, bool male, Random &random)
{
	DebugAssert(raceID >= 0);
	DebugAssert(raceID <= 7);

	this->attributeName = attributeName;

	// Lower limit (non-inclusive) of base attribute value, set by race and gender below.
	// 20-sided-die roll will be added.
	int baseValueBase;

	// Source: https://en.uesp.net/wiki/Arena:Character_Creation#Character_Stats
	if (raceID == 0) // Breton
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 50;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 50;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = 40;
	}
	else if (raceID == 1) // Redguard
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = male ? 40 : 30;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 40 : 50;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 50;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 50;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = 40;
	}
	else if (raceID == 2) // Nord
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = male ? 30 : 40;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 30 : 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = male ? 40 : 50;
	}
	else if (raceID == 3) // Dark Elf
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 50;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = 40;
	}
	else if (raceID == 4) // High Elf
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 50;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = male ? 40 : 50;
		else baseValueBase = 40;
	}
	else if (raceID == 5) // Wood Elf
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = male ? 30 : 40;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = male ? 30 : 40;
	}
	else if (raceID == 6) // Khajiit
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 40 : 50;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 30;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = 50;
	}
	else // Argonian
	{
		if (attributeName == PrimaryAttributeName::Strength) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 40;
		else if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 50 : 40;
		else if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = male ? 30 : 40;
		else if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;
		else baseValueBase = male ? 30 : 40;
	}

	this->baseValue = baseValueBase + random.next(20) + 1;
}

int PrimaryAttribute::get() const
{
	DebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);

	return this->baseValue;
}

PrimaryAttributeName PrimaryAttribute::getAttributeName() const
{
	return this->attributeName;
}

std::vector<AttributeModifierName> PrimaryAttribute::getModifierNames() const
{
	auto modifierNames = PrimaryAttributeModifierNames.at(this->getAttributeName());
	return modifierNames;
}

int PrimaryAttribute::getModifier() const
{
	DebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);

	// This value is exactly right. Try some more experiments.
	int modifierValue = (this->baseValue - 50) / 10;
	return modifierValue;
}

std::string PrimaryAttribute::toString() const
{
	auto displayName = PrimaryAttributeDisplayNames.at(this->getAttributeName());
	return displayName;
}

void PrimaryAttribute::set(int value)
{
	// The caller shouldn't try to set the value to a bad value. If only this was Ada!
	// Ada has automatic bounds checking on numeric types, like "percent is 0.0...100.0"
	// or something, so no assertions would be necessary.
	DebugAssert(value >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(value <= PrimaryAttribute::MAX_VALUE);

	this->baseValue = value;
}
<commit_msg>Removed hardcoded attribute values.<commit_after>#include <unordered_map>

#include "AttributeModifierName.h"
#include "PrimaryAttribute.h"
#include "PrimaryAttributeName.h"
#include "../Math/Random.h"

#include "components/debug/Debug.h"

const std::unordered_map<PrimaryAttributeName, std::string> PrimaryAttributeDisplayNames =
{
	{ PrimaryAttributeName::Strength, "Strength" },
	{ PrimaryAttributeName::Intelligence, "Intelligence" },
	{ PrimaryAttributeName::Willpower, "Willpower" },
	{ PrimaryAttributeName::Agility, "Agility" },
	{ PrimaryAttributeName::Speed, "Speed" },
	{ PrimaryAttributeName::Endurance, "Endurance" },
	{ PrimaryAttributeName::Personality, "Personality" },
	{ PrimaryAttributeName::Luck, "Luck" }
};

const std::unordered_map<PrimaryAttributeName, std::vector<AttributeModifierName>> PrimaryAttributeModifierNames =
{
	{ PrimaryAttributeName::Strength, { AttributeModifierName::MeleeDamage } },
	{ PrimaryAttributeName::Intelligence, { } },
	{ PrimaryAttributeName::Willpower, { AttributeModifierName::MagicDefense } },
	{ PrimaryAttributeName::Agility, { AttributeModifierName::ToHit, AttributeModifierName::ToDefense } },
	{ PrimaryAttributeName::Speed, { } },
	{ PrimaryAttributeName::Endurance, { AttributeModifierName::HealthPerLevel,
	AttributeModifierName::HealModifier } },
	{ PrimaryAttributeName::Personality, { AttributeModifierName::Charisma } },
	{ PrimaryAttributeName::Luck, { } }
};

const int PrimaryAttribute::MIN_VALUE = 0;
const int PrimaryAttribute::MAX_VALUE = 100;

PrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int baseValue)
{
	DebugAssert(baseValue >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(baseValue <= PrimaryAttribute::MAX_VALUE);

	this->attributeName = attributeName;
	this->baseValue = baseValue;
}

PrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int raceID, bool male, Random &random)
{
	DebugAssert(raceID >= 0);
	DebugAssert(raceID <= 7);

	this->attributeName = attributeName;

	// @todo: read from ExeData::entities::raceAttributes
	this->baseValue = 0;
}

int PrimaryAttribute::get() const
{
	DebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);

	return this->baseValue;
}

PrimaryAttributeName PrimaryAttribute::getAttributeName() const
{
	return this->attributeName;
}

std::vector<AttributeModifierName> PrimaryAttribute::getModifierNames() const
{
	auto modifierNames = PrimaryAttributeModifierNames.at(this->getAttributeName());
	return modifierNames;
}

int PrimaryAttribute::getModifier() const
{
	DebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);

	// This value is exactly right. Try some more experiments.
	int modifierValue = (this->baseValue - 50) / 10;
	return modifierValue;
}

std::string PrimaryAttribute::toString() const
{
	auto displayName = PrimaryAttributeDisplayNames.at(this->getAttributeName());
	return displayName;
}

void PrimaryAttribute::set(int value)
{
	// The caller shouldn't try to set the value to a bad value. If only this was Ada!
	// Ada has automatic bounds checking on numeric types, like "percent is 0.0...100.0"
	// or something, so no assertions would be necessary.
	DebugAssert(value >= PrimaryAttribute::MIN_VALUE);
	DebugAssert(value <= PrimaryAttribute::MAX_VALUE);

	this->baseValue = value;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights.  These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdirectfbscreen.h"
#include "qdirectfbpaintdevice.h"
#include "qdirectfbpaintengine.h"

#ifndef QT_NO_QWS_DIRECTFB

QT_BEGIN_NAMESPACE

QDirectFBPaintDevice::QDirectFBPaintDevice(QDirectFBScreen *scr)
    : QCustomRasterPaintDevice(0), dfbSurface(0), screen(scr),
      bpl(-1), lockFlgs(DFBSurfaceLockFlags(0)), mem(0), engine(0), imageFormat(QImage::Format_Invalid)
{
#ifdef QT_DIRECTFB_SUBSURFACE
    subSurface = 0;
    syncPending = false;
#endif
}

QDirectFBPaintDevice::~QDirectFBPaintDevice()
{
    unlockSurface();
    if (QDirectFBScreen::instance()) {
        unlockSurface();
#ifdef QT_DIRECTFB_SUBSURFACE
        if (subSurface) {
            screen->releaseDFBSurface(subSurface);
        }
#endif
        if (dfbSurface) {
            screen->releaseDFBSurface(dfbSurface);
        }
    }
    delete engine;
}

IDirectFBSurface *QDirectFBPaintDevice::directFBSurface() const
{
    return dfbSurface;
}

bool QDirectFBPaintDevice::lockSurface(DFBSurfaceLockFlags lockFlags)
{
    if (lockFlgs && (lockFlags & ~lockFlgs))
        unlockSurface();
    if (!mem) {
        Q_ASSERT(dfbSurface);
#ifdef QT_DIRECTFB_SUBSURFACE
        if (!subSurface) {
            DFBResult result;
            subSurface = screen->getSubSurface(dfbSurface, QRect(), QDirectFBScreen::TrackSurface, &result);
            if (result != DFB_OK || !subSurface) {
                DirectFBError("Couldn't create sub surface", result);
                return false;
            }
        }
        IDirectFBSurface *surface = subSurface;
#else
        IDirectFBSurface *surface = dfbSurface;
#endif
        Q_ASSERT(surface);
        mem = QDirectFBScreen::lockSurface(surface, lockFlags, &bpl);
        lockFlgs = lockFlags;
        Q_ASSERT(mem);
        Q_ASSERT(bpl > 0);
        const QSize s = size();
        lockedImage = QImage(mem, s.width(), s.height(), bpl,
                             QDirectFBScreen::getImageFormat(dfbSurface));
        return true;
    }
#ifdef QT_DIRECTFB_SUBSURFACE
    if (syncPending) {
        syncPending = false;
        screen->waitIdle();
    }
#endif
    return false;
}

void QDirectFBPaintDevice::unlockSurface()
{
    if (QDirectFBScreen::instance() && lockFlgs) {
#ifdef QT_DIRECTFB_SUBSURFACE
        IDirectFBSurface *surface = subSurface;
#else
        IDirectFBSurface *surface = dfbSurface;
#endif
        if (surface) {
            surface->Unlock(surface);
            lockFlgs = static_cast<DFBSurfaceLockFlags>(0);
        }
    }
}

void *QDirectFBPaintDevice::memory() const
{
    return mem;
}

QImage::Format QDirectFBPaintDevice::format() const
{
    return imageFormat;
}

int QDirectFBPaintDevice::bytesPerLine() const
{
    Q_ASSERT(!mem || bpl != -1);
    return bpl;
}

QSize QDirectFBPaintDevice::size() const
{
    int w, h;
    dfbSurface->GetSize(dfbSurface, &w, &h);
    return QSize(w, h);
}

int QDirectFBPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const
{
    if (!dfbSurface)
        return 0;

    switch (metric) {
    case QPaintDevice::PdmWidth:
    case QPaintDevice::PdmHeight:
        return (metric == PdmWidth ? size().width() : size().height());
    case QPaintDevice::PdmWidthMM:
        return (size().width() * 1000) / dotsPerMeterX();
    case QPaintDevice::PdmHeightMM:
        return (size().height() * 1000) / dotsPerMeterY();
    case QPaintDevice::PdmPhysicalDpiX:
    case QPaintDevice::PdmDpiX:
        return (dotsPerMeterX() * 254) / 10000; // 0.0254 meters-per-inch
    case QPaintDevice::PdmPhysicalDpiY:
    case QPaintDevice::PdmDpiY:
        return (dotsPerMeterY() * 254) / 10000; // 0.0254 meters-per-inch
    case QPaintDevice::PdmDepth:
        return QDirectFBScreen::depth(imageFormat);
    case QPaintDevice::PdmNumColors: {
        if (!lockedImage.isNull())
            return lockedImage.numColors();

        DFBResult result;
        IDirectFBPalette *palette = 0;
        unsigned int numColors = 0;

        result = dfbSurface->GetPalette(dfbSurface, &palette);
        if ((result != DFB_OK) || !palette)
            return 0;

        result = palette->GetSize(palette, &numColors);
        palette->Release(palette);
        if (result != DFB_OK)
            return 0;

        return numColors;
    }
    default:
        qCritical("QDirectFBPaintDevice::metric(): Unhandled metric!");
        return 0;
    }
}

QPaintEngine *QDirectFBPaintDevice::paintEngine() const
{
    return engine;
}

QT_END_NAMESPACE

#endif // QT_NO_QWS_DIRECTFB
<commit_msg>Make sure to set mem to 0 in unlockSurface<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights.  These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdirectfbscreen.h"
#include "qdirectfbpaintdevice.h"
#include "qdirectfbpaintengine.h"

#ifndef QT_NO_QWS_DIRECTFB

QT_BEGIN_NAMESPACE

QDirectFBPaintDevice::QDirectFBPaintDevice(QDirectFBScreen *scr)
    : QCustomRasterPaintDevice(0), dfbSurface(0), screen(scr),
      bpl(-1), lockFlgs(DFBSurfaceLockFlags(0)), mem(0), engine(0), imageFormat(QImage::Format_Invalid)
{
#ifdef QT_DIRECTFB_SUBSURFACE
    subSurface = 0;
    syncPending = false;
#endif
}

QDirectFBPaintDevice::~QDirectFBPaintDevice()
{
    unlockSurface();
    if (QDirectFBScreen::instance()) {
        unlockSurface();
#ifdef QT_DIRECTFB_SUBSURFACE
        if (subSurface) {
            screen->releaseDFBSurface(subSurface);
        }
#endif
        if (dfbSurface) {
            screen->releaseDFBSurface(dfbSurface);
        }
    }
    delete engine;
}

IDirectFBSurface *QDirectFBPaintDevice::directFBSurface() const
{
    return dfbSurface;
}

bool QDirectFBPaintDevice::lockSurface(DFBSurfaceLockFlags lockFlags)
{
    if (lockFlgs && (lockFlags & ~lockFlgs))
        unlockSurface();
    if (!mem) {
        Q_ASSERT(dfbSurface);
#ifdef QT_DIRECTFB_SUBSURFACE
        if (!subSurface) {
            DFBResult result;
            subSurface = screen->getSubSurface(dfbSurface, QRect(), QDirectFBScreen::TrackSurface, &result);
            if (result != DFB_OK || !subSurface) {
                DirectFBError("Couldn't create sub surface", result);
                return false;
            }
        }
        IDirectFBSurface *surface = subSurface;
#else
        IDirectFBSurface *surface = dfbSurface;
#endif
        Q_ASSERT(surface);
        mem = QDirectFBScreen::lockSurface(surface, lockFlags, &bpl);
        lockFlgs = lockFlags;
        Q_ASSERT(mem);
        Q_ASSERT(bpl > 0);
        const QSize s = size();
        lockedImage = QImage(mem, s.width(), s.height(), bpl,
                             QDirectFBScreen::getImageFormat(dfbSurface));
        return true;
    }
#ifdef QT_DIRECTFB_SUBSURFACE
    if (syncPending) {
        syncPending = false;
        screen->waitIdle();
    }
#endif
    return false;
}

void QDirectFBPaintDevice::unlockSurface()
{
    if (QDirectFBScreen::instance() && lockFlgs) {
#ifdef QT_DIRECTFB_SUBSURFACE
        IDirectFBSurface *surface = subSurface;
#else
        IDirectFBSurface *surface = dfbSurface;
#endif
        if (surface) {
            surface->Unlock(surface);
            lockFlgs = static_cast<DFBSurfaceLockFlags>(0);
            mem = 0;
        }
    }
}

void *QDirectFBPaintDevice::memory() const
{
    return mem;
}

QImage::Format QDirectFBPaintDevice::format() const
{
    return imageFormat;
}

int QDirectFBPaintDevice::bytesPerLine() const
{
    Q_ASSERT(!mem || bpl != -1);
    return bpl;
}

QSize QDirectFBPaintDevice::size() const
{
    int w, h;
    dfbSurface->GetSize(dfbSurface, &w, &h);
    return QSize(w, h);
}

int QDirectFBPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const
{
    if (!dfbSurface)
        return 0;

    switch (metric) {
    case QPaintDevice::PdmWidth:
    case QPaintDevice::PdmHeight:
        return (metric == PdmWidth ? size().width() : size().height());
    case QPaintDevice::PdmWidthMM:
        return (size().width() * 1000) / dotsPerMeterX();
    case QPaintDevice::PdmHeightMM:
        return (size().height() * 1000) / dotsPerMeterY();
    case QPaintDevice::PdmPhysicalDpiX:
    case QPaintDevice::PdmDpiX:
        return (dotsPerMeterX() * 254) / 10000; // 0.0254 meters-per-inch
    case QPaintDevice::PdmPhysicalDpiY:
    case QPaintDevice::PdmDpiY:
        return (dotsPerMeterY() * 254) / 10000; // 0.0254 meters-per-inch
    case QPaintDevice::PdmDepth:
        return QDirectFBScreen::depth(imageFormat);
    case QPaintDevice::PdmNumColors: {
        if (!lockedImage.isNull())
            return lockedImage.numColors();

        DFBResult result;
        IDirectFBPalette *palette = 0;
        unsigned int numColors = 0;

        result = dfbSurface->GetPalette(dfbSurface, &palette);
        if ((result != DFB_OK) || !palette)
            return 0;

        result = palette->GetSize(palette, &numColors);
        palette->Release(palette);
        if (result != DFB_OK)
            return 0;

        return numColors;
    }
    default:
        qCritical("QDirectFBPaintDevice::metric(): Unhandled metric!");
        return 0;
    }
}

QPaintEngine *QDirectFBPaintDevice::paintEngine() const
{
    return engine;
}

QT_END_NAMESPACE

#endif // QT_NO_QWS_DIRECTFB
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: layerparser.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: jb $ $Date: 2002-11-22 14:51:57 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "layerparser.hxx"

// -----------------------------------------------------------------------------
#ifndef CONFIGMGR_WRAPEXCEPTION_HXX
#include "wrapexception.hxx"
#endif

#define WRAP_PARSE_EXCEPTIONS()  \
    PASS_EXCEPTION(sax::SAXException)       \
    PASS_EXCEPTION(uno::RuntimeException)   \
    WRAP_CONFIGDATA_EXCEPTIONS( raiseParseException )   \
    WRAP_OTHER_EXCEPTIONS( raiseParseException )

#define WRAP_PARSE_EXCEPTIONS_MSG( msg )  \
    PASS_EXCEPTION(sax::SAXException)       \
    PASS_EXCEPTION(uno::RuntimeException)   \
    WRAP_CONFIGDATA_EXCEPTIONS1( raiseParseException, msg ) \
    WRAP_OTHER_EXCEPTIONS1( raiseParseException, msg )

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

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace xml
    {
// -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        namespace sax       = ::com::sun::star::xml::sax;
// -----------------------------------------------------------------------------

LayerParser::LayerParser(ServiceFactory const & _xSvcFactory, uno::Reference< backenduno::XLayerHandler > const & _xHandler)
: BasicParser(_xSvcFactory)
, m_xHandler(_xHandler)
, m_bRemoved(false)
, m_bNewProp(false)
{
    if (!m_xHandler.is())
    {
        OUString sMessage(RTL_CONSTASCII_USTRINGPARAM("Cannot create LayerParser: Unexpected NULL Handler"));
        throw uno::RuntimeException(sMessage, NULL);
    }
}
// -----------------------------------------------------------------------------

LayerParser::~LayerParser()
{
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::startDocument(  )
        throw (sax::SAXException, uno::RuntimeException)
{
    BasicParser::startDocument();

    try
    {
        OSL_ENSURE(isEmptyNode(), "BasicParser does not mark new document as empty");

        m_xHandler->startLayer();
        m_bRemoved = false;
        m_bNewProp = false;
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Starting layer")
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::endDocument(  ) throw (sax::SAXException, uno::RuntimeException)
{
    if (isEmptyNode()) OSL_TRACE("Configuration Parser: XML layer document ended without any data");

    BasicParser::endDocument();

    try
    {
        m_xHandler->endLayer();
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Ending layer")
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::startElement( const OUString& aName, const uno::Reference< sax::XAttributeList >& xAttribs )
        throw (sax::SAXException, uno::RuntimeException)
{
    if ( this->isSkipping() )
    {
        this->startSkipping( aName, xAttribs );
        return;
    }

    ElementInfo aInfo = getDataParser().parseElementInfo(aName,xAttribs);

    try
    {
        switch (aInfo.type)
        {
        case ElementType::group: case ElementType::set:
            OSL_ENSURE( false, "Layer XML parser - Unexpected: found group/set element (should be 'node')\n");
            // fall thru
        case ElementType::layer:
        case ElementType::node:
            this->startNode(aInfo,xAttribs);
            OSL_ASSERT( this->isInNode() && !this->isInProperty() );
            break;

        case ElementType::property:
            this->startProperty(aInfo,xAttribs);
            OSL_ASSERT( this->isInUnhandledProperty() );
            break;

        case ElementType::value:
            this->startValueData(xAttribs);
            OSL_ASSERT( this->isInValueData() );
            break;

        default: // skip unknown elements
            OSL_ENSURE( aInfo.type >= ElementType::other, "Layer XML parser - Unexpected: found schema element in layer data\n");
            OSL_ENSURE( aInfo.type <  ElementType::other, "Layer XML parser - Warning: ignoring unknown element tag\n");
            this->startSkipping( aName, xAttribs );
            return;
        }
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Starting Element")
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::endElement( const OUString& aName )
        throw (sax::SAXException, uno::RuntimeException)
{
    if ( this->wasSkipping(aName) )
        return;

    try
    {
        if ( this->isInValueData())
            this->endValueData();

        else if (this->isInProperty())
            this->endProperty();

        else if (this->isInNode())
            this->endNode();

        else {
            this->raiseParseException("Layer parser: Invalid XML: endElement without matching startElement");
        }
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Ending Element")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

void LayerParser::startNode( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )
{
    this->checkNotRemoved();

    BasicParser::startNode(aInfo,xAttribs);

    switch (aInfo.op)
    {
    case Operation::none:
    case Operation::modify:
        m_xHandler->overrideNode(aInfo.name,aInfo.flags);
        break;

    case Operation::replace:
        {
            backenduno::TemplateIdentifier aTemplate;
            if (getDataParser().getInstanceType(xAttribs,aTemplate.Name,aTemplate.Component))
                m_xHandler->addOrReplaceNodeFromTemplate(aInfo.name,aTemplate,aInfo.flags);
            else
                m_xHandler->addOrReplaceNode(aInfo.name,aInfo.flags);
        }
        break;

    case Operation::remove:
        m_xHandler->dropNode(aInfo.name);
        m_bRemoved = true;
        break;

    default: OSL_ASSERT(false);
    case Operation::unknown:
        this->raiseParseException("Layer parser: Invalid Data: unknown operation");
    }
}
// -----------------------------------------------------------------------------

void LayerParser::endNode()
{
    if (!this->isInRemoved())
        m_xHandler->endNode();
    else
        m_bRemoved = false;

    BasicParser::endNode();
}
// -----------------------------------------------------------------------------

void LayerParser::startProperty( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )
{
    this->checkNotRemoved();

    BasicParser::startProperty(aInfo,xAttribs);

    switch (aInfo.op)
    {
    case Operation::none:
    case Operation::modify:
        m_xHandler->overrideProperty(aInfo.name,aInfo.flags,getActivePropertyType());
        OSL_ASSERT(!m_bNewProp);
        break;

    case Operation::replace:
        // defer to later
        m_bNewProp = true;
        break;

    case Operation::remove:
        this->raiseParseException("Layer parser: Invalid Data: operation 'remove' is not permitted for properties");

    default: OSL_ASSERT(false);
    case Operation::unknown:
        this->raiseParseException("Layer parser: Invalid Data: unknown operation");
    }
    OSL_POSTCOND(this->isInUnhandledProperty(),"Error: Property not reckognized as unhandled");
}
// -----------------------------------------------------------------------------

void LayerParser::addOrReplaceCurrentProperty(const uno::Any& aValue)
{
    const ElementInfo& currentInfo = getActiveNodeInfo() ;

    OSL_ASSERT(currentInfo.op == Operation::replace) ;

    if (aValue.hasValue())
    {
        m_xHandler->addPropertyWithValue(currentInfo.name,
                                         currentInfo.flags, aValue) ;
    }
    else
    {
        m_xHandler->addProperty(currentInfo.name, currentInfo.flags,
                                getActivePropertyType()) ;
    }
}
// -----------------------------------------------------------------------------

void LayerParser::endProperty()
{
    OSL_ASSERT(!this->isInRemoved());

    if (m_bNewProp)
    {
        OSL_ASSERT(getActiveNodeInfo().op == Operation::replace);
        if (this->isInUnhandledProperty())
        {
            // No value tag is treated as NULL
            addOrReplaceCurrentProperty( uno::Any() ) ;
        }
        m_bNewProp = false;
    }
    else
    {
        OSL_ASSERT(getActiveNodeInfo().op != Operation::replace);
        m_xHandler->endProperty();
    }

    BasicParser::endProperty();
}
// -----------------------------------------------------------------------------

void LayerParser::startValueData(const uno::Reference< sax::XAttributeList >& xAttribs)
{
    this->checkNotRemoved();

    BasicParser::startValueData(xAttribs);
}
// -----------------------------------------------------------------------------

void LayerParser::endValueData()
{
    uno::Any aValue = this->getCurrentValue();

    if (m_bNewProp)
    {
        OSL_ENSURE(!isValueDataLocalized(),"Layer parser: Invalid Data: 'lang' ignored for newly added property.");

        addOrReplaceCurrentProperty(aValue) ;
    }
    else if (this->isValueDataLocalized())
    {
        OUString aLocale = this->getValueDataLocale();

        m_xHandler->setPropertyValueForLocale(aValue,aLocale);
    }
    else
    {
        m_xHandler->setPropertyValue(aValue);
    }

    BasicParser::endValueData();

    OSL_POSTCOND(!this->isInUnhandledProperty(),"Error: Property not reckognized as unhandled");
}
// -----------------------------------------------------------------------------

void LayerParser::checkNotRemoved()
{
    if (m_bRemoved)
        raiseParseException("Layer parser: Invalid Data: Data inside removed node.");
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
    } // namespace

// -----------------------------------------------------------------------------
} // namespace

<commit_msg>INTEGRATION: CWS configapi01 (1.9.26); FILE MERGED 2003/04/15 10:25:37 jb 1.9.26.1: #i11893# backend\updatedata.cxx<commit_after>/*************************************************************************
 *
 *  $RCSfile: layerparser.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-17 13:34:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "layerparser.hxx"

// -----------------------------------------------------------------------------
#ifndef CONFIGMGR_WRAPEXCEPTION_HXX
#include "wrapexception.hxx"
#endif

#define WRAP_PARSE_EXCEPTIONS()  \
    PASS_EXCEPTION(sax::SAXException)       \
    PASS_EXCEPTION(uno::RuntimeException)   \
    WRAP_CONFIGDATA_EXCEPTIONS( raiseParseException )   \
    WRAP_OTHER_EXCEPTIONS( raiseParseException )

#define WRAP_PARSE_EXCEPTIONS_MSG( msg )  \
    PASS_EXCEPTION(sax::SAXException)       \
    PASS_EXCEPTION(uno::RuntimeException)   \
    WRAP_CONFIGDATA_EXCEPTIONS1( raiseParseException, msg ) \
    WRAP_OTHER_EXCEPTIONS1( raiseParseException, msg )

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

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace xml
    {
// -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        namespace sax       = ::com::sun::star::xml::sax;
// -----------------------------------------------------------------------------

LayerParser::LayerParser(ServiceFactory const & _xSvcFactory, uno::Reference< backenduno::XLayerHandler > const & _xHandler)
: BasicParser(_xSvcFactory)
, m_xHandler(_xHandler)
, m_bRemoved(false)
, m_bNewProp(false)
{
    if (!m_xHandler.is())
    {
        OUString sMessage(RTL_CONSTASCII_USTRINGPARAM("Cannot create LayerParser: Unexpected NULL Handler"));
        throw uno::RuntimeException(sMessage, NULL);
    }
}
// -----------------------------------------------------------------------------

LayerParser::~LayerParser()
{
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::startDocument(  )
        throw (sax::SAXException, uno::RuntimeException)
{
    BasicParser::startDocument();

    try
    {
        OSL_ENSURE(isEmptyNode(), "BasicParser does not mark new document as empty");

        m_xHandler->startLayer();
        m_bRemoved = false;
        m_bNewProp = false;
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Starting layer")
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::endDocument(  ) throw (sax::SAXException, uno::RuntimeException)
{
    if (isEmptyNode()) OSL_TRACE("Configuration Parser: XML layer document ended without any data");

    BasicParser::endDocument();

    try
    {
        m_xHandler->endLayer();
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Ending layer")
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::startElement( const OUString& aName, const uno::Reference< sax::XAttributeList >& xAttribs )
        throw (sax::SAXException, uno::RuntimeException)
{
    if ( this->isSkipping() )
    {
        this->startSkipping( aName, xAttribs );
        return;
    }

    ElementInfo aInfo = getDataParser().parseElementInfo(aName,xAttribs);

    try
    {
        switch (aInfo.type)
        {
        case ElementType::group: case ElementType::set:
            OSL_ENSURE( false, "Layer XML parser - Unexpected: found group/set element (should be 'node')\n");
            // fall thru
        case ElementType::layer:
        case ElementType::node:
            this->startNode(aInfo,xAttribs);
            OSL_ASSERT( this->isInNode() && !this->isInProperty() );
            break;

        case ElementType::property:
            this->startProperty(aInfo,xAttribs);
            OSL_ASSERT( this->isInUnhandledProperty() );
            break;

        case ElementType::value:
            this->startValueData(xAttribs);
            OSL_ASSERT( this->isInValueData() );
            break;

        default: // skip unknown elements
            OSL_ENSURE( aInfo.type >= ElementType::other, "Layer XML parser - Unexpected: found schema element in layer data\n");
            OSL_ENSURE( aInfo.type <  ElementType::other, "Layer XML parser - Warning: ignoring unknown element tag\n");
            this->startSkipping( aName, xAttribs );
            return;
        }
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Starting Element")
}
// -----------------------------------------------------------------------------

void SAL_CALL LayerParser::endElement( const OUString& aName )
        throw (sax::SAXException, uno::RuntimeException)
{
    if ( this->wasSkipping(aName) )
        return;

    try
    {
        if ( this->isInValueData())
            this->endValueData();

        else if (this->isInProperty())
            this->endProperty();

        else if (this->isInNode())
            this->endNode();

        else {
            this->raiseParseException("Layer parser: Invalid XML: endElement without matching startElement");
        }
    }
    WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Ending Element")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

void LayerParser::startNode( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )
{
    this->checkNotRemoved();

    BasicParser::startNode(aInfo,xAttribs);

    switch (aInfo.op)
    {
    case Operation::none:
    case Operation::modify:
        m_xHandler->overrideNode(aInfo.name,aInfo.flags,false);
        break;

    case Operation::clear:
        m_xHandler->overrideNode(aInfo.name,aInfo.flags,true);
        break;

    case Operation::replace:
        {
            backenduno::TemplateIdentifier aTemplate;
            if (getDataParser().getInstanceType(xAttribs,aTemplate.Name,aTemplate.Component))
                m_xHandler->addOrReplaceNodeFromTemplate(aInfo.name,aTemplate,aInfo.flags);
            else
                m_xHandler->addOrReplaceNode(aInfo.name,aInfo.flags);
        }
        break;

    case Operation::remove:
        m_xHandler->dropNode(aInfo.name);
        m_bRemoved = true;
        break;

    default: OSL_ASSERT(false);
    case Operation::unknown:
        this->raiseParseException("Layer parser: Invalid Data: unknown operation");
    }
}
// -----------------------------------------------------------------------------

void LayerParser::endNode()
{
    if (!this->isInRemoved())
        m_xHandler->endNode();
    else
        m_bRemoved = false;

    BasicParser::endNode();
}
// -----------------------------------------------------------------------------

void LayerParser::startProperty( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )
{
    this->checkNotRemoved();

    BasicParser::startProperty(aInfo,xAttribs);

    switch (aInfo.op)
    {
    case Operation::none:
    case Operation::modify:
        m_xHandler->overrideProperty(aInfo.name,aInfo.flags,getActivePropertyType(),false);
        OSL_ASSERT(!m_bNewProp);
        break;

    case Operation::clear:
        m_xHandler->overrideProperty(aInfo.name,aInfo.flags,getActivePropertyType(),true);
        OSL_ASSERT(!m_bNewProp);
        break;

    case Operation::replace:
        // defer to later
        m_bNewProp = true;
        break;

    case Operation::remove:
        this->raiseParseException("Layer parser: Invalid Data: operation 'remove' is not permitted for properties");

    default: OSL_ASSERT(false);
    case Operation::unknown:
        this->raiseParseException("Layer parser: Invalid Data: unknown operation");
    }
    OSL_POSTCOND(this->isInUnhandledProperty(),"Error: Property not reckognized as unhandled");
}
// -----------------------------------------------------------------------------

void LayerParser::addOrReplaceCurrentProperty(const uno::Any& aValue)
{
    const ElementInfo& currentInfo = getActiveNodeInfo() ;

    OSL_ASSERT(currentInfo.op == Operation::replace) ;

    if (aValue.hasValue())
    {
        m_xHandler->addPropertyWithValue(currentInfo.name,
                                         currentInfo.flags, aValue) ;
    }
    else
    {
        m_xHandler->addProperty(currentInfo.name, currentInfo.flags,
                                getActivePropertyType()) ;
    }
}
// -----------------------------------------------------------------------------

void LayerParser::endProperty()
{
    OSL_ASSERT(!this->isInRemoved());

    if (m_bNewProp)
    {
        OSL_ASSERT(getActiveNodeInfo().op == Operation::replace);
        if (this->isInUnhandledProperty())
        {
            // No value tag is treated as NULL
            addOrReplaceCurrentProperty( uno::Any() ) ;
        }
        m_bNewProp = false;
    }
    else
    {
        OSL_ASSERT(getActiveNodeInfo().op != Operation::replace);
        m_xHandler->endProperty();
    }

    BasicParser::endProperty();
}
// -----------------------------------------------------------------------------

void LayerParser::startValueData(const uno::Reference< sax::XAttributeList >& xAttribs)
{
    this->checkNotRemoved();

    BasicParser::startValueData(xAttribs);
}
// -----------------------------------------------------------------------------

void LayerParser::endValueData()
{
    uno::Any aValue = this->getCurrentValue();

    if (m_bNewProp)
    {
        OSL_ENSURE(!isValueDataLocalized(),"Layer parser: Invalid Data: 'lang' ignored for newly added property.");

        addOrReplaceCurrentProperty(aValue) ;
    }
    else if (this->isValueDataLocalized())
    {
        OUString aLocale = this->getValueDataLocale();

        m_xHandler->setPropertyValueForLocale(aValue,aLocale);
    }
    else
    {
        m_xHandler->setPropertyValue(aValue);
    }

    BasicParser::endValueData();

    OSL_POSTCOND(!this->isInUnhandledProperty(),"Error: Property not reckognized as unhandled");
}
// -----------------------------------------------------------------------------

void LayerParser::checkNotRemoved()
{
    if (m_bRemoved)
        raiseParseException("Layer parser: Invalid Data: Data inside removed node.");
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
    } // namespace

// -----------------------------------------------------------------------------
} // namespace

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mpositionindicatorview.h"
#include "mpositionindicatorview_p.h"
#include "qapplication.h"

#include <QString>
#include <QTimer>
#include <QStyleOptionGraphicsItem>
#include <QPropertyAnimation>

#include "mtheme.h"
#include "mviewcreator.h"
#include "mpositionindicator.h"
#include "mscalableimage.h"

MPositionIndicatorViewPrivate::MPositionIndicatorViewPrivate()
    : controller(0),
      hideTimer(new QTimer()),
      visible(false),
      onDisplay(false)
{
}

MPositionIndicatorViewPrivate::~MPositionIndicatorViewPrivate()
{
    delete this->hideTimer;
}

void MPositionIndicatorViewPrivate::init(MPositionIndicator *controller)
{
    Q_Q(MPositionIndicatorView);

    this->controller = controller;
    hideTimer->setSingleShot(true);
    fadeAnimation = new QPropertyAnimation(controller, "opacity", q);

    q->connect(hideTimer, SIGNAL(timeout()), SLOT(hide()));
    q->connect(controller, SIGNAL(displayEntered()), SLOT(_q_displayEntered()));
    q->connect(controller, SIGNAL(displayExited()), SLOT(_q_displayExited()));
}

bool MPositionIndicatorViewPrivate::isInSwitcher() const
{
    bool isInSwitcher = false;
    if (controller->scene() && !controller->scene()->views().isEmpty()) {
        MWindow* win = qobject_cast<MWindow*>(controller->scene()->views().at(0));
        if (win) {
            isInSwitcher = win->isInSwitcher();
        }
    }
    return isInSwitcher;
}

void MPositionIndicatorViewPrivate::_q_displayEntered()
{
    Q_Q(MPositionIndicatorView);

    onDisplay = true;
    if (!isInSwitcher()) {
        hideTimer->start(q->style()->hideTimeout());
    }
}

void MPositionIndicatorViewPrivate::_q_displayExited()
{
    Q_Q(MPositionIndicatorView);

    /* stop everything and keep indicator visible for next use */
    onDisplay = false;
    hideTimer->stop();
    fadeAnimation->stop();
    controller->setProperty("opacity", 1.0f);
    visible = true;
    q->update();
}

MPositionIndicatorView::MPositionIndicatorView(MPositionIndicator *controller) :
    MWidgetView(* new MPositionIndicatorViewPrivate, controller)
{
    Q_D(MPositionIndicatorView);
    d->init(controller);
}

MPositionIndicatorView::~MPositionIndicatorView()
{
    Q_D(MPositionIndicatorView);
    d->controller = 0;
}

void MPositionIndicatorView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    Q_UNUSED(painter);
    Q_UNUSED(option);
}

void MPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    Q_UNUSED(option);
    Q_D(const MPositionIndicatorView);

    if (d->isInSwitcher()) {
        return;
    }

    QSizeF  vpSize = model()->viewportSize();
    QRectF  pRange = model()->range().adjusted(0, 0, vpSize.width(), vpSize.height());
    QPointF pPos   = model()->position();

    const MScalableImage *indicator = style()->indicatorImage();
    const MScalableImage *rail = style()->backgroundImage();

    if ((int)pRange.height() > (int)vpSize.height()) {

        int indicatorPixmapSizeX = indicator->pixmap()->width();
        int railPixmapSizeX = rail->pixmap()->width();

        int indicatorHeight = qMax(style()->minIndicatorSize(), int((vpSize.height()/pRange.height())*size().height()));
        int indicatorPositionY = (pPos.y()/pRange.height())*size().height();

        if (indicatorPositionY + indicatorHeight > size().height()) {
            indicatorHeight = size().height() - indicatorPositionY;
        }

        if (indicatorPositionY < 0) {
            indicatorHeight += indicatorPositionY;
            indicatorPositionY = 0;
        }

        int railPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - railPixmapSizeX);
        int indicatorPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - indicatorPixmapSizeX);

        rail->draw((qreal)railPositionX,
                    0.0,
                    (qreal)railPixmapSizeX,
                    size().height(),
                    painter);

        indicator->draw(indicatorPositionX,
                        indicatorPositionY,
                        indicatorPixmapSizeX,
                        indicatorHeight,
                        painter);
    }

    if ((int)pRange.width() > (int)vpSize.width()) {

        int indicatorPixmapSizeY = indicator->pixmap()->height();
        int railPixmapSizeY = rail->pixmap()->height();
        int indicatorWidth = qMax(style()->minIndicatorSize(), int((vpSize.width()/pRange.width())*size().width()));
        int indicatorPositionX = (pPos.x()/pRange.width())*size().width();

        if (indicatorPositionX + indicatorWidth > size().width()) {
            indicatorWidth = size().width() - indicatorPositionX;
        }

        if (indicatorPositionX < 0) {
            indicatorWidth += indicatorPositionX;
            indicatorPositionX = 0;
        }

        rail->draw( 0.0,
                    size().height() - railPixmapSizeY,
                    size().width(),
                    (qreal)railPixmapSizeY,
                    painter);

        indicator->draw((qreal)indicatorPositionX,
                        size().height() - indicatorPixmapSizeY,
                        (qreal)indicatorWidth,
                        (qreal)indicatorPixmapSizeY,
                        painter);
    }
}

void MPositionIndicatorView::updateData(const QList<const char *>& modifications)
{
    Q_D(MPositionIndicatorView);

    MWidgetView::updateData(modifications);

    if (d->onDisplay) {
        resetHideTimer();
    }
    update();
}

void MPositionIndicatorView::setupModel()
{
    Q_D(MPositionIndicatorView);

    MWidgetView::setupModel();

    if (d->onDisplay) {
        resetHideTimer();
    }
    update();
}

void MPositionIndicatorView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
    MWidgetView::resizeEvent(event);
    update();
}

void MPositionIndicatorView::changeEvent(QEvent *event)
{
    Q_D(MPositionIndicatorView);

    MWidgetView::changeEvent(event);

    if (event->type() == QEvent::EnabledChange) {
        if (d->controller->isEnabled()) {
            d->controller->setVisible(true);
        } else {
            d->controller->setVisible(false);
        }
    }
}

void MPositionIndicatorView::hide()
{
    Q_D(MPositionIndicatorView);
    d->visible = false;
    d->fadeAnimation->stop();
    d->fadeAnimation->setEndValue(0.0f);
    d->fadeAnimation->start();
    update();
}

void MPositionIndicatorView::resetHideTimer()
{
    Q_D(MPositionIndicatorView);
    if (!d->visible) {
        d->fadeAnimation->stop();
        d->fadeAnimation->setEndValue(1.0f);
        d->fadeAnimation->start();
        d->visible = true;
    }
    d->hideTimer->stop();
    if (!d->isInSwitcher()) {
        d->hideTimer->start(style()->hideTimeout());
    }
}

M_REGISTER_VIEW_NEW(MPositionIndicatorView, MPositionIndicator)

#include "moc_mpositionindicatorview.cpp"
<commit_msg>Fixes: NB#218298 - MPositionIndicator does not momentarily appear after it has been enabled<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mpositionindicatorview.h"
#include "mpositionindicatorview_p.h"
#include "qapplication.h"

#include <QString>
#include <QTimer>
#include <QStyleOptionGraphicsItem>
#include <QPropertyAnimation>

#include "mtheme.h"
#include "mviewcreator.h"
#include "mpositionindicator.h"
#include "mscalableimage.h"

MPositionIndicatorViewPrivate::MPositionIndicatorViewPrivate()
    : controller(0),
      hideTimer(new QTimer()),
      visible(false),
      onDisplay(false)
{
}

MPositionIndicatorViewPrivate::~MPositionIndicatorViewPrivate()
{
    delete this->hideTimer;
}

void MPositionIndicatorViewPrivate::init(MPositionIndicator *controller)
{
    Q_Q(MPositionIndicatorView);

    this->controller = controller;
    hideTimer->setSingleShot(true);
    fadeAnimation = new QPropertyAnimation(controller, "opacity", q);

    q->connect(hideTimer, SIGNAL(timeout()), SLOT(hide()));
    q->connect(controller, SIGNAL(displayEntered()), SLOT(_q_displayEntered()));
    q->connect(controller, SIGNAL(displayExited()), SLOT(_q_displayExited()));
}

bool MPositionIndicatorViewPrivate::isInSwitcher() const
{
    bool isInSwitcher = false;
    if (controller->scene() && !controller->scene()->views().isEmpty()) {
        MWindow* win = qobject_cast<MWindow*>(controller->scene()->views().at(0));
        if (win) {
            isInSwitcher = win->isInSwitcher();
        }
    }
    return isInSwitcher;
}

void MPositionIndicatorViewPrivate::_q_displayEntered()
{
    Q_Q(MPositionIndicatorView);

    onDisplay = true;
    if (!isInSwitcher()) {
        hideTimer->start(q->style()->hideTimeout());
    }
}

void MPositionIndicatorViewPrivate::_q_displayExited()
{
    Q_Q(MPositionIndicatorView);

    /* stop everything and keep indicator visible for next use */
    onDisplay = false;
    hideTimer->stop();
    fadeAnimation->stop();
    controller->setProperty("opacity", 1.0f);
    visible = true;
    q->update();
}

MPositionIndicatorView::MPositionIndicatorView(MPositionIndicator *controller) :
    MWidgetView(* new MPositionIndicatorViewPrivate, controller)
{
    Q_D(MPositionIndicatorView);
    d->init(controller);
}

MPositionIndicatorView::~MPositionIndicatorView()
{
    Q_D(MPositionIndicatorView);
    d->controller = 0;
}

void MPositionIndicatorView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    Q_UNUSED(painter);
    Q_UNUSED(option);
}

void MPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    Q_UNUSED(option);
    Q_D(const MPositionIndicatorView);

    if (d->isInSwitcher()) {
        return;
    }

    QSizeF  vpSize = model()->viewportSize();
    QRectF  pRange = model()->range().adjusted(0, 0, vpSize.width(), vpSize.height());
    QPointF pPos   = model()->position();

    const MScalableImage *indicator = style()->indicatorImage();
    const MScalableImage *rail = style()->backgroundImage();

    if ((int)pRange.height() > (int)vpSize.height()) {

        int indicatorPixmapSizeX = indicator->pixmap()->width();
        int railPixmapSizeX = rail->pixmap()->width();

        int indicatorHeight = qMax(style()->minIndicatorSize(), int((vpSize.height()/pRange.height())*size().height()));
        int indicatorPositionY = (pPos.y()/pRange.height())*size().height();

        if (indicatorPositionY + indicatorHeight > size().height()) {
            indicatorHeight = size().height() - indicatorPositionY;
        }

        if (indicatorPositionY < 0) {
            indicatorHeight += indicatorPositionY;
            indicatorPositionY = 0;
        }

        int railPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - railPixmapSizeX);
        int indicatorPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - indicatorPixmapSizeX);

        rail->draw((qreal)railPositionX,
                    0.0,
                    (qreal)railPixmapSizeX,
                    size().height(),
                    painter);

        indicator->draw(indicatorPositionX,
                        indicatorPositionY,
                        indicatorPixmapSizeX,
                        indicatorHeight,
                        painter);
    }

    if ((int)pRange.width() > (int)vpSize.width()) {

        int indicatorPixmapSizeY = indicator->pixmap()->height();
        int railPixmapSizeY = rail->pixmap()->height();
        int indicatorWidth = qMax(style()->minIndicatorSize(), int((vpSize.width()/pRange.width())*size().width()));
        int indicatorPositionX = (pPos.x()/pRange.width())*size().width();

        if (indicatorPositionX + indicatorWidth > size().width()) {
            indicatorWidth = size().width() - indicatorPositionX;
        }

        if (indicatorPositionX < 0) {
            indicatorWidth += indicatorPositionX;
            indicatorPositionX = 0;
        }

        rail->draw( 0.0,
                    size().height() - railPixmapSizeY,
                    size().width(),
                    (qreal)railPixmapSizeY,
                    painter);

        indicator->draw((qreal)indicatorPositionX,
                        size().height() - indicatorPixmapSizeY,
                        (qreal)indicatorWidth,
                        (qreal)indicatorPixmapSizeY,
                        painter);
    }
}

void MPositionIndicatorView::updateData(const QList<const char *>& modifications)
{
    Q_D(MPositionIndicatorView);

    MWidgetView::updateData(modifications);

    if (d->onDisplay) {
        resetHideTimer();
    }
    update();
}

void MPositionIndicatorView::setupModel()
{
    Q_D(MPositionIndicatorView);

    MWidgetView::setupModel();

    if (d->onDisplay) {
        resetHideTimer();
    }
    update();
}

void MPositionIndicatorView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
    MWidgetView::resizeEvent(event);
    update();
}

void MPositionIndicatorView::changeEvent(QEvent *event)
{
    Q_D(MPositionIndicatorView);

    MWidgetView::changeEvent(event);

    if (event->type() == QEvent::EnabledChange) {
        if (d->controller->isEnabled()) {
            resetHideTimer();
            d->controller->setVisible(true);
        } else {
            d->controller->setVisible(false);
        }
    }
}

void MPositionIndicatorView::hide()
{
    Q_D(MPositionIndicatorView);
    d->visible = false;
    d->fadeAnimation->stop();
    d->fadeAnimation->setEndValue(0.0f);
    d->fadeAnimation->start();
    update();
}

void MPositionIndicatorView::resetHideTimer()
{
    Q_D(MPositionIndicatorView);
    if (!d->visible) {
        d->fadeAnimation->stop();
        d->fadeAnimation->setEndValue(1.0f);
        d->fadeAnimation->start();
        d->visible = true;
    }
    d->hideTimer->stop();
    if (!d->isInSwitcher()) {
        d->hideTimer->start(style()->hideTimeout());
    }
}

M_REGISTER_VIEW_NEW(MPositionIndicatorView, MPositionIndicator)

#include "moc_mpositionindicatorview.cpp"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: spritecanvasbase.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 14:36:31 $
 *
 *  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 INCLUDED_CANVAS_SPRITECANVASBASE_HXX
#define INCLUDED_CANVAS_SPRITECANVASBASE_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _COM_SUN_STAR_RENDERING_XSPRITECANVAS_HPP_
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_INTERPOLATIONMODE_HPP_
#include <com/sun/star/rendering/InterpolationMode.hpp>
#endif

#ifndef INCLUDED_CANVAS_INTEGERBITMAPBASE_HXX
#include <canvas/base/integerbitmapbase.hxx>
#endif
#ifndef INCLUDED_CANVAS_SPRITEREDRAWMANAGER_HXX
#include <canvas/spriteredrawmanager.hxx>
#endif

namespace canvas
{
    /** Helper template to handle XIntegerBitmap method forwarding to
        BitmapCanvasHelper

        Use this helper to handle the XIntegerBitmap part of your
        implementation.

        @tpl Base
        Base class to use, most probably one of the
        WeakComponentImplHelperN templates with the appropriate
        interfaces. At least XSpriteCanvas and SpriteSurface should be
        among them (why else would you use this template, then?). Base
        class must have an Base( const Mutex& ) constructor (like the
        WeakComponentImplHelperN templates have).

        @tpl CanvasHelper
        Canvas helper implementation for the backend in question

        @tpl Mutex
        Lock strategy to use. Defaults to using the
        OBaseMutex-provided lock.  Everytime one of the methods is
        entered, an object of type Mutex is created with m_aMutex as
        the sole parameter, and destroyed again when the method scope
        is left.

        @tpl UnambiguousBase
        Optional unambiguous base class for XInterface of Base. It's
        sometimes necessary to specify this parameter, e.g. if Base
        derives from multiple UNO interface (were each provides its
        own version of XInterface, making the conversion ambiguous)

        @see CanvasBase for further contractual requirements towards
        the CanvasHelper type, and some examples.
     */
    template< class Base,
              class CanvasHelper,
              class Mutex=::osl::MutexGuard,
              class UnambiguousBase=::com::sun::star::uno::XInterface > class SpriteCanvasBase :
        public IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase >
    {
    public:
        typedef IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase > BaseType;
        typedef ::rtl::Reference< SpriteCanvasBase >                            Reference;

        SpriteCanvasBase() :
            maRedrawManager()
        {
        }

#if defined __SUNPRO_CC
        using Base::disposing;
#endif
        virtual void SAL_CALL disposing()
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.disposing();

            // pass on to base class
            BaseType::disposing();
        }

        // XSpriteCanvas
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromAnimation( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimation >& animation ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifyArgs(animation,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createSpriteFromAnimation(animation);
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromBitmaps( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap > >& animationBitmaps,
                                                                                sal_Int8                                                                                interpolationMode ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::rendering::VolatileContentDestroyedException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifyArgs(animationBitmaps,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));
            tools::verifyRange( interpolationMode,
                                ::com::sun::star::rendering::InterpolationMode::NEAREST_NEIGHBOR,
                                ::com::sun::star::rendering::InterpolationMode::BEZIERSPLINE4 );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createSpriteFromBitmaps(animationBitmaps, interpolationMode);
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCustomSprite > SAL_CALL createCustomSprite( const ::com::sun::star::geometry::RealSize2D& spriteSize ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifySpriteSize(spriteSize,
                                    BOOST_CURRENT_FUNCTION,
                                    static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createCustomSprite(spriteSize);
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite > SAL_CALL createClonedSprite( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite >& original ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifyArgs(original,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createClonedSprite(original);
        }

        // SpriteSurface
        virtual void showSprite( const Sprite::Reference& rSprite )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.showSprite( rSprite );
        }

        virtual void hideSprite( const Sprite::Reference& rSprite )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.hideSprite( rSprite );
        }

        virtual void moveSprite( const Sprite::Reference&       rSprite,
                                 const ::basegfx::B2DPoint&     rOldPos,
                                 const ::basegfx::B2DPoint&     rNewPos,
                                 const ::basegfx::B2DVector&    rSpriteSize )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.moveSprite( rSprite, rOldPos, rNewPos, rSpriteSize );
        }

        virtual void updateSprite( const Sprite::Reference&     rSprite,
                                   const ::basegfx::B2DPoint&   rPos,
                                   const ::basegfx::B2DRange&   rUpdateArea )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.updateSprite( rSprite, rPos, rUpdateArea );
        }

    protected:
        SpriteRedrawManager maRedrawManager;
    };
}

#endif /* INCLUDED_CANVAS_SPRITECANVASBASE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008/04/01 15:03:03 thb 1.3.80.3: #i85898# Stripping all external header guards 2008/04/01 10:49:25 thb 1.3.80.2: #i85898# Stripping all external header guards 2008/03/28 16:34:53 rt 1.3.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: spritecanvasbase.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_CANVAS_SPRITECANVASBASE_HXX
#define INCLUDED_CANVAS_SPRITECANVASBASE_HXX

#include <rtl/ref.hxx>
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <com/sun/star/rendering/InterpolationMode.hpp>
#include <canvas/base/integerbitmapbase.hxx>
#include <canvas/spriteredrawmanager.hxx>

namespace canvas
{
    /** Helper template to handle XIntegerBitmap method forwarding to
        BitmapCanvasHelper

        Use this helper to handle the XIntegerBitmap part of your
        implementation.

        @tpl Base
        Base class to use, most probably one of the
        WeakComponentImplHelperN templates with the appropriate
        interfaces. At least XSpriteCanvas and SpriteSurface should be
        among them (why else would you use this template, then?). Base
        class must have an Base( const Mutex& ) constructor (like the
        WeakComponentImplHelperN templates have).

        @tpl CanvasHelper
        Canvas helper implementation for the backend in question

        @tpl Mutex
        Lock strategy to use. Defaults to using the
        OBaseMutex-provided lock.  Everytime one of the methods is
        entered, an object of type Mutex is created with m_aMutex as
        the sole parameter, and destroyed again when the method scope
        is left.

        @tpl UnambiguousBase
        Optional unambiguous base class for XInterface of Base. It's
        sometimes necessary to specify this parameter, e.g. if Base
        derives from multiple UNO interface (were each provides its
        own version of XInterface, making the conversion ambiguous)

        @see CanvasBase for further contractual requirements towards
        the CanvasHelper type, and some examples.
     */
    template< class Base,
              class CanvasHelper,
              class Mutex=::osl::MutexGuard,
              class UnambiguousBase=::com::sun::star::uno::XInterface > class SpriteCanvasBase :
        public IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase >
    {
    public:
        typedef IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase > BaseType;
        typedef ::rtl::Reference< SpriteCanvasBase >                            Reference;

        SpriteCanvasBase() :
            maRedrawManager()
        {
        }

#if defined __SUNPRO_CC
        using Base::disposing;
#endif
        virtual void SAL_CALL disposing()
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.disposing();

            // pass on to base class
            BaseType::disposing();
        }

        // XSpriteCanvas
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromAnimation( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimation >& animation ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifyArgs(animation,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createSpriteFromAnimation(animation);
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromBitmaps( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap > >& animationBitmaps,
                                                                                sal_Int8                                                                                interpolationMode ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::rendering::VolatileContentDestroyedException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifyArgs(animationBitmaps,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));
            tools::verifyRange( interpolationMode,
                                ::com::sun::star::rendering::InterpolationMode::NEAREST_NEIGHBOR,
                                ::com::sun::star::rendering::InterpolationMode::BEZIERSPLINE4 );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createSpriteFromBitmaps(animationBitmaps, interpolationMode);
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCustomSprite > SAL_CALL createCustomSprite( const ::com::sun::star::geometry::RealSize2D& spriteSize ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifySpriteSize(spriteSize,
                                    BOOST_CURRENT_FUNCTION,
                                    static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createCustomSprite(spriteSize);
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite > SAL_CALL createClonedSprite( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite >& original ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException)
        {
            tools::verifyArgs(original,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::maCanvasHelper.createClonedSprite(original);
        }

        // SpriteSurface
        virtual void showSprite( const Sprite::Reference& rSprite )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.showSprite( rSprite );
        }

        virtual void hideSprite( const Sprite::Reference& rSprite )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.hideSprite( rSprite );
        }

        virtual void moveSprite( const Sprite::Reference&       rSprite,
                                 const ::basegfx::B2DPoint&     rOldPos,
                                 const ::basegfx::B2DPoint&     rNewPos,
                                 const ::basegfx::B2DVector&    rSpriteSize )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.moveSprite( rSprite, rOldPos, rNewPos, rSpriteSize );
        }

        virtual void updateSprite( const Sprite::Reference&     rSprite,
                                   const ::basegfx::B2DPoint&   rPos,
                                   const ::basegfx::B2DRange&   rUpdateArea )
        {
            OSL_ASSERT( rSprite.is() );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maRedrawManager.updateSprite( rSprite, rPos, rUpdateArea );
        }

    protected:
        SpriteRedrawManager maRedrawManager;
    };
}

#endif /* INCLUDED_CANVAS_SPRITECANVASBASE_HXX */
<|endoftext|>