<commit_before>#include "AIHandler.h"
#define SUCCESS 1
#define FAIL 0

AIHandler::AIHandler(){}
AIHandler::~AIHandler(){}
int AIHandler::Shutdown()
{
	for (int i = 0; i < this->m_nrOfAIComponents; i++)
	{
		delete this->m_AIComponents.at(i);
	}

	return SUCCESS;
}

int AIHandler::Initialize(int max)
{
	this->m_nrOfAIComponents = 0;

	if (max < 0)
	{
		// temp
		m_maxOfAIComponents = 3;
		//return FAIL;
	}

	this->m_maxOfAIComponents = max;

	for (int i = 0; i < this->m_maxOfAIComponents; i++)
	{
		m_AIComponents.push_back(CreateAIComponent(i));
	}

	return SUCCESS;
}
int AIHandler::Update(float deltaTime)
{
	for (int i = 0; i < this->m_nrOfAIComponents; i++)
	{
		if (this->m_AIComponents.at(i)->m_active && this->m_AIComponents.at(i)->m_triggered)
		{
			// AIComponent logic/behavior, movement of e.g. platforms
			DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->m_position;
			int currentWaypoint = this->m_AIComponents.at(i)->m_currentWaypoint;
			int nrOfWaypoint = this->m_AIComponents.at(i)->m_nrOfWaypoint;
			int pattern = this->m_AIComponents.at(i)->m_pattern;
			int time = this->m_AIComponents.at(i)->m_time;
			int direction = this->m_AIComponents.at(i)->m_direction;

			if (pattern == 1)
			{
				if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint)
				{
					if (direction == 0)
						this->m_AIComponents.at(i)->m_direction = 1;
					else
						this->m_AIComponents.at(i)->m_direction = 0;
				}
			}
			else if (pattern == 3)
			{
				//TODO Round-trip pattern
			}
			else
			{
				//Identical to pattern 2 (Circular)
				if (direction == 0)
				{
					if (WaypointApprox(i))
					{
						currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
						this->m_AIComponents.at(i)->m_nextWaypoint++;
						if (this->m_AIComponents.at(i)->m_nextWaypoint >= this->m_AIComponents.at(i)->m_nrOfWaypoint)
							this->m_AIComponents.at(i)->m_nextWaypoint = 0;
					}
				}
				else
				{
					if (WaypointApprox(i))
					{
						currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
						this->m_AIComponents.at(i)->m_nextWaypoint--;
						if (this->m_AIComponents.at(i)->m_nextWaypoint <= this->m_AIComponents.at(i)->m_nrOfWaypoint)
							this->m_AIComponents.at(i)->m_nextWaypoint = nrOfWaypoint;
					}
				}
			}

			//Update position
			DirectX::XMVECTOR v;
			v = DirectX::XMVectorSubtract(
				this->m_AIComponents.at(i)->m_waypoints[this->m_AIComponents.at(i)->m_nextWaypoint],
				pos);

			DirectX::XMVECTOR m;
			m = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), 10); //Speed?
			m = DirectX::XMVectorScale(m, deltaTime);

			this->m_AIComponents.at(i)->m_position = DirectX::XMVectorMultiply(m, this->m_AIComponents.at(i)->m_position);
		}
	}

	return SUCCESS;
}

void AIHandler::SetComponentActive(int compID)
{
	this->m_AIComponents.at(compID)->m_active = true;
}

void AIHandler::SetComponentFalse(int compID)
{
	this->m_AIComponents.at(compID)->m_active = false;
}

void AIHandler::SetEntityID(int compID, int entityID)
{
	this->m_AIComponents.at(compID)->m_entityID = entityID;
}

void AIHandler::SetTriggered(int compID, bool triggered)
{
	this->m_AIComponents.at(compID)->m_triggered = triggered;
}

void AIHandler::SetTime(int compID, int time)
{
	this->m_AIComponents.at(compID)->m_time = time;
}

void AIHandler::SetSpeed(int compID, int speed)
{
	this->m_AIComponents.at(compID)->m_speed = speed;
}

void AIHandler::SetDirection(int compID, int direction)
{
	this->m_AIComponents.at(compID)->m_direction = direction;
}

void AIHandler::SetCurrentWaypoint(int compID, int currentWaypoint)
{
	this->m_AIComponents.at(compID)->m_currentWaypoint = currentWaypoint;
}

void AIHandler::SetPattern(int compID, int pattern)
{
	this->m_AIComponents.at(compID)->m_pattern = pattern;
}

void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[])
{
	for (int i = 0; i < 8; i++)
	{
		this->m_AIComponents.at(compID)->m_waypoints[i] = waypoints[i];
		this->m_AIComponents.at(compID)->m_nrOfWaypoint++;
	}
}

int AIHandler::GetNrOfAIComponents() const
{
	return this->m_nrOfAIComponents;
}

DirectX::XMVECTOR AIHandler::GetPosition(int compID) const
{
	return this->m_AIComponents.at(compID)->m_position;
}

AIComponent* AIHandler::CreateAIComponent(int entityID)
{
	AIComponent* newComponent = nullptr;
	newComponent = new AIComponent;

	newComponent->m_active = 0;
	newComponent->m_entityID = entityID;
	newComponent->m_position = DirectX::XMVECTOR();

	newComponent->m_triggered = false;
	newComponent->m_time = 0;
	newComponent->m_speed = 0;
	newComponent->m_direction = 0;
	newComponent->m_currentWaypoint = 0;
	newComponent->m_nrOfWaypoint = 0;

	for (int i = 0; i < 8; i++) {
		newComponent->m_waypoints[i] = DirectX::XMVECTOR();
		newComponent->m_nrOfWaypoint++;
	}

	return newComponent;
}

bool AIHandler::WaypointApprox(int compID)
{
	using namespace DirectX;

	int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
	int current = this->m_AIComponents.at(compID)->m_nextWaypoint;

	DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->m_waypoints[next]
		,this->m_AIComponents.at(compID)->m_waypoints[current]);

	float length = VectorLength(v);

	if (length > 0.1)
	{
		return true;
	}

	return false;
}

int AIHandler::GetNextWaypoint(int compID, int pattern)
{
	/*const int ARR_LEN = 10;

	int arr[ARR_LEN] = { 0,1,2,3,4,5,6,7,8,9 };

	for (int i = 0; i < ARR_LEN * 2; ++i)
	cout << arr[i % ARR_LEN] << " ";*/

	int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
	int current = this->m_AIComponents.at(compID)->m_nextWaypoint;

	if (pattern == 1)
	{
		//TODO Linear pattern next waypoint logic
	}
	else
	{
		//if (this->m_AIComponents.at(compID)->m_nrOfWaypoint)
	}

	if (next == current)
	{

	}

	this->m_AIComponents.at(compID)->m_currentWaypoint;
	this->m_AIComponents.at(compID)->m_direction;

	//this->m_AIComponents.at(compID)->m_waypoints[i];

	return 0;
}

float AIHandler::VectorLength(DirectX::XMVECTOR v)
{
	float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v));
	return length;
}
<commit_msg>UPDATE Cleanup and initializing some new variables<commit_after>#include "AIHandler.h"
#define SUCCESS 1
#define FAIL 0

AIHandler::AIHandler(){}
AIHandler::~AIHandler(){}
int AIHandler::Shutdown()
{
	for (int i = 0; i < this->m_nrOfAIComponents; i++)
	{
		delete this->m_AIComponents.at(i);
	}

	return SUCCESS;
}

int AIHandler::Initialize(int max)
{
	this->m_nrOfAIComponents = 0;

	if (max < 0)
	{
		// temp
		m_maxOfAIComponents = 3;
		//return FAIL;
	}

	this->m_maxOfAIComponents = max;

	for (int i = 0; i < this->m_maxOfAIComponents; i++)
	{
		m_AIComponents.push_back(CreateAIComponent(i));
	}

	return SUCCESS;
}
int AIHandler::Update(float deltaTime)
{
	for (int i = 0; i < this->m_nrOfAIComponents; i++)
	{
		if (this->m_AIComponents.at(i)->m_active && this->m_AIComponents.at(i)->m_triggered)
		{
			// AIComponent logic/behavior, movement of e.g. platforms
			DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->m_position;
			int currentWaypoint = this->m_AIComponents.at(i)->m_currentWaypoint;
			int nrOfWaypoint = this->m_AIComponents.at(i)->m_nrOfWaypoint;
			int pattern = this->m_AIComponents.at(i)->m_pattern;
			int time = this->m_AIComponents.at(i)->m_time;
			int direction = this->m_AIComponents.at(i)->m_direction;

			if (pattern == 1)
			{
				if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint)
				{
					if (direction == 0)
						this->m_AIComponents.at(i)->m_direction = 1;
					else
						this->m_AIComponents.at(i)->m_direction = 0;
				}
			}
			else if (pattern == 3)
			{
				//TODO Round-trip pattern
			}
			else
			{
				//Identical to pattern 2 (Circular)
				if (direction == 0)
				{
					if (WaypointApprox(i))
					{
						currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
						this->m_AIComponents.at(i)->m_nextWaypoint++;
						if (this->m_AIComponents.at(i)->m_nextWaypoint >= this->m_AIComponents.at(i)->m_nrOfWaypoint)
							this->m_AIComponents.at(i)->m_nextWaypoint = 0;
					}
				}
				else
				{
					if (WaypointApprox(i))
					{
						currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
						this->m_AIComponents.at(i)->m_nextWaypoint--;
						if (this->m_AIComponents.at(i)->m_nextWaypoint <= this->m_AIComponents.at(i)->m_nrOfWaypoint)
							this->m_AIComponents.at(i)->m_nextWaypoint = nrOfWaypoint;
					}
				}
			}

			//Update position
			DirectX::XMVECTOR v;
			v = DirectX::XMVectorSubtract(
				this->m_AIComponents.at(i)->m_waypoints[this->m_AIComponents.at(i)->m_nextWaypoint],
				pos);

			DirectX::XMVECTOR m;
			m = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), 10); //Speed?
			m = DirectX::XMVectorScale(m, deltaTime);

			this->m_AIComponents.at(i)->m_position = DirectX::XMVectorMultiply(m, this->m_AIComponents.at(i)->m_position);
		}
	}

	return SUCCESS;
}

void AIHandler::SetComponentActive(int compID)
{
	this->m_AIComponents.at(compID)->m_active = true;
}

void AIHandler::SetComponentFalse(int compID)
{
	this->m_AIComponents.at(compID)->m_active = false;
}

void AIHandler::SetEntityID(int compID, int entityID)
{
	this->m_AIComponents.at(compID)->m_entityID = entityID;
}

void AIHandler::SetTriggered(int compID, bool triggered)
{
	this->m_AIComponents.at(compID)->m_triggered = triggered;
}

void AIHandler::SetTime(int compID, int time)
{
	this->m_AIComponents.at(compID)->m_time = time;
}

void AIHandler::SetSpeed(int compID, int speed)
{
	this->m_AIComponents.at(compID)->m_speed = speed;
}

void AIHandler::SetDirection(int compID, int direction)
{
	this->m_AIComponents.at(compID)->m_direction = direction;
}

void AIHandler::SetCurrentWaypoint(int compID, int currentWaypoint)
{
	this->m_AIComponents.at(compID)->m_currentWaypoint = currentWaypoint;
}

void AIHandler::SetPattern(int compID, int pattern)
{
	this->m_AIComponents.at(compID)->m_pattern = pattern;
}

void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[])
{
	for (int i = 0; i < 8; i++)
	{
		this->m_AIComponents.at(compID)->m_waypoints[i] = waypoints[i];
		this->m_AIComponents.at(compID)->m_nrOfWaypoint++;
	}
}

int AIHandler::GetNrOfAIComponents() const
{
	return this->m_nrOfAIComponents;
}

DirectX::XMVECTOR AIHandler::GetPosition(int compID) const
{
	return this->m_AIComponents.at(compID)->m_position;
}

AIComponent* AIHandler::CreateAIComponent(int entityID)
{
	AIComponent* newComponent = nullptr;
	newComponent = new AIComponent;

	newComponent->m_active = 0;
	newComponent->m_entityID = entityID;
	newComponent->m_position = DirectX::XMVECTOR();

	newComponent->m_triggered = false;
	newComponent->m_pattern = 0;
	newComponent->m_time = 0;
	newComponent->m_speed = 0;
	newComponent->m_direction = 0;
	newComponent->m_nextWaypoint = 0;
	newComponent->m_currentWaypoint = 0;
	newComponent->m_nrOfWaypoint = 0;

	for (int i = 0; i < 8; i++) {
		newComponent->m_waypoints[i] = DirectX::XMVECTOR();
		newComponent->m_nrOfWaypoint++;
	}

	return newComponent;
}

bool AIHandler::WaypointApprox(int compID)
{
	using namespace DirectX;

	int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
	int current = this->m_AIComponents.at(compID)->m_nextWaypoint;

	DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->m_waypoints[next]
		,this->m_AIComponents.at(compID)->m_waypoints[current]);

	float length = VectorLength(v);

	if (length > 0.1)
	{
		return true;
	}

	return false;
}

int AIHandler::GetNextWaypoint(int compID, int pattern)
{
	int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
	int current = this->m_AIComponents.at(compID)->m_nextWaypoint;

	if (pattern == 1)
	{
		//TODO Linear pattern next waypoint logic
	}
	else
	{

	}

	if (next == current)
	{

	}

	this->m_AIComponents.at(compID)->m_currentWaypoint;
	this->m_AIComponents.at(compID)->m_direction;

	return 0;
}

float AIHandler::VectorLength(DirectX::XMVECTOR v)
{
	float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v));
	return length;
}
<|endoftext|>


<commit_before>	#include <stdio.h>
    #include "log.h"

    int main(void)
    {
		Logger::GetLogger()->log_open("mycat");
		int i = 10;
		float j = 23.45;
		Logger::GetLogger()->Info("info,%d,%f", i,j);
		Logger::GetLogger()->Error("error");
		Logger::GetLogger()->Warning("warn");
		Logger::GetLogger()->log_close();
        return 0;
    }
<commit_msg>git_rm<commit_after><|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-----------------------------------------------------------------
//   Implementation of the derived class for track residuals
//   based on linear chi2 minimization (in approximation of
//   small alignment angles and translations)
//
//-----------------------------------------------------------------

#include <TMath.h>
#include <TGeoMatrix.h>

#include "AliLog.h"
#include "AliAlignObj.h"
#include "AliTrackPointArray.h"
#include "AliTrackResidualsFast.h"

#include <TMatrixDSym.h>
#include <TMatrixDSymEigen.h>

ClassImp(AliTrackResidualsFast)

//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast():
  AliTrackResiduals(),
  fSumR(0)
{
  // Default constructor
  for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}

//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(Int_t ntracks):
  AliTrackResiduals(ntracks),
  fSumR(0)
{
  // Constructor
  for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}

//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(const AliTrackResidualsFast &res):
  AliTrackResiduals(res),
  fSumR(res.fSumR)
{
  // Copy constructor
  for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
}

//______________________________________________________________________________
AliTrackResidualsFast &AliTrackResidualsFast::operator= (const AliTrackResidualsFast& res)
{
  // Assignment operator
 ((AliTrackResiduals *)this)->operator=(res);
 for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
 fSumR = res.fSumR;

 return *this;
}

//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Minimize()
{
  // Implementation of fast linear Chi2
  // based minimization of track residuals sum

  //  if(fBFixed[0]||fBFixed[1]||fBFixed[2]||fBFixed[3]||fBFixed[4]||fBFixed[5])
  //    AliError("Cannot yet fix parameters in this minimizer");

  for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
  fSumR = 0;

  AliTrackPoint p1,p2;

  for (Int_t itrack = 0; itrack < fLast; itrack++) {
    if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
    for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
      fVolArray[itrack]->GetPoint(p1,ipoint);
      fTrackArray[itrack]->GetPoint(p2,ipoint);
      AddPoints(p1,p2);
    }
  }

  return Update();

  // debug info
//   Float_t chi2 = 0;
//   for (Int_t itrack = 0; itrack < fLast; itrack++) {
//     if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
//     for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
//       fVolArray[itrack]->GetPoint(p1,ipoint);
//       fAlignObj->Transform(p1);
//       fTrackArray[itrack]->GetPoint(p2,ipoint);
//       Float_t residual = p2.GetResidual(p1,kFALSE);
//       chi2 += residual;
//     }
//   }
//   printf("Final chi2 = %f\n",chi2);
}

//______________________________________________________________________________
void AliTrackResidualsFast::AddPoints(AliTrackPoint &p, AliTrackPoint &pprime)
{
  // Update the sums used for
  // the linear chi2 minimization
  Float_t xyz[3],xyzp[3];
  Float_t cov[6],covp[6];
  p.GetXYZ(xyz,cov); pprime.GetXYZ(xyzp,covp);
  TMatrixDSym mcov(3);
  mcov(0,0) = cov[0]; mcov(0,1) = cov[1]; mcov(0,2) = cov[2];
  mcov(1,0) = cov[1]; mcov(1,1) = cov[3]; mcov(1,2) = cov[4];
  mcov(2,0) = cov[2]; mcov(2,1) = cov[4]; mcov(2,2) = cov[5];
  TMatrixDSym mcovp(3);
  mcovp(0,0) = covp[0]; mcovp(0,1) = covp[1]; mcovp(0,2) = covp[2];
  mcovp(1,0) = covp[1]; mcovp(1,1) = covp[3]; mcovp(1,2) = covp[4];
  mcovp(2,0) = covp[2]; mcovp(2,1) = covp[4]; mcovp(2,2) = covp[5];
  TMatrixDSym msum = mcov + mcovp;

  msum.Invert();

  if (!msum.IsValid()) return;

  TMatrixD        sums(3,1);
  sums(0,0) = (xyzp[0]-xyz[0]);
  sums(1,0) = (xyzp[1]-xyz[1]);
  sums(2,0) = (xyzp[2]-xyz[2]);
  TMatrixD sumst = sums.T(); sums.T();

  TMatrixD        mf(3,6);
  mf(0,0) = 1;      mf(1,0) = 0;       mf(2,0) = 0;
  mf(0,1) = 0;      mf(1,1) = 1;       mf(2,1) = 0;
  mf(0,2) = 0;      mf(1,2) = 0;       mf(2,2) = 1;
  mf(0,3) = 0;      mf(1,3) = -xyz[2]; mf(2,3) = xyz[1];
  mf(0,4) = xyz[2]; mf(1,4) = 0;       mf(2,4) =-xyz[0];
  mf(0,5) =-xyz[1]; mf(1,5) = xyz[0];  mf(2,5) = 0;

  for(Int_t j=0;j<6;j++){
    if(fBFixed[j]==kTRUE){
      mf(0,j)=0.;mf(1,j)=0.;mf(2,j)=0.;
    }
  }

  TMatrixD        mft = mf.T(); mf.T();
  TMatrixD sums2 = mft * msum * sums;

  TMatrixD smatrix = mft * msum * mf;

  fSum[0] += smatrix(0,0);
  fSum[1] += smatrix(0,1);
  fSum[2] += smatrix(0,2);
  fSum[3] += smatrix(0,3);
  fSum[4] += smatrix(0,4);
  fSum[5] += smatrix(0,5);
  fSum[6] += smatrix(1,1);
  fSum[7] += smatrix(1,2);
  fSum[8] += smatrix(1,3);
  fSum[9] += smatrix(1,4);
  fSum[10]+= smatrix(1,5);
  fSum[11]+= smatrix(2,2);
  fSum[12]+= smatrix(2,3);
  fSum[13]+= smatrix(2,4);
  fSum[14]+= smatrix(2,5);
  fSum[15]+= smatrix(3,3);
  fSum[16]+= smatrix(3,4);
  fSum[17]+= smatrix(3,5);
  fSum[18]+= smatrix(4,4);
  fSum[19]+= smatrix(4,5);
  fSum[20]+= smatrix(5,5);
  fSum[21] += sums2(0,0);
  fSum[22] += sums2(1,0);
  fSum[23] += sums2(2,0);
  fSum[24] += sums2(3,0);
  fSum[25] += sums2(4,0);
  fSum[26] += sums2(5,0);

  TMatrixD  tmp = sumst * msum * sums;
  fSumR += tmp(0,0);

  fNdf += 3;
}

//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Update()
{
  // Find the alignment parameters
  // by using the already accumulated
  // sums
  TMatrixDSym     smatrix(6);
  TMatrixD        sums(1,6);

  smatrix(0,0) = fSum[0];
  smatrix(0,1) = smatrix(1,0) = fSum[1];
  smatrix(0,2) = smatrix(2,0) = fSum[2];
  smatrix(0,3) = smatrix(3,0) = fSum[3];
  smatrix(0,4) = smatrix(4,0) = fSum[4];
  smatrix(0,5) = smatrix(5,0) = fSum[5];
  smatrix(1,1) = fSum[6];
  smatrix(1,2) = smatrix(2,1) = fSum[7];
  smatrix(1,3) = smatrix(3,1) = fSum[8];
  smatrix(1,4) = smatrix(4,1) = fSum[9];
  smatrix(1,5) = smatrix(5,1) = fSum[10];
  smatrix(2,2) = fSum[11];
  smatrix(2,3) = smatrix(3,2) = fSum[12];
  smatrix(2,4) = smatrix(4,2) = fSum[13];
  smatrix(2,5) = smatrix(5,2) = fSum[14];
  smatrix(3,3) = fSum[15];
  smatrix(3,4) = smatrix(4,3) = fSum[16];
  smatrix(3,5) = smatrix(5,3) = fSum[17];
  smatrix(4,4) = fSum[18];
  smatrix(4,5) = smatrix(5,4) = fSum[19];
  smatrix(5,5) = fSum[20];

  sums(0,0)    = fSum[21]; sums(0,1) = fSum[22]; sums(0,2) = fSum[23];
  sums(0,3)    = fSum[24]; sums(0,4) = fSum[25]; sums(0,5) = fSum[26];

  Int_t fixedparamat[6]={0,0,0,0,0,0};
  const Int_t unfixedparam=GetNFreeParam();
  Int_t position[6],last=0;//position is of size 6 but only unfiexedparam indeces will be used

  if(fBFixed[0]==kTRUE){
    fixedparamat[0]=1;
  }
  else {
    position[0]=0;
    last++;
  }

  for(Int_t j=1;j<6;j++){
    if(fBFixed[j]==kTRUE){
      fixedparamat[j]=fixedparamat[j-1]+1;
    }
    else {
      fixedparamat[j]=fixedparamat[j-1];
      position[last]=j;
      last++;
    }
  }

  TMatrixDSym smatrixRedu(unfixedparam);
  for(Int_t i=0;i<unfixedparam;i++){
    for(Int_t j=0;j<unfixedparam;j++){
      smatrixRedu(i,j)=smatrix(position[i],position[j]);
    }
  }

  //  smatrixRedu.Print();
  smatrixRedu.Invert();

  if (!smatrixRedu.IsValid()) {
    printf("Minimization Failed! \n");
    return kFALSE;
  }

  TMatrixDSym smatrixUp(6);
  for(Int_t i=0;i<6;i++){
    for(Int_t j=0;j<6;j++){
      if(fBFixed[i]==kTRUE||fBFixed[j]==kTRUE)smatrixUp(i,j)=0.;
      else smatrixUp(i,j)=smatrixRedu(i-fixedparamat[i],j-fixedparamat[j]);
    }
  }

  Double_t covmatrarray[21];

  for(Int_t i=0;i<6;i++){
      for(Int_t j=0;j<=i;j++){
	if(fBFixed[i]==kFALSE&&fBFixed[j]==kFALSE){
	  if(TMath::Abs(smatrixUp(i,j)/TMath::Sqrt(TMath::Abs(smatrixUp(i,i)*smatrixUp(j,j))))>1.01)printf("Too large Correlation number!\n");
	}
	covmatrarray[i*(i+1)/2+j]=smatrixUp(i,j);
      }
  }

  TMatrixD res = sums*smatrixUp;
  fAlignObj->SetPars(res(0,0),res(0,1),res(0,2),
		     TMath::RadToDeg()*res(0,3),
		     TMath::RadToDeg()*res(0,4),
		     TMath::RadToDeg()*res(0,5));

  fAlignObj->SetCorrMatrix(covmatrarray);
  TMatrixD  tmp = res*sums.T();
  fChi2 = fSumR - tmp(0,0);
  fNdf -= unfixedparam;

  return kTRUE;
}

<commit_msg>Coverity fix.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-----------------------------------------------------------------
//   Implementation of the derived class for track residuals
//   based on linear chi2 minimization (in approximation of
//   small alignment angles and translations)
//
//-----------------------------------------------------------------

#include <TMath.h>
#include <TGeoMatrix.h>

#include "AliLog.h"
#include "AliAlignObj.h"
#include "AliTrackPointArray.h"
#include "AliTrackResidualsFast.h"

#include <TMatrixDSym.h>
#include <TMatrixDSymEigen.h>

ClassImp(AliTrackResidualsFast)

//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast():
  AliTrackResiduals(),
  fSumR(0)
{
  // Default constructor
  for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}

//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(Int_t ntracks):
  AliTrackResiduals(ntracks),
  fSumR(0)
{
  // Constructor
  for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
}

//______________________________________________________________________________
AliTrackResidualsFast::AliTrackResidualsFast(const AliTrackResidualsFast &res):
  AliTrackResiduals(res),
  fSumR(res.fSumR)
{
  // Copy constructor
  for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
}

//______________________________________________________________________________
AliTrackResidualsFast &AliTrackResidualsFast::operator= (const AliTrackResidualsFast& res)
{
  // Assignment operator
 ((AliTrackResiduals *)this)->operator=(res);
 for (Int_t i = 0; i < 27; i++) fSum[i] = res.fSum[i];
 fSumR = res.fSumR;

 return *this;
}

//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Minimize()
{
  // Implementation of fast linear Chi2
  // based minimization of track residuals sum

  //  if(fBFixed[0]||fBFixed[1]||fBFixed[2]||fBFixed[3]||fBFixed[4]||fBFixed[5])
  //    AliError("Cannot yet fix parameters in this minimizer");

  for (Int_t i = 0; i < 27; i++) fSum[i] = 0;
  fSumR = 0;

  AliTrackPoint p1,p2;

  for (Int_t itrack = 0; itrack < fLast; itrack++) {
    if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
    for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
      fVolArray[itrack]->GetPoint(p1,ipoint);
      fTrackArray[itrack]->GetPoint(p2,ipoint);
      AddPoints(p1,p2);
    }
  }

  return Update();

  // debug info
//   Float_t chi2 = 0;
//   for (Int_t itrack = 0; itrack < fLast; itrack++) {
//     if (!fVolArray[itrack] || !fTrackArray[itrack]) continue;
//     for (Int_t ipoint = 0; ipoint < fVolArray[itrack]->GetNPoints(); ipoint++) {
//       fVolArray[itrack]->GetPoint(p1,ipoint);
//       fAlignObj->Transform(p1);
//       fTrackArray[itrack]->GetPoint(p2,ipoint);
//       Float_t residual = p2.GetResidual(p1,kFALSE);
//       chi2 += residual;
//     }
//   }
//   printf("Final chi2 = %f\n",chi2);
}

//______________________________________________________________________________
void AliTrackResidualsFast::AddPoints(AliTrackPoint &p, AliTrackPoint &pprime)
{
  // Update the sums used for
  // the linear chi2 minimization
  Float_t xyz[3],xyzp[3];
  Float_t cov[6],covp[6];
  p.GetXYZ(xyz,cov); pprime.GetXYZ(xyzp,covp);
  TMatrixDSym mcov(3);
  mcov(0,0) = cov[0]; mcov(0,1) = cov[1]; mcov(0,2) = cov[2];
  mcov(1,0) = cov[1]; mcov(1,1) = cov[3]; mcov(1,2) = cov[4];
  mcov(2,0) = cov[2]; mcov(2,1) = cov[4]; mcov(2,2) = cov[5];
  TMatrixDSym mcovp(3);
  mcovp(0,0) = covp[0]; mcovp(0,1) = covp[1]; mcovp(0,2) = covp[2];
  mcovp(1,0) = covp[1]; mcovp(1,1) = covp[3]; mcovp(1,2) = covp[4];
  mcovp(2,0) = covp[2]; mcovp(2,1) = covp[4]; mcovp(2,2) = covp[5];
  TMatrixDSym msum = mcov + mcovp;

  msum.Invert();

  if (!msum.IsValid()) return;

  TMatrixD        sums(3,1);
  sums(0,0) = (xyzp[0]-xyz[0]);
  sums(1,0) = (xyzp[1]-xyz[1]);
  sums(2,0) = (xyzp[2]-xyz[2]);
  TMatrixD sumst = sums.T(); sums.T();

  TMatrixD        mf(3,6);
  mf(0,0) = 1;      mf(1,0) = 0;       mf(2,0) = 0;
  mf(0,1) = 0;      mf(1,1) = 1;       mf(2,1) = 0;
  mf(0,2) = 0;      mf(1,2) = 0;       mf(2,2) = 1;
  mf(0,3) = 0;      mf(1,3) = -xyz[2]; mf(2,3) = xyz[1];
  mf(0,4) = xyz[2]; mf(1,4) = 0;       mf(2,4) =-xyz[0];
  mf(0,5) =-xyz[1]; mf(1,5) = xyz[0];  mf(2,5) = 0;

  for(Int_t j=0;j<6;j++){
    if(fBFixed[j]==kTRUE){
      mf(0,j)=0.;mf(1,j)=0.;mf(2,j)=0.;
    }
  }

  TMatrixD        mft = mf.T(); mf.T();
  TMatrixD sums2 = mft * msum * sums;

  TMatrixD smatrix = mft * msum * mf;

  fSum[0] += smatrix(0,0);
  fSum[1] += smatrix(0,1);
  fSum[2] += smatrix(0,2);
  fSum[3] += smatrix(0,3);
  fSum[4] += smatrix(0,4);
  fSum[5] += smatrix(0,5);
  fSum[6] += smatrix(1,1);
  fSum[7] += smatrix(1,2);
  fSum[8] += smatrix(1,3);
  fSum[9] += smatrix(1,4);
  fSum[10]+= smatrix(1,5);
  fSum[11]+= smatrix(2,2);
  fSum[12]+= smatrix(2,3);
  fSum[13]+= smatrix(2,4);
  fSum[14]+= smatrix(2,5);
  fSum[15]+= smatrix(3,3);
  fSum[16]+= smatrix(3,4);
  fSum[17]+= smatrix(3,5);
  fSum[18]+= smatrix(4,4);
  fSum[19]+= smatrix(4,5);
  fSum[20]+= smatrix(5,5);
  fSum[21] += sums2(0,0);
  fSum[22] += sums2(1,0);
  fSum[23] += sums2(2,0);
  fSum[24] += sums2(3,0);
  fSum[25] += sums2(4,0);
  fSum[26] += sums2(5,0);

  TMatrixD  tmp = sumst * msum * sums;
  fSumR += tmp(0,0);

  fNdf += 3;
}

//______________________________________________________________________________
Bool_t AliTrackResidualsFast::Update()
{
  // Find the alignment parameters
  // by using the already accumulated
  // sums
  TMatrixDSym     smatrix(6);
  TMatrixD        sums(1,6);

  smatrix(0,0) = fSum[0];
  smatrix(0,1) = smatrix(1,0) = fSum[1];
  smatrix(0,2) = smatrix(2,0) = fSum[2];
  smatrix(0,3) = smatrix(3,0) = fSum[3];
  smatrix(0,4) = smatrix(4,0) = fSum[4];
  smatrix(0,5) = smatrix(5,0) = fSum[5];
  smatrix(1,1) = fSum[6];
  smatrix(1,2) = smatrix(2,1) = fSum[7];
  smatrix(1,3) = smatrix(3,1) = fSum[8];
  smatrix(1,4) = smatrix(4,1) = fSum[9];
  smatrix(1,5) = smatrix(5,1) = fSum[10];
  smatrix(2,2) = fSum[11];
  smatrix(2,3) = smatrix(3,2) = fSum[12];
  smatrix(2,4) = smatrix(4,2) = fSum[13];
  smatrix(2,5) = smatrix(5,2) = fSum[14];
  smatrix(3,3) = fSum[15];
  smatrix(3,4) = smatrix(4,3) = fSum[16];
  smatrix(3,5) = smatrix(5,3) = fSum[17];
  smatrix(4,4) = fSum[18];
  smatrix(4,5) = smatrix(5,4) = fSum[19];
  smatrix(5,5) = fSum[20];

  sums(0,0)    = fSum[21]; sums(0,1) = fSum[22]; sums(0,2) = fSum[23];
  sums(0,3)    = fSum[24]; sums(0,4) = fSum[25]; sums(0,5) = fSum[26];

  Int_t fixedparamat[6]={0,0,0,0,0,0};
  const Int_t unfixedparam=GetNFreeParam();
  Int_t position[6]={0,0,0,0,0,0};
  Int_t last=0;//position is of size 6 but only unfiexedparam indeces will be used

  if(fBFixed[0]==kTRUE){
    fixedparamat[0]=1;
  }
  else {
    position[0]=0;
    last++;
  }

  for(Int_t j=1;j<6;j++){
    if(fBFixed[j]==kTRUE){
      fixedparamat[j]=fixedparamat[j-1]+1;
    }
    else {
      fixedparamat[j]=fixedparamat[j-1];
      position[last]=j;
      last++;
    }
  }

  TMatrixDSym smatrixRedu(unfixedparam);
  for(Int_t i=0;i<unfixedparam;i++){
    for(Int_t j=0;j<unfixedparam;j++){
      smatrixRedu(i,j)=smatrix(position[i],position[j]);
    }
  }

  //  smatrixRedu.Print();
  smatrixRedu.Invert();

  if (!smatrixRedu.IsValid()) {
    printf("Minimization Failed! \n");
    return kFALSE;
  }

  TMatrixDSym smatrixUp(6);
  for(Int_t i=0;i<6;i++){
    for(Int_t j=0;j<6;j++){
      if(fBFixed[i]==kTRUE||fBFixed[j]==kTRUE)smatrixUp(i,j)=0.;
      else smatrixUp(i,j)=smatrixRedu(i-fixedparamat[i],j-fixedparamat[j]);
    }
  }

  Double_t covmatrarray[21];

  for(Int_t i=0;i<6;i++){
      for(Int_t j=0;j<=i;j++){
	if(fBFixed[i]==kFALSE&&fBFixed[j]==kFALSE){
	  if(TMath::Abs(smatrixUp(i,j)/TMath::Sqrt(TMath::Abs(smatrixUp(i,i)*smatrixUp(j,j))))>1.01)printf("Too large Correlation number!\n");
	}
	covmatrarray[i*(i+1)/2+j]=smatrixUp(i,j);
      }
  }

  TMatrixD res = sums*smatrixUp;
  fAlignObj->SetPars(res(0,0),res(0,1),res(0,2),
		     TMath::RadToDeg()*res(0,3),
		     TMath::RadToDeg()*res(0,4),
		     TMath::RadToDeg()*res(0,5));

  fAlignObj->SetCorrMatrix(covmatrarray);
  TMatrixD  tmp = res*sums.T();
  fChi2 = fSumR - tmp(0,0);
  fNdf -= unfixedparam;

  return kTRUE;
}

<|endoftext|>


<commit_before>#define UNICODE
#include <windows.h>
#include <ole2.h>
#include <oaidl.h>
#include <objbase.h>
#include <AtlBase.h>
#include <AtlConv.h>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdlib.h>
#include "FSAPI.h"
#include "dictationbridge-core/master/master.h"
#include "combool.h"

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleacc.lib")

#define ERR(x, msg) do { \
if(x != S_OK) {\
MessageBox(NULL, msg L"\n", NULL, NULL);\
exit(1);\
}\
} while(0)

std::string wideToString(wchar_t const * text, unsigned int length) {
	auto tmp = new char[length*2+1];
	auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text,
		length, tmp, length*2,
		NULL, NULL);
	tmp[resultingLen] = '\0';
	std::string ret(tmp);
	delete[] tmp;
	return ret;
}

std::string BSTRToString(BSTR text) {
	unsigned int len = SysStringLen(text);
	return wideToString(text, len);
}

CComPtr<IJawsApi> pJfw =nullptr;

void initSpeak() {
	CLSID JFWClass;
	auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass);
	ERR(res, L"Couldn't get Jaws interface ID");
res =pJfw.CoCreateInstance(JFWClass);
	ERR(res, L"Couldn't create Jaws interface");
}

void speak(std::wstring text) {
CComBSTR bS =CComBSTR(text.size(), text.data());
CComBool silence =false;
CComBool bResult;
	pJfw->SayString(bS, silence, &bResult);
}

void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {
	//We need to replace \r with nothing.
std::wstring text =textUnprocessed;
text.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) {
		return checkingCharacter == '\r';
	}), end(text));

	if(text.compare(L"\n\n") ==0
|| text.compare(L"") ==0 //new paragraph in word.
	) {
		speak(L"New paragraph.");
	}
	else if(text.compare(L"\n") ==0) {
		speak(L"New line.");
	}
	else {
speak(text.c_str());
}
}

void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {
std::wstringstream deletedText;
deletedText << "Deleted ";
deletedText << text;
	speak(deletedText.str().c_str());
}

//These are string constants for the microphone status, as well as the status itself:
//The pointer below is set to the last one we saw.
std::wstring MICROPHONE_OFF = L"Dragon's microphone is off;";
std::wstring MICROPHONE_ON = L"Normal mode: You can dictate and use voice";
std::wstring MICROPHONE_SLEEPING = L"The microphone is asleep;";

std::wstring microphoneState;

void announceMicrophoneState(const std::wstring state) {
	if(state == MICROPHONE_ON) speak(L"Microphone on.");
	else if(state == MICROPHONE_OFF) speak(L"Microphone off.");
	else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping.");
	else speak(L"Microphone in unknown state.");
}

wchar_t processNameBuffer[1024] = {0};

void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
	//First, is it coming from natspeak.exe?
	DWORD procId;
	GetWindowThreadProcessId(hwnd, &procId);
	auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);
	//We can't recover from this failing, so abort.
	if(procHandle == NULL) return;
	DWORD len = 1024;
	auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);
	CloseHandle(procHandle);
	if(res == 0) return;
std::wstring processName =processNameBuffer;
	if(processName.find(L"dragonbar.exe") == std::string::npos
		&& processName.find(L"natspeak.exe") == std::string::npos) return;
	//Attempt to get the new text.
CComPtr<IAccessible> pAcc;
CComVariant vChild;
	HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &vChild);
	if(hres != S_OK) return;
CComBSTR bName;
	hres = pAcc->get_accName(vChild, &bName);
	if(hres != S_OK) return;
std::wstring name =bName;
	const std::wstring possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};
std::wstring newState = microphoneState;
	for(int i = 0; i < 3; i++) {
		if(name.find(possibles[i]) != std::string::npos) {
			newState = possibles[i];
			break;
		}
	}
	if(newState != microphoneState) {
		announceMicrophoneState(newState);
		microphoneState = newState;
	}
}

int keepRunning = 1; // Goes to 0 on WM_CLOSE.
LPCTSTR msgWindowClassName = L"DictationBridgeJFWHelper";

LRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) {
	if(msg == WM_CLOSE) keepRunning = 0;
	return DefWindowProc(hwnd, msg, wparam, lparam);
}

int CALLBACK WinMain(_In_ HINSTANCE hInstance,
	_In_ HINSTANCE hPrevInstance,
	_In_ LPSTR lpCmdLine,
	_In_ int nCmdShow) {
	// First, is a core running?
	if(FindWindow(msgWindowClassName, NULL)) {
		MessageBox(NULL, L"Core already running.", NULL, NULL);
		return 0;
	}
	WNDCLASS windowClass = {0};
	windowClass.lpfnWndProc = exitProc;
	windowClass.hInstance = hInstance;
	windowClass.lpszClassName = msgWindowClassName;
	auto msgWindowClass = RegisterClass(&windowClass);
	if(msgWindowClass == 0) {
		MessageBox(NULL, L"Failed to register window class.", NULL, NULL);
		return 0;
	}
	auto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
	if(msgWindowHandle == 0) {
		MessageBox(NULL, L"Failed to create message-only window.", NULL, NULL);
		return 0;
	}
	HRESULT res;
	res = OleInitialize(NULL);
	ERR(res, L"Couldn't initialize OLE");
	initSpeak();
	auto started = DBMaster_Start();
	if(!started) {
		printf("Couldn't start DictationBridge-core\n");
		return 1;
	}
	DBMaster_SetTextInsertedCallback(textCallback);
	DBMaster_SetTextDeletedCallback(textDeletedCallback);
	if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {
		printf("Couldn't register to receive events\n");
		return 1;
	}
	MSG msg;
	while(GetMessage(&msg, NULL, NULL, NULL) > 0) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		if(keepRunning == 0) break;
	}
	DBMaster_Stop();
	OleUninitialize();
	DestroyWindow(msgWindowHandle);
	return 0;
}
<commit_msg>Remove code and includes that we no longer use.<commit_after>#define UNICODE
#include <windows.h>
#include <ole2.h>
#include <AtlBase.h>
#include <algorithm>
#include <sstream>
#include <string>
#include "FSAPI.h"
#include "dictationbridge-core/master/master.h"
#include "combool.h"

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleacc.lib")

#define ERR(x, msg) do { \
if(x != S_OK) {\
MessageBox(NULL, msg L"\n", NULL, NULL);\
exit(1);\
}\
} while(0)

CComPtr<IJawsApi> pJfw =nullptr;

void initSpeak() {
	CLSID JFWClass;
	auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass);
	ERR(res, L"Couldn't get Jaws interface ID");
res =pJfw.CoCreateInstance(JFWClass);
	ERR(res, L"Couldn't create Jaws interface");
}

void speak(std::wstring text) {
CComBSTR bS =CComBSTR(text.size(), text.data());
CComBool silence =false;
CComBool bResult;
	pJfw->SayString(bS, silence, &bResult);
}

void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {
	//We need to replace \r with nothing.
std::wstring text =textUnprocessed;
text.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) {
		return checkingCharacter == '\r';
	}), end(text));

	if(text.compare(L"\n\n") ==0
|| text.compare(L"") ==0 //new paragraph in word.
	) {
		speak(L"New paragraph.");
	}
	else if(text.compare(L"\n") ==0) {
		speak(L"New line.");
	}
	else {
speak(text.c_str());
}
}

void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {
std::wstringstream deletedText;
deletedText << "Deleted ";
deletedText << text;
	speak(deletedText.str().c_str());
}

//These are string constants for the microphone status, as well as the status itself:
//The pointer below is set to the last one we saw.
std::wstring MICROPHONE_OFF = L"Dragon's microphone is off;";
std::wstring MICROPHONE_ON = L"Normal mode: You can dictate and use voice";
std::wstring MICROPHONE_SLEEPING = L"The microphone is asleep;";

std::wstring microphoneState;

void announceMicrophoneState(const std::wstring state) {
	if(state == MICROPHONE_ON) speak(L"Microphone on.");
	else if(state == MICROPHONE_OFF) speak(L"Microphone off.");
	else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping.");
	else speak(L"Microphone in unknown state.");
}

wchar_t processNameBuffer[1024] = {0};

void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
	//First, is it coming from natspeak.exe?
	DWORD procId;
	GetWindowThreadProcessId(hwnd, &procId);
	auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);
	//We can't recover from this failing, so abort.
	if(procHandle == NULL) return;
	DWORD len = 1024;
	auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);
	CloseHandle(procHandle);
	if(res == 0) return;
std::wstring processName =processNameBuffer;
	if(processName.find(L"dragonbar.exe") == std::string::npos
		&& processName.find(L"natspeak.exe") == std::string::npos) return;
	//Attempt to get the new text.
CComPtr<IAccessible> pAcc;
CComVariant vChild;
	HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &vChild);
	if(hres != S_OK) return;
CComBSTR bName;
	hres = pAcc->get_accName(vChild, &bName);
	if(hres != S_OK) return;
std::wstring name =bName;
	const std::wstring possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};
std::wstring newState = microphoneState;
	for(int i = 0; i < 3; i++) {
		if(name.find(possibles[i]) != std::string::npos) {
			newState = possibles[i];
			break;
		}
	}
	if(newState != microphoneState) {
		announceMicrophoneState(newState);
		microphoneState = newState;
	}
}

int keepRunning = 1; // Goes to 0 on WM_CLOSE.
LPCTSTR msgWindowClassName = L"DictationBridgeJFWHelper";

LRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) {
	if(msg == WM_CLOSE) keepRunning = 0;
	return DefWindowProc(hwnd, msg, wparam, lparam);
}

int CALLBACK WinMain(_In_ HINSTANCE hInstance,
	_In_ HINSTANCE hPrevInstance,
	_In_ LPSTR lpCmdLine,
	_In_ int nCmdShow) {
	// First, is a core running?
	if(FindWindow(msgWindowClassName, NULL)) {
		MessageBox(NULL, L"Core already running.", NULL, NULL);
		return 0;
	}
	WNDCLASS windowClass = {0};
	windowClass.lpfnWndProc = exitProc;
	windowClass.hInstance = hInstance;
	windowClass.lpszClassName = msgWindowClassName;
	auto msgWindowClass = RegisterClass(&windowClass);
	if(msgWindowClass == 0) {
		MessageBox(NULL, L"Failed to register window class.", NULL, NULL);
		return 0;
	}
	auto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
	if(msgWindowHandle == 0) {
		MessageBox(NULL, L"Failed to create message-only window.", NULL, NULL);
		return 0;
	}
	HRESULT res;
	res = OleInitialize(NULL);
	ERR(res, L"Couldn't initialize OLE");
	initSpeak();
	auto started = DBMaster_Start();
	if(!started) {
		printf("Couldn't start DictationBridge-core\n");
		return 1;
	}
	DBMaster_SetTextInsertedCallback(textCallback);
	DBMaster_SetTextDeletedCallback(textDeletedCallback);
	if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {
		printf("Couldn't register to receive events\n");
		return 1;
	}
	MSG msg;
	while(GetMessage(&msg, NULL, NULL, NULL) > 0) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		if(keepRunning == 0) break;
	}
	DBMaster_Stop();
	OleUninitialize();
	DestroyWindow(msgWindowHandle);
	return 0;
}
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <SurgSim/Graphics/OsgBoxRepresentation.h>

#include <SurgSim/Graphics/OsgRigidTransformConversions.h>
#include <SurgSim/Graphics/OsgUnitBox.h>

#include <osg/Geode>
#include <osg/Shape>
#include <osg/ShapeDrawable>

using SurgSim::Graphics::OsgBoxRepresentation;
using SurgSim::Graphics::OsgUnitBox;

OsgBoxRepresentation::OsgBoxRepresentation(const std::string& name) : Representation(name), BoxRepresentation(name),
	OsgRepresentation(name, new osg::Switch()),
	m_sharedUnitBox(getSharedUnitBox()),
	m_scale(1.0, 1.0, 1.0)
{
	m_switch = static_cast<osg::Switch*>(getOsgNode().get());
	m_switch->setName(name + " Switch");

	m_transform = new osg::PositionAttitudeTransform();
	m_switch->setName(name + " Transform");
	m_transform->addChild(m_sharedUnitBox->getNode());

	m_switch->addChild(m_transform);

	std::pair<osg::Quat, osg::Vec3d> pose = std::make_pair(m_transform->getAttitude(), m_transform->getPosition());
	m_pose = fromOsg(pose);
}

void OsgBoxRepresentation::setVisible(bool visible)
{
	m_switch->setChildValue(m_transform, visible);
}

bool OsgBoxRepresentation::isVisible() const
{
	return m_switch->getChildValue(m_transform);
}

/// Sets the size along X-axis of the box
/// \param sizeX Size along X-axis of the box
void OsgBoxRepresentation::setSizeX(double sizeX)
{
	m_scale.x() = sizeX;
	m_transform->setScale(m_scale);
}
/// Returns the size along X-axis of the box
/// \return Size along X-axis of the box
double OsgBoxRepresentation::getSizeX() const
{
	return m_scale.x();
}

/// Sets the size along Y-axis of the box
/// \param sizeY Size along Y-axis of the box
void OsgBoxRepresentation::setSizeY(double sizeY)
{
	m_scale.y() = sizeY;
	m_transform->setScale(m_scale);
}
/// Returns the size along Y-axis of the box
/// \return Size along Y-axis of the box
double OsgBoxRepresentation::getSizeY() const
{
	return m_scale.y();
}

/// Sets the size along Z-axis of the box
/// \param sizeZ Size along Z-axis of the box
void OsgBoxRepresentation::setSizeZ(double sizeZ)
{
	m_scale.z() = sizeZ;
	m_transform->setScale(m_scale);
}
/// Returns the size along Z-axis of the box
/// \return Size along Z-axis of the box
double OsgBoxRepresentation::getSizeZ() const
{
	return m_scale.z();
}

/// Sets the size of the box
/// \param sizeX Size along X-axis of the box
/// \param sizeY Size along Y-axis of the box
/// \param sizeZ Size along Z-axis of the box
void OsgBoxRepresentation::setSize(double sizeX, double sizeY, double sizeZ)
{
	m_scale.x() = sizeX;
	m_scale.y() = sizeY;
	m_scale.z() = sizeZ;
	m_transform->setScale(m_scale);
}
/// Gets the size of the box
/// \param sizeX Reference to store the size along X-axis of the box
/// \param sizeY Reference to store the size along Y-axis of the box
/// \param sizeZ Reference to store the size along Z-axis of the box
void OsgBoxRepresentation::getSize(double& sizeX, double& sizeY, double& sizeZ)
{
	sizeX =	m_scale.x();
	sizeY = m_scale.y();
	sizeZ = m_scale.z();
}

/// Sets the size of the box
/// \param size Size of the box
void OsgBoxRepresentation::setSize(SurgSim::Math::Vector3d size)
{
	m_scale.set(size.x(), size.y(), size.z());
	m_transform->setScale(m_scale);
}
/// Returns the radius of the sphere
/// \return Size of the box
SurgSim::Math::Vector3d OsgBoxRepresentation::getSize() const
{
	return SurgSim::Math::Vector3d(m_scale._v);
}

void OsgBoxRepresentation::setPose(const SurgSim::Math::RigidTransform3d& transform)
{
	m_pose = transform;
	std::pair<osg::Quat, osg::Vec3d> pose = toOsg(m_pose);
	m_transform->setAttitude(pose.first);
	m_transform->setPosition(pose.second);
}

const SurgSim::Math::RigidTransform3d& OsgBoxRepresentation::getPose() const
{
	return m_pose;
}

void OsgBoxRepresentation::update(double dt)
{
}

std::shared_ptr<OsgUnitBox> OsgBoxRepresentation::getSharedUnitBox()
{
	static SurgSim::Framework::SharedInstance<OsgUnitBox> shared;
	return shared.get();
}
<commit_msg>Member intialization order fixed and function comments removed from cpp file.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <SurgSim/Graphics/OsgBoxRepresentation.h>

#include <SurgSim/Graphics/OsgRigidTransformConversions.h>
#include <SurgSim/Graphics/OsgUnitBox.h>

#include <osg/Geode>
#include <osg/Shape>
#include <osg/ShapeDrawable>

using SurgSim::Graphics::OsgBoxRepresentation;
using SurgSim::Graphics::OsgUnitBox;

OsgBoxRepresentation::OsgBoxRepresentation(const std::string& name) : Representation(name), BoxRepresentation(name),
	OsgRepresentation(name, new osg::Switch()),
	m_scale(1.0, 1.0, 1.0),
	m_sharedUnitBox(getSharedUnitBox())
{
	m_switch = static_cast<osg::Switch*>(getOsgNode().get());
	m_switch->setName(name + " Switch");

	m_transform = new osg::PositionAttitudeTransform();
	m_switch->setName(name + " Transform");
	m_transform->addChild(m_sharedUnitBox->getNode());

	m_switch->addChild(m_transform);

	std::pair<osg::Quat, osg::Vec3d> pose = std::make_pair(m_transform->getAttitude(), m_transform->getPosition());
	m_pose = fromOsg(pose);
}

void OsgBoxRepresentation::setVisible(bool visible)
{
	m_switch->setChildValue(m_transform, visible);
}

bool OsgBoxRepresentation::isVisible() const
{
	return m_switch->getChildValue(m_transform);
}

void OsgBoxRepresentation::setSizeX(double sizeX)
{
	m_scale.x() = sizeX;
	m_transform->setScale(m_scale);
}
double OsgBoxRepresentation::getSizeX() const
{
	return m_scale.x();
}

void OsgBoxRepresentation::setSizeY(double sizeY)
{
	m_scale.y() = sizeY;
	m_transform->setScale(m_scale);
}
double OsgBoxRepresentation::getSizeY() const
{
	return m_scale.y();
}

void OsgBoxRepresentation::setSizeZ(double sizeZ)
{
	m_scale.z() = sizeZ;
	m_transform->setScale(m_scale);
}
double OsgBoxRepresentation::getSizeZ() const
{
	return m_scale.z();
}

void OsgBoxRepresentation::setSize(double sizeX, double sizeY, double sizeZ)
{
	m_scale.x() = sizeX;
	m_scale.y() = sizeY;
	m_scale.z() = sizeZ;
	m_transform->setScale(m_scale);
}
void OsgBoxRepresentation::getSize(double& sizeX, double& sizeY, double& sizeZ)
{
	sizeX =	m_scale.x();
	sizeY = m_scale.y();
	sizeZ = m_scale.z();
}

void OsgBoxRepresentation::setSize(SurgSim::Math::Vector3d size)
{
	m_scale.set(size.x(), size.y(), size.z());
	m_transform->setScale(m_scale);
}
SurgSim::Math::Vector3d OsgBoxRepresentation::getSize() const
{
	return SurgSim::Math::Vector3d(m_scale._v);
}

void OsgBoxRepresentation::setPose(const SurgSim::Math::RigidTransform3d& transform)
{
	m_pose = transform;
	std::pair<osg::Quat, osg::Vec3d> pose = toOsg(m_pose);
	m_transform->setAttitude(pose.first);
	m_transform->setPosition(pose.second);
}

const SurgSim::Math::RigidTransform3d& OsgBoxRepresentation::getPose() const
{
	return m_pose;
}

void OsgBoxRepresentation::update(double dt)
{
}

std::shared_ptr<OsgUnitBox> OsgBoxRepresentation::getSharedUnitBox()
{
	static SurgSim::Framework::SharedInstance<OsgUnitBox> shared;
	return shared.get();
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2014  P.L. Lucas <selairi@gmail.com>
    Copyright (C) 2013  <copyright holder> <email>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "monitorsettingsdialog.h"

#include "monitorwidget.h"
#include "timeoutdialog.h"

#include <KScreen/Output>

MonitorSettingsDialog::MonitorSettingsDialog() :
    QDialog(nullptr, 0)
{
    ui.setupUi(this);

    KScreen::GetConfigOperation *operation = new KScreen::GetConfigOperation();
    connect(operation, &KScreen::GetConfigOperation::finished, [&] (KScreen::ConfigOperation *op) {
        KScreen::GetConfigOperation *configOp = qobject_cast<KScreen::GetConfigOperation *>(op);
        if (configOp)
        {
            mOldConfig = configOp->config();
            loadConfiguration(configOp->config());
        }
    });

    connect(ui.buttonBox, &QDialogButtonBox::clicked, [&] (QAbstractButton *button) {
        if (ui.buttonBox->standardButton(button) == QDialogButtonBox::Apply)
            applyConfiguration();
    });
}

MonitorSettingsDialog::~MonitorSettingsDialog()
{
}

void MonitorSettingsDialog::loadConfiguration(KScreen::ConfigPtr config)
{
    if (mConfig == config)
        return;

    mConfig = config;

    KScreen::OutputList outputs = mConfig->outputs();
    for (const KScreen::OutputPtr &output : outputs)
    {
        if (output->isConnected())
        {
            MonitorWidget *monitor = new MonitorWidget(output, mConfig, this);
            ui.monitorList->addItem(output->name());
            ui.stackedWidget->addWidget(monitor);
        }
    }

    ui.monitorList->setCurrentRow(0);
    adjustSize();
}

/**
 * Apply the settings
 */
void MonitorSettingsDialog::applyConfiguration()
{
    if (mConfig && KScreen::Config::canBeApplied(mConfig))
    {
        KScreen::SetConfigOperation(mConfig).exec();

        TimeoutDialog mTimeoutDialog;
        if (mTimeoutDialog.exec() == QDialog::Rejected)
            // TODO: why isn't this working? why??
            QTimer::singleShot(5000, [&] {
                KScreen::SetConfigOperation(mOldConfig).exec();
            });
        else
            mOldConfig = mConfig;
    }
}

void MonitorSettingsDialog::accept()
{
    applyConfiguration();
    QDialog::accept();
}

void MonitorSettingsDialog::reject()
{
    QDialog::reject();
}
<commit_msg>lxqt-config-monitor: fix for reverting to previous configuration<commit_after>/*
    Copyright (C) 2014  P.L. Lucas <selairi@gmail.com>
    Copyright (C) 2013  <copyright holder> <email>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "monitorsettingsdialog.h"

#include "monitorwidget.h"
#include "timeoutdialog.h"

#include <KScreen/Output>

MonitorSettingsDialog::MonitorSettingsDialog() :
    QDialog(nullptr, 0)
{
    ui.setupUi(this);

    KScreen::GetConfigOperation *operation = new KScreen::GetConfigOperation();
    connect(operation, &KScreen::GetConfigOperation::finished, [this, operation] (KScreen::ConfigOperation *op) {
        KScreen::GetConfigOperation *configOp = qobject_cast<KScreen::GetConfigOperation *>(op);
        if (configOp)
        {
            mOldConfig = configOp->config()->clone();
            loadConfiguration(configOp->config());
            operation->deleteLater();
        }
    });

    connect(ui.buttonBox, &QDialogButtonBox::clicked, [&] (QAbstractButton *button) {
        if (ui.buttonBox->standardButton(button) == QDialogButtonBox::Apply)
            applyConfiguration();
    });
}

MonitorSettingsDialog::~MonitorSettingsDialog()
{
}

void MonitorSettingsDialog::loadConfiguration(KScreen::ConfigPtr config)
{
    if (mConfig == config)
        return;

    mConfig = config;

    KScreen::OutputList outputs = mConfig->outputs();
    for (const KScreen::OutputPtr &output : outputs)
    {
        if (output->isConnected())
        {
            MonitorWidget *monitor = new MonitorWidget(output, mConfig, this);
            ui.monitorList->addItem(output->name());
            ui.stackedWidget->addWidget(monitor);
        }
    }

    ui.monitorList->setCurrentRow(0);
    adjustSize();
}

/**
 * Apply the settings
 */
void MonitorSettingsDialog::applyConfiguration()
{
    if (mConfig && KScreen::Config::canBeApplied(mConfig))
    {
        KScreen::SetConfigOperation(mConfig).exec();

        TimeoutDialog mTimeoutDialog;
        if (mTimeoutDialog.exec() == QDialog::Rejected)
            KScreen::SetConfigOperation(mOldConfig).exec();
        else
            mOldConfig = mConfig->clone();
    }
}

void MonitorSettingsDialog::accept()
{
    applyConfiguration();
    QDialog::accept();
}

void MonitorSettingsDialog::reject()
{
    QDialog::reject();
}
<|endoftext|>


<commit_before>/*
 * This file is part of Maliit Plugins
 *
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
 *
 * Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * Neither the name of Nokia Corporation nor the names of its contributors may be
 * used to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "utils.h"

#include "models/area.h"
#include "models/key.h"
#include "models/keyarea.h"
#include "models/layout.h"
#include "models/text.h"
#include "view/glass.h"
#include "view/setup.h"
#include "logic/wordengine.h"
#include "plugin/editor.h"
#include "inputmethodhostprobe.h"

#include <maliit/plugins/testsurfacefactory.h>

#include <QtCore>
#include <QtTest>
#include <QWidget>
#include <QList>
#include <QMouseEvent>

using namespace MaliitKeyboard;
Q_DECLARE_METATYPE(Layout::Orientation)
Q_DECLARE_METATYPE(QList<QMouseEvent*>)

namespace {
const int g_size = 48;
const int g_divider = 3;

QPoint keyOriginLookup(const QString &name)
{
    static const int distance = g_size / g_divider;

    if (name == "a") {
        return QPoint(0, 0);
    } else if (name == "b") {
        return QPoint(distance, 0);
    } else if (name == "c") {
        return QPoint(0, distance);
    } else if (name == "d") {
        return QPoint(distance, distance);
    } else if (name == "space") {
        return QPoint(distance * 2, 0);
    } else if (name == "return") {
        return QPoint(distance * 2, distance);
    }

    return QPoint();
}

Key createKey(Key::Action action,
              const QString &text)
{
    static const QSize size(g_size / g_divider, g_size / g_divider);

    Key result;
    result.setAction(action);
    result.setOrigin(keyOriginLookup(text));
    result.rArea().setSize(size);
    result.rLabel().setText(text);

    return result;
}

// Populate KeyArea with six keys, a, b, c, d, space and return. Notice how the KeyArea
// covers the whole widget. Key width and height equals g_size / g_divider.
// .-----------.
// | a | b |<s>|
// |---|---|---|
// | c | d |<r>|
// `-----------'
KeyArea createAbcdArea()
{
    KeyArea key_area;
    Area area;
    area.setSize(QSize(g_size, g_size));
    key_area.setArea(area);

    key_area.rKeys().append(createKey(Key::ActionInsert, "a"));
    key_area.rKeys().append(createKey(Key::ActionInsert, "b"));
    key_area.rKeys().append(createKey(Key::ActionInsert, "c"));
    key_area.rKeys().append(createKey(Key::ActionInsert, "d"));
    key_area.rKeys().append(createKey(Key::ActionSpace,  "space"));
    key_area.rKeys().append(createKey(Key::ActionReturn, "return"));

    return key_area;
}

QList<QMouseEvent *> createPressReleaseEvent(const QPoint &origin,
                                             Layout::Orientation orientation)
{
    static const int offset(g_size / (g_divider * 2));

    QList<QMouseEvent *> result;
    QPoint pos = (orientation == Layout::Landscape) ? QPoint(origin.x() + offset, origin.y() + offset)
                                                    : QPoint(origin.y() + offset, g_size - (origin.x() + offset));

    result.append(new QMouseEvent(QKeyEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));
    result.append(new QMouseEvent(QKeyEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));

    return result;
}
}

class TestPreeditString
    : public QObject
{
    Q_OBJECT

private:
    typedef QList<Maliit::PreeditTextFormat> FormatList;

    Q_SLOT void initTestCase()
    {
        qRegisterMetaType<QList<QMouseEvent*> >();
        qRegisterMetaType<Layout::Orientation>();
        qRegisterMetaType<FormatList>();
    }

    Q_SLOT void test_data()
    {
        QTest::addColumn<Layout::Orientation>("orientation");
        QTest::addColumn<QList<QMouseEvent*> >("mouse_events");
        QTest::addColumn<QString>("expected_last_preedit_string");
        QTest::addColumn<QString>("expected_commit_string");
        QTest::addColumn<FormatList>("expected_preedit_format");

        for (int orientation = 0; orientation < 1; ++orientation) {
            // FIXME: here should be 2          ^
            // FIXME: tests fail for portrait layouts
            const Layout::Orientation layout_orientation(orientation == 0 ? Layout::Landscape
                                                                          : Layout::Portrait);
            QTest::newRow("No mouse events: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>())
                << "" << "" << FormatList();

            QTest::newRow("Only return pressed: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "" << "" << FormatList();

            QTest::newRow("Release outside of widget: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(QPoint(g_size * 2, g_size * 2), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "" << "" << FormatList();

            QTest::newRow("Release button over key 'a': expect commit string 'a'.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "a" << "a" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));

            QTest::newRow("Release button over key 'a', but no commit: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation))
                << "a" << "" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));

            QTest::newRow("Release button over keys 'c, b, d, a': expect commit string 'cbda'.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("space"), layout_orientation))
                << "cbda" << "cbda " << (FormatList() << Maliit::PreeditTextFormat(0, 4, Maliit::PreeditDefault));

            QTest::newRow("Typing two words: expect commit string 'ab cd', with last preedit being 'cd'.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("space"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "cd" << "ab cd" << (FormatList() << Maliit::PreeditTextFormat(0, 2, Maliit::PreeditDefault));

        }
    }

    Q_SLOT void test()
    {
        // FIXME: mikhas: We should have tests for the preedit &
        // preedit correctness stuff, and how it blends with word
        // prediction. I guess you will need to add
        // WordEngine::setSpellChecker() API so that you can inject a
        // fake spellchecker, for the tests. Otherwise, the test would
        // have to be skipped when there's no hunspell/presage, which
        // I wouldn't like to have.

        QFETCH(Layout::Orientation, orientation);
        QFETCH(QList<QMouseEvent*>, mouse_events);
        QFETCH(QString, expected_last_preedit_string);
        QFETCH(QString, expected_commit_string);
        QFETCH(QList<Maliit::PreeditTextFormat>, expected_preedit_format);

        Glass glass;
        Editor editor(EditorOptions(), new Model::Text, new Logic::WordEngine, 0);
        InputMethodHostProbe host;
        SharedLayout layout(new Layout);
        QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> surface(Maliit::Plugins::createTestGraphicsViewSurface());
        QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> extended_surface(Maliit::Plugins::createTestGraphicsViewSurface(surface));

        // geometry stuff is usually done by maliit-server, so we need
        // to do it manually here:
        //surface->view()->viewport()->setGeometry(0, 0, g_size, g_size);
        surface->view()->setSceneRect(0, 0, g_size, g_size);
        surface->scene()->setSceneRect(0, 0, g_size, g_size);
        glass.setSurface(surface);
        glass.setExtendedSurface(extended_surface);
        glass.addLayout(layout);
        editor.setHost(&host);
        layout->setOrientation(orientation);
        editor.setPreeditEnabled(true);

        Setup::connectGlassToTextEditor(&glass, &editor);
        const KeyArea &key_area(createAbcdArea());

        layout->setExtendedPanel(key_area);
        layout->setActivePanel(Layout::ExtendedPanel);

        Q_FOREACH (QMouseEvent *ev, mouse_events) {
            QApplication::instance()->postEvent(surface->view()->viewport(), ev);
        }

        TestUtils::waitForSignal(&glass, SIGNAL(keyReleased(Key,SharedLayout)));
        QCOMPARE(host.lastPreeditString(), expected_last_preedit_string);
        QCOMPARE(host.commitStringHistory(), expected_commit_string);
        QCOMPARE(host.lastPreeditTextFormatList(), expected_preedit_format);
    }
};

QTEST_MAIN(TestPreeditString)
#include "main.moc"
<commit_msg>Add equality operator for Maliit::PreeditTextFormat.<commit_after>/*
 * This file is part of Maliit Plugins
 *
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
 *
 * Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * Neither the name of Nokia Corporation nor the names of its contributors may be
 * used to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "utils.h"

#include "models/area.h"
#include "models/key.h"
#include "models/keyarea.h"
#include "models/layout.h"
#include "models/text.h"
#include "view/glass.h"
#include "view/setup.h"
#include "logic/wordengine.h"
#include "plugin/editor.h"
#include "inputmethodhostprobe.h"

#include <maliit/plugins/testsurfacefactory.h>

#include <QtCore>
#include <QtTest>
#include <QWidget>
#include <QList>
#include <QMouseEvent>

using namespace MaliitKeyboard;
Q_DECLARE_METATYPE(Layout::Orientation)
Q_DECLARE_METATYPE(QList<QMouseEvent*>)

namespace {
const int g_size = 48;
const int g_divider = 3;

QPoint keyOriginLookup(const QString &name)
{
    static const int distance = g_size / g_divider;

    if (name == "a") {
        return QPoint(0, 0);
    } else if (name == "b") {
        return QPoint(distance, 0);
    } else if (name == "c") {
        return QPoint(0, distance);
    } else if (name == "d") {
        return QPoint(distance, distance);
    } else if (name == "space") {
        return QPoint(distance * 2, 0);
    } else if (name == "return") {
        return QPoint(distance * 2, distance);
    }

    return QPoint();
}

Key createKey(Key::Action action,
              const QString &text)
{
    static const QSize size(g_size / g_divider, g_size / g_divider);

    Key result;
    result.setAction(action);
    result.setOrigin(keyOriginLookup(text));
    result.rArea().setSize(size);
    result.rLabel().setText(text);

    return result;
}

// Populate KeyArea with six keys, a, b, c, d, space and return. Notice how the KeyArea
// covers the whole widget. Key width and height equals g_size / g_divider.
// .-----------.
// | a | b |<s>|
// |---|---|---|
// | c | d |<r>|
// `-----------'
KeyArea createAbcdArea()
{
    KeyArea key_area;
    Area area;
    area.setSize(QSize(g_size, g_size));
    key_area.setArea(area);

    key_area.rKeys().append(createKey(Key::ActionInsert, "a"));
    key_area.rKeys().append(createKey(Key::ActionInsert, "b"));
    key_area.rKeys().append(createKey(Key::ActionInsert, "c"));
    key_area.rKeys().append(createKey(Key::ActionInsert, "d"));
    key_area.rKeys().append(createKey(Key::ActionSpace,  "space"));
    key_area.rKeys().append(createKey(Key::ActionReturn, "return"));

    return key_area;
}

QList<QMouseEvent *> createPressReleaseEvent(const QPoint &origin,
                                             Layout::Orientation orientation)
{
    static const int offset(g_size / (g_divider * 2));

    QList<QMouseEvent *> result;
    QPoint pos = (orientation == Layout::Landscape) ? QPoint(origin.x() + offset, origin.y() + offset)
                                                    : QPoint(origin.y() + offset, g_size - (origin.x() + offset));

    result.append(new QMouseEvent(QKeyEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));
    result.append(new QMouseEvent(QKeyEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier));

    return result;
}

bool operator==(const Maliit::PreeditTextFormat &a, const Maliit::PreeditTextFormat &b) {
    return ((a.start == b.start) and (a.length == b.length) and (a.preeditFace == b.preeditFace));
}

} // unnamed namespace

class TestPreeditString
    : public QObject
{
    Q_OBJECT

private:
    typedef QList<Maliit::PreeditTextFormat> FormatList;

    Q_SLOT void initTestCase()
    {
        qRegisterMetaType<QList<QMouseEvent*> >();
        qRegisterMetaType<Layout::Orientation>();
        qRegisterMetaType<FormatList>();
    }

    Q_SLOT void test_data()
    {
        QTest::addColumn<Layout::Orientation>("orientation");
        QTest::addColumn<QList<QMouseEvent*> >("mouse_events");
        QTest::addColumn<QString>("expected_last_preedit_string");
        QTest::addColumn<QString>("expected_commit_string");
        QTest::addColumn<FormatList>("expected_preedit_format");

        for (int orientation = 0; orientation < 1; ++orientation) {
            // FIXME: here should be 2          ^
            // FIXME: tests fail for portrait layouts
            const Layout::Orientation layout_orientation(orientation == 0 ? Layout::Landscape
                                                                          : Layout::Portrait);
            QTest::newRow("No mouse events: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>())
                << "" << "" << FormatList();

            QTest::newRow("Only return pressed: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "" << "" << FormatList();

            QTest::newRow("Release outside of widget: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(QPoint(g_size * 2, g_size * 2), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "" << "" << FormatList();

            QTest::newRow("Release button over key 'a': expect commit string 'a'.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "a" << "a" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));

            QTest::newRow("Release button over key 'a', but no commit: expect empty commit string.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation))
                << "a" << "" << (FormatList() << Maliit::PreeditTextFormat(0, 1, Maliit::PreeditDefault));

            QTest::newRow("Release button over keys 'c, b, d, a': expect commit string 'cbda'.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("space"), layout_orientation))
                << "cbda" << "cbda " << (FormatList() << Maliit::PreeditTextFormat(0, 4, Maliit::PreeditDefault));

            QTest::newRow("Typing two words: expect commit string 'ab cd', with last preedit being 'cd'.")
                << layout_orientation
                << (QList<QMouseEvent *>() << createPressReleaseEvent(keyOriginLookup("a"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("b"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("space"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("c"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("d"), layout_orientation)
                                           << createPressReleaseEvent(keyOriginLookup("return"), layout_orientation))
                << "cd" << "ab cd" << (FormatList() << Maliit::PreeditTextFormat(0, 2, Maliit::PreeditDefault));

        }
    }

    Q_SLOT void test()
    {
        // FIXME: mikhas: We should have tests for the preedit &
        // preedit correctness stuff, and how it blends with word
        // prediction. I guess you will need to add
        // WordEngine::setSpellChecker() API so that you can inject a
        // fake spellchecker, for the tests. Otherwise, the test would
        // have to be skipped when there's no hunspell/presage, which
        // I wouldn't like to have.

        QFETCH(Layout::Orientation, orientation);
        QFETCH(QList<QMouseEvent*>, mouse_events);
        QFETCH(QString, expected_last_preedit_string);
        QFETCH(QString, expected_commit_string);
        QFETCH(QList<Maliit::PreeditTextFormat>, expected_preedit_format);

        Glass glass;
        Editor editor(EditorOptions(), new Model::Text, new Logic::WordEngine, 0);
        InputMethodHostProbe host;
        SharedLayout layout(new Layout);
        QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> surface(Maliit::Plugins::createTestGraphicsViewSurface());
        QSharedPointer<Maliit::Plugins::AbstractGraphicsViewSurface> extended_surface(Maliit::Plugins::createTestGraphicsViewSurface(surface));

        // geometry stuff is usually done by maliit-server, so we need
        // to do it manually here:
        //surface->view()->viewport()->setGeometry(0, 0, g_size, g_size);
        surface->view()->setSceneRect(0, 0, g_size, g_size);
        surface->scene()->setSceneRect(0, 0, g_size, g_size);
        glass.setSurface(surface);
        glass.setExtendedSurface(extended_surface);
        glass.addLayout(layout);
        editor.setHost(&host);
        layout->setOrientation(orientation);
        editor.setPreeditEnabled(true);

        Setup::connectGlassToTextEditor(&glass, &editor);
        const KeyArea &key_area(createAbcdArea());

        layout->setExtendedPanel(key_area);
        layout->setActivePanel(Layout::ExtendedPanel);

        Q_FOREACH (QMouseEvent *ev, mouse_events) {
            QApplication::instance()->postEvent(surface->view()->viewport(), ev);
        }

        TestUtils::waitForSignal(&glass, SIGNAL(keyReleased(Key,SharedLayout)));
        QCOMPARE(host.lastPreeditString(), expected_last_preedit_string);
        QCOMPARE(host.commitStringHistory(), expected_commit_string);
        QCOMPARE(host.lastPreeditTextFormatList(), expected_preedit_format);
    }
};

QTEST_MAIN(TestPreeditString)
#include "main.moc"
<|endoftext|>