<commit_before>#include "ReversedCoaxialRZ.h"
#include "iostream"
#include "Units.h"
#include <cmath>
using namespace GeFiCa;
void ReversedCoaxialRZ::SetupBoundary()
{
   double x1=HoleOutterR,
	  y1=Z,
	  x2=HoleInnerR,
	  y2=Z-HoleZ,
	  x3=Radius-ConnorLength,
	  y3=Z,
	  x4=Radius,
	  y4=Z-ConnorZ;
   // y = k x + b
   double k1=(y1-y2)/(x1-x2);
   double b1=y1-k1*x1;
   double k2=(y3-y4)/(x3-x4);
   double b2=y3-k2*x3;

   for (int i=0;i<n;i++) {
      //right side of hole
      if(fC1[i]-fC2[i]/k1+b1/k1<fdC1m[i] && fC2[i]>y2 &&
            fC1[i]-fC2[i]/k1+b1/k1>0) fdC1m[i]=fC1[i]-fC2[i]/k1+b1/k1;
      //left corner
      if(fC1[i]+fC2[i]/k2-b2/k2>0 && fC1[i]+fC2[i]/k2-b2/k2<fdC1m[i] &&
            fC2[i]>y4) fdC1m[i]=fC1[i]+fC2[i]/k2-b2/k2;
      //left side of hole
      if(-fC1[i]-fC2[i]/k1+b1/k1>0&&-fC1[i]-fC2[i]/k1+b1/k1<fdC1p[i]&&fC2[i]>y2)
         fdC1p[i]=-fC1[i]-fC2[i]/k1+b1/k1;
      //right corner
      if(-fC1[i]+fC2[i]/k2-b2/k2>0&&-fC1[i]+fC2[i]/k2-b2/k2<fdC1p[i]&&fC2[i]>y4)
         fdC1p[i]=-fC1[i]+fC2[i]/k2-b2/k2;
      //down right side of hole
      if(-fC2[i]+fC1[i]*k1+b1>0&&-fC2[i]+fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
         fdC2p[i]=-fC2[i]+fC1[i]*k1+b1;
      //down right of corner
      if(-fC2[i]-fC1[i]*k2+b2>0&&-fC2[i]-fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
         fdC2p[i]=-fC2[i]-fC1[i]*k2+b2;
      //down left side of hole
      if(-fC2[i]-fC1[i]*k1+b1>0&&-fC2[i]-fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
         fdC2p[i]=-fC2[i]-fC1[i]*k1+b1;
      //down left of corner
      if(-fC2[i]+fC1[i]*k2+b2>0&&-fC2[i]+fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
         fdC2p[i]=-fC2[i]+fC1[i]*k2+b2;
      //down center of hole
      if(y2-fC2[i]<fdC2p[i]&&fC1[i]>-HoleInnerR&&fC1[i]<HoleInnerR)
         fdC2p[i]=y2-fC2[i];
   }
}
//_____________________________________________________________________________
//
void ReversedCoaxialRZ::Initialize()
{
   if (Radius<=HoleOutterR||Radius<=HoleInnerR) {
      Warning("Initialize",
            "Lower bound (%f) >= upper bound (%f)! No grid is created!",
            Radius, HoleOutterR);
      return;
   }
   double steplength1=(Radius*2)/(n1-1);
   double steplength2=(Z-Z0)/(n2-1);
   SetStepLength(steplength1,steplength2);
   double x1=HoleOutterR,
	  y1=Z,
	  x2=HoleInnerR,
	  y2=Z-HoleZ,
	  x3=Radius-ConnorLength,
	  y3=Z,
	  x4=Radius,
	  y4=Z-ConnorZ;
   double k1=(y1-y2)/(x1-x2);
   double b1=y1-k1*x1;
   double k2=(y3-y4)/(x3-x4);
   double b2=(y3-k2*x3);

   for(int i=n;i-->0;)
   {
      fC1[i]=fC1[i]-Radius;
      fV[i]=(V0+V1)/2;
   }
   // set potential for electrodes
   for(int i=n-1;i>=n-n1;i--) {
      fIsFixed[i]=true;
      fV[i]=V0;
      if(fC1[n-1-i]>=-PointContactR-0.001&&fC1[n-1-i]<=PointContactR+0.001) {
         fV[n-1-i]=V1;
         fIsFixed[n-1-i]=true;
      }
   }
   for(int i=0;i<n-n1;i=i+n1) {
      fIsFixed[i]=true;
      fIsFixed[i+n1-1]=true;
      fV[i]=V0;
      fV[i+n1-1]=V0;
   }
   for (int i=0;i<n;i++)
   {
     if(((fC2[i]>-k1*(fC1[i])+b1-steplength2/2  && fC2[i]>y2-steplength2/2)||(fC2[i]>-k2*(fC1[i])+b2-steplength2/2))&&fC1[i]<0)
     {
       fIsFixed[i]=true;
       fV[i]=V0;
     }

     if(((fC2[i]>-k1*(fC1[i])+b1+steplength2 && fC2[i]>y2+steplength2)||fC2[i]>-k2*(fC1[i])+b2+steplength2)&&fC1[i]<0)
     {
       fV[i]=0;
     }
     if(((fC2[i]>k1*(fC1[i])+b1-steplength2/2  && fC2[i]>y2-steplength2/2)||(fC2[i]>k2*(fC1[i])+b2-steplength2/2))&&fC1[i]>0)
     {
       fIsFixed[i]=true;
       fV[i]=V0;
     }

     if(((fC2[i]>k1*(fC1[i])+b1+steplength2 && fC2[i]>y2+steplength2)||fC2[i]>k2*(fC1[i])+b2+steplength2)&&fC1[i]>0)
     {
       fV[i]=0;
     }
   }
   SetupBoundary();
}
//_____________________________________________________________________________
//
bool ReversedCoaxialRZ::CalculatePotential(EMethod method)
{
   if(!fIsLoaded)Initialize();
   return RZ::CalculatePotential(method);
}
<commit_msg>fix hole boundary setup<commit_after>#include "ReversedCoaxialRZ.h"
#include "iostream"
#include "Units.h"
#include <cmath>
using namespace GeFiCa;
void ReversedCoaxialRZ::SetupBoundary()
{
   double x1=HoleOutterR,
	  y1=Z,
	  x2=HoleInnerR,
	  y2=Z-HoleZ,
	  x3=Radius-ConnorLength,
	  y3=Z,
	  x4=Radius,
	  y4=Z-ConnorZ;
   // y = k x + b
   double k1=(y1-y2)/(x1-x2);
   double b1=y1-k1*x1;
   double k2=(y3-y4)/(x3-x4);
   double b2=y3-k2*x3;

   for (int i=0;i<n;i++) {
      //right side of hole
      if(fC1[i]-fC2[i]/k1+b1/k1<fdC1m[i] && fC2[i]>y2 &&
            fC1[i]-fC2[i]/k1+b1/k1>0) fdC1m[i]=fC1[i]-fC2[i]/k1+b1/k1;
      //left corner
      if(fC1[i]+fC2[i]/k2-b2/k2>0 && fC1[i]+fC2[i]/k2-b2/k2<fdC1m[i] &&
            fC2[i]>y4) fdC1m[i]=fC1[i]+fC2[i]/k2-b2/k2;
      //left side of hole
      if(-fC1[i]-fC2[i]/k1+b1/k1>0&&-fC1[i]-fC2[i]/k1+b1/k1<fdC1p[i]&&fC2[i]>y2)
         fdC1p[i]=-fC1[i]-fC2[i]/k1+b1/k1;
      //right corner
      if(-fC1[i]+fC2[i]/k2-b2/k2>0&&-fC1[i]+fC2[i]/k2-b2/k2<fdC1p[i]&&fC2[i]>y4)
         fdC1p[i]=-fC1[i]+fC2[i]/k2-b2/k2;
      //down right side of hole
      if(-fC2[i]+fC1[i]*k1+b1>0&&-fC2[i]+fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
         fdC2p[i]=-fC2[i]+fC1[i]*k1+b1;
      //down right of corner
      if(-fC2[i]-fC1[i]*k2+b2>0&&-fC2[i]-fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
         fdC2p[i]=-fC2[i]-fC1[i]*k2+b2;
      //down left side of hole
      if(-fC2[i]-fC1[i]*k1+b1>0&&-fC2[i]-fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
         fdC2p[i]=-fC2[i]-fC1[i]*k1+b1;
      //down left of corner
      if(-fC2[i]+fC1[i]*k2+b2>0&&-fC2[i]+fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
         fdC2p[i]=-fC2[i]+fC1[i]*k2+b2;
      //down center of hole
      if(y2-fC2[i]<fdC2p[i]&&fC1[i]>-HoleInnerR&&fC1[i]<HoleInnerR)
         fdC2p[i]=y2-fC2[i];
   }
}
//_____________________________________________________________________________
//
void ReversedCoaxialRZ::Initialize()
{
   if (Radius<=HoleOutterR||Radius<=HoleInnerR) {
      Warning("Initialize",
            "Lower bound (%f) >= upper bound (%f)! No grid is created!",
            Radius, HoleOutterR);
      return;
   }
   double steplength1=(Radius*2)/(n1-1);
   double steplength2=(Z-Z0)/(n2-1);
   SetStepLength(steplength1,steplength2);
   double x1=HoleOutterR,
	  y1=Z,
	  x2=HoleInnerR,
	  y2=Z-HoleZ,
	  x3=Radius-ConnorLength,
	  y3=Z,
	  x4=Radius,
	  y4=Z-ConnorZ;
   double k1=(y1-y2)/(x1-x2);
   double b1=y1-k1*x1;
   double k2=(y3-y4)/(x3-x4);
   double b2=(y3-k2*x3);

   for(int i=n;i-->0;)
   {
      fC1[i]=fC1[i]-Radius;
      fV[i]=(V0+V1)/2;
   }
   // set potential for electrodes
   for(int i=n-1;i>=n-n1;i--) {
      fIsFixed[i]=true;
      fV[i]=V0;
      if(fC1[n-1-i]>=-PointContactR-0.001&&fC1[n-1-i]<=PointContactR+0.001) {
         fV[n-1-i]=V1;
         fIsFixed[n-1-i]=true;
      }
   }
   for(int i=0;i<n-n1;i=i+n1) {
      fIsFixed[i]=true;
      fIsFixed[i+n1-1]=true;
      fV[i]=V0;
      fV[i+n1-1]=V0;
   }
   for (int i=0;i<n;i++)
   {
     if(((fC2[i]>-k1*(fC1[i])+b1  && fC2[i]>y2)||(fC2[i]>-k2*(fC1[i])+b2))&&fC1[i]<0)
     {
       fIsFixed[i]=true;
       fV[i]=V0;
     }
     if(((fC2[i]>k1*(fC1[i])+b1  && fC2[i]>y2)||(fC2[i]>k2*(fC1[i])+b2))&&fC1[i]>0)
     {
       fIsFixed[i]=true;
       fV[i]=V0;
     }

   }
   SetupBoundary();
}
//_____________________________________________________________________________
//
bool ReversedCoaxialRZ::CalculatePotential(EMethod method)
{
   if(!fIsLoaded)Initialize();
   return RZ::CalculatePotential(method);
}
<|endoftext|>


<commit_before>#include "SecondaryWindows.h"

FenetreNewGame::FenetreNewGame()
{
    setWindowTitle("Nouvelle partie");
    setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
    setFixedSize(300, 240);

	QGridLayout *grid1 = new QGridLayout();
	QGridLayout *grid2 = new QGridLayout();

	group1 = new QGroupBox();
	group2 = new QGroupBox();
	dialogButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

	connect(dialogButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);
	connect(dialogButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);

	// choix de la difficulte
	m_facile = new QRadioButton("Facile");
	m_moyen = new QRadioButton("Moyen");
	m_difficile = new QRadioButton("Difficile");
	m_aleatoire = new QRadioButton("Aleatoire");

	// choix du nombre de joueurs
	m_un = new QRadioButton("Un joueur");
	m_deux = new QRadioButton("Deux joueurs");

	//Definition des Sections;
	grid1->addWidget(m_un);
	grid1->addWidget(m_deux);
	m_un->setChecked(true);

	grid2->addWidget(m_facile, 0, 0, 0, 9, Qt::AlignLeft);
	grid2->addWidget(m_moyen, 0, 4, 0, 8);
	grid2->addWidget(m_difficile, 0, 6, 0, 9, Qt::AlignCenter);
	grid2->addWidget(m_aleatoire, 0, 9, 0, 9, Qt::AlignRight);
	m_facile->setChecked(true);

	// integration de bouton
	QVBoxLayout *vertical = new QVBoxLayout();
	QHBoxLayout *horizontal = new QHBoxLayout();

	group1->setLayout(grid1);
	group1->setTitle("Selectionner le nombre de joueurs");
	group2->setLayout(grid2);
	group2->setTitle("Selectionner la difficulte");
	vertical->addWidget(group1);
	horizontal->addWidget(group2);
	vertical->addLayout(horizontal);
	vertical->addWidget(dialogButtons);

	setLayout(vertical);
}

FenetreTutoriel::FenetreTutoriel()
{
	setWindowTitle("Tutoriel");
    setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));

	window = new QVBoxLayout();
	title = new QLabel("Dans ce pr" + QString(233) + "sent tutoriel, l'explication du jeu sera fait enti" + QString(232) + "rement.");

	content = new QLabel("	Pour ajuster les param" + QString(232) + "tre du canon, dite 'A' ou 'O' et le tenire jusqu'"
		+ QString(224) + " ce que vous vouliez arr" + QString(234) +
		"ter! \n	Pour change le mode, dite 'I' pour changer le mode \n");

	window->addWidget(title, 1, Qt::AlignCenter);
	window->addWidget(content, 1, Qt::AlignCenter);

	QHBoxLayout * firstRow = new QHBoxLayout;
	QLabel * firstPicture = new QLabel;
	firstPicture->setPixmap(QPixmap(":/resources/tutoriel/tour_joueur.jpg"));
	QLabel * firstText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du joueur courant.");

	firstRow->addWidget(firstPicture);
	firstRow->addWidget(firstText, 0, Qt::AlignRight);

	QHBoxLayout * secondRow = new QHBoxLayout;
	QLabel * secondPicture = new QLabel;
	secondPicture->setPixmap(QPixmap(":/resources/tutoriel/mode_joueur.jpg"));
	QLabel * secondText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du mode d'ajustement courant du joueur.");

	secondRow->addWidget(secondPicture);
	secondRow->addWidget(secondText, 0, Qt::AlignRight);

	QHBoxLayout * thirdRow = new QHBoxLayout;
	QLabel * thirdPicture = new QLabel;
	thirdPicture->setPixmap(QPixmap(":/resources/tutoriel/parametres_mode.jpg"));
	QLabel * thirdText = new QLabel("Indicateur des param" + QString(232) + "tres de tir du joueur");

	thirdRow->addWidget(thirdPicture);
	thirdRow->addWidget(thirdText, 0, Qt::AlignRight);

	window->addLayout(firstRow);
	window->addLayout(secondRow);
	window->addLayout(thirdRow);

	setLayout(window);

}

FenetreVersion::FenetreVersion()
{
	setWindowTitle("Version");
    setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
	setFixedSize(500, 140);

	QVBoxLayout * vertical = new QVBoxLayout();
	m_ligne1 = new QLabel("SCORCH VERSION 0.5");
	m_ligne2 = new QLabel("Derniere mise a jour : 2016-04-04");
	m_ligne3 = new QLabel("Developpe par l'equipe P19 de l'U de S");
	m_ligne4 = new QLabel("Les programmeurs ayant particip" + QString(233) + " " + QString(224) + " la cr" + QString(233) + "ation de Scorch");
	m_ligne5 = new QLabel("Emile Fugulin, Jean-Philippe Fournier, Julien Larochelle, Philippe Spino");

	m_ligne1->setFont(QFont("OCR A extented",10));
	m_ligne2->setFont(QFont("fantasque sans mono",10));
	m_ligne3->setFont(QFont("fantasque sans mono",10));
	m_ligne4->setFont(QFont("fantasque sans mono",10));
	m_ligne5->setFont(QFont("fantasque sans mono",10));

	vertical->addWidget(m_ligne1, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne2, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne3, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne4, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne5, 1, Qt::AlignCenter);
	setLayout(vertical);
}
<commit_msg>Continued tutorial window<commit_after>#include "SecondaryWindows.h"

FenetreNewGame::FenetreNewGame()
{
    setWindowTitle("Nouvelle partie");
    setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
    setFixedSize(300, 240);

	QGridLayout *grid1 = new QGridLayout();
	QGridLayout *grid2 = new QGridLayout();

	group1 = new QGroupBox();
	group2 = new QGroupBox();
	dialogButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

	connect(dialogButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);
	connect(dialogButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);

	// choix de la difficulte
	m_facile = new QRadioButton("Facile");
	m_moyen = new QRadioButton("Moyen");
	m_difficile = new QRadioButton("Difficile");
	m_aleatoire = new QRadioButton("Aleatoire");

	// choix du nombre de joueurs
	m_un = new QRadioButton("Un joueur");
	m_deux = new QRadioButton("Deux joueurs");

	//Definition des Sections;
	grid1->addWidget(m_un);
	grid1->addWidget(m_deux);
	m_un->setChecked(true);

	grid2->addWidget(m_facile, 0, 0, 0, 9, Qt::AlignLeft);
	grid2->addWidget(m_moyen, 0, 4, 0, 8);
	grid2->addWidget(m_difficile, 0, 6, 0, 9, Qt::AlignCenter);
	grid2->addWidget(m_aleatoire, 0, 9, 0, 9, Qt::AlignRight);
	m_facile->setChecked(true);

	// integration de bouton
	QVBoxLayout *vertical = new QVBoxLayout();
	QHBoxLayout *horizontal = new QHBoxLayout();

	group1->setLayout(grid1);
	group1->setTitle("Selectionner le nombre de joueurs");
	group2->setLayout(grid2);
	group2->setTitle("Selectionner la difficulte");
	vertical->addWidget(group1);
	horizontal->addWidget(group2);
	vertical->addLayout(horizontal);
	vertical->addWidget(dialogButtons);

	setLayout(vertical);
}

FenetreTutoriel::FenetreTutoriel()
{
	setWindowTitle("Tutoriel");
    setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
	setMaximumSize(QSize(600, 2000));
	setSizePolicy(QSizePolicy::Maximum, QSizePolicy::MinimumExpanding);

	window = new QVBoxLayout();
	//title = new QLabel("Dans ce pr" + QString(233) + "sent tutoriel, l'explication du jeu sera fait enti" + QString(232) + "rement.");

	content = new QLabel("Pour ajuster les param" + QString(232) + "tre du canon, dite 'A' ou 'O' et le tenir jusqu'"
		+ QString(224) + " ce que vous vouliez arr" + QString(234) + "ter. Pour changer le mode, il faut prononcer la lettre 'I'. Les clavier peut aussi contrler les activits de tir, les flches gauche et droite permettant de modifier le mode d'ajustement et les flches haut et bas permettant d'ajuster le paramtre. La barre espace permet quant  elle de provoquer le tir lorsque le mode est \"tir\"");
	content->setWordWrap(true);
	//window->addWidget(title, 0, Qt::AlignCenter);
	window->addWidget(content, 0, Qt::AlignLeft);

	QHBoxLayout * firstRow = new QHBoxLayout;
	QLabel * firstPicture = new QLabel;
	firstPicture->setPixmap(QPixmap(":/resources/tutoriel/tour_joueur.jpg"));
	QLabel * firstText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du joueur courant.");
	//firstText->setWordWrap(true);

	firstRow->addWidget(firstText, 0, Qt::AlignLeft);
	firstRow->addWidget(firstPicture, 0, Qt::AlignRight);

	QHBoxLayout * secondRow = new QHBoxLayout;
	QLabel * secondPicture = new QLabel;
	secondPicture->setPixmap(QPixmap(":/resources/tutoriel/mode_joueur.jpg"));
	QLabel * secondText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du mode d'ajustement courant du joueur.");
	//secondText->setWordWrap(true);

	secondRow->addWidget(secondText, 0, Qt::AlignLeft);
	secondRow->addWidget(secondPicture, 0, Qt::AlignRight);

	QHBoxLayout * thirdRow = new QHBoxLayout;
	QLabel * thirdPicture = new QLabel;
	thirdPicture->setPixmap(QPixmap(":/resources/tutoriel/parametres_mode.jpg"));
	QLabel * thirdText = new QLabel("Indicateur des param" + QString(232) + "tres de tir du joueur");
	thirdText->setWordWrap(true);

	thirdRow->addWidget(thirdText, 0, Qt::AlignLeft);
	thirdRow->addWidget(thirdPicture, 0, Qt::AlignRight);

	QHBoxLayout * fourthRow = new QHBoxLayout;
	QLabel * fourthText = new QLabel("Dans le menu de nouvelle partie, il est possible de s" + QString(233) + "lectionner un mode de jeu entre \"un joueur\" et \"deux joueurs\". Le mode simple joueur inclut une intelligence pour l'adversaire." + QString("Aussi dans la cr" + QString(233) + "ation d'une nouvelle partie, il est possible de s" + QString(233) + "lectionner le difficult" + QString(233) + ", qui ajuste premi" + QString(232) + "rement le niveau de difficult" + QString(233) + " du terrain."));
	fourthText->setWordWrap(true);

	fourthRow->addWidget(fourthText, 0, Qt::AlignLeft);

	window->addLayout(firstRow);
	window->addLayout(secondRow);
	window->addLayout(thirdRow);
	window->addLayout(fourthRow);

	setLayout(window);

}

FenetreVersion::FenetreVersion()
{
	setWindowTitle("Version");
    setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
	setFixedSize(500, 140);

	QVBoxLayout * vertical = new QVBoxLayout();
	m_ligne1 = new QLabel("SCORCH VERSION 0.5");
	m_ligne2 = new QLabel("Derniere mise a jour : 2016-04-04");
	m_ligne3 = new QLabel("Developpe par l'equipe P19 de l'U de S");
	m_ligne4 = new QLabel("Les programmeurs ayant particip" + QString(233) + " " + QString(224) + " la cr" + QString(233) + "ation de Scorch");
	m_ligne5 = new QLabel("Emile Fugulin, Jean-Philippe Fournier, Julien Larochelle, Philippe Spino");

	m_ligne1->setFont(QFont("OCR A extented",10));
	m_ligne2->setFont(QFont("fantasque sans mono",10));
	m_ligne3->setFont(QFont("fantasque sans mono",10));
	m_ligne4->setFont(QFont("fantasque sans mono",10));
	m_ligne5->setFont(QFont("fantasque sans mono",10));

	vertical->addWidget(m_ligne1, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne2, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne3, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne4, 1, Qt::AlignCenter);
	vertical->addWidget(m_ligne5, 1, Qt::AlignCenter);
	setLayout(vertical);
}
<|endoftext|>


<commit_before>#include "hyperclient/hyperclient.h"
#include <iostream>

using namespace std;

int main()
{
    cout<<"test start "<<endl;
    //define hyper attribute
    hyperclient_attribute test_attr[3];

    test_attr[0].attr = "phone";
    test_attr[0].value = "123455";
    test_attr[0].value_sz = strlen(test_attr[0].value);
    test_attr[0].datatype = HYPERDATATYPE_STRING;

    test_attr[1].attr = "last";
    test_attr[1].value = "Yang";
    test_attr[1].value_sz = strlen(test_attr[1].value);
    test_attr[1].datatype = HYPERDATATYPE_STRING;

    test_attr[2].attr = "first";
    test_attr[2].value = "Fred";
    test_attr[2].value_sz = strlen(test_attr[2].value);
    test_attr[2].datatype = HYPERDATATYPE_STRING;

    hyperclient_returncode retcode;
    const char *key = "adamyang";
    hyperclient test_client("127.0.0.1", 1234);
    const char *trigger = "testtrigger";

    int64_t ret = test_client.tri_put("phonebook", key, strlen(key), trigger, strlen(trigger), &retcode, test_attr, 3);

    hyperclient_returncode loop_status;
    int64_t loop_id = test_client.loop(-1, &loop_status);

    if(ret != loop_id)
    {
        cout <<"exit here 1"<<endl;
        exit(1);
    }

    cout<<"put ret is "<<ret<<" return code is "<<retcode<<endl;

    //define the container for the attribute get

    const char *key2 = "andywang";

    hyperclient_attribute *test_get_attr;
    size_t get_size = 0;
    ret = test_client.tri_get("phonebook", key2, strlen(key2), trigger, strlen(trigger), &retcode, &test_get_attr, &get_size);

    loop_id = test_client.loop(-1, &loop_status);

    if(ret != loop_id)
    {
        cout <<"exit here 2"<<endl;
        exit(1);
    }

    if(get_size!=0)
    {
        cout<<"we get something "<<endl;
        for(int i=0; i<get_size; i++)
        {
            cout<<"attr "<<i<<": "<<test_get_attr[i].attr<<", value : "<<string(test_get_attr[i].value, test_get_attr[i].value_sz)<<endl;
        }
    }
    else
    {
        cout<<"we get nothing"<<endl;
    }

    cout<<"get ret is "<<ret<<" return code is "<<retcode<<endl;

    return 0;
}
<commit_msg>tested search<commit_after>#include "hyperclient/hyperclient.h"
#include <iostream>

using namespace std;

int main()
{
    cout<<"test start "<<endl;

    //first we put a entry into the keystore
    hyperclient_attribute test_attr[3];

    test_attr[0].attr = "phone";
    test_attr[0].value = "123455";
    test_attr[0].value_sz = strlen(test_attr[0].value);
    test_attr[0].datatype = HYPERDATATYPE_STRING;

    test_attr[1].attr = "last";
    test_attr[1].value = "Yang";
    test_attr[1].value_sz = strlen(test_attr[1].value);
    test_attr[1].datatype = HYPERDATATYPE_STRING;

    test_attr[2].attr = "first";
    test_attr[2].value = "Fred";
    test_attr[2].value_sz = strlen(test_attr[2].value);
    test_attr[2].datatype = HYPERDATATYPE_STRING;

    hyperclient_returncode retcode;
    const char *key = "adamyang";
    hyperclient test_client("127.0.0.1", 1234);
    const char *trigger = "testtrigger";

    int64_t ret = test_client.tri_put("phonebook", key, strlen(key), trigger, strlen(trigger), &retcode, test_attr, 3);

    hyperclient_returncode loop_status;
    int64_t loop_id = test_client.loop(-1, &loop_status);

    if(ret != loop_id)
    {
        cout <<"exit here 1"<<endl;
        exit(1);
    }

    cout<<"put ret is "<<ret<<" return code is "<<retcode<<endl;

    //define the container for the attribute get
    //we then use tri_get to get the data out, which will returned triggered output
    const char *key2 = "andywang";

    hyperclient_attribute *test_get_attr;
    size_t get_size = 0;
    ret = test_client.tri_get("phonebook", key2, strlen(key2), trigger, strlen(trigger), &retcode, &test_get_attr, &get_size);

    loop_id = test_client.loop(-1, &loop_status);

    if(ret != loop_id)
    {
        cout <<"exit here 2"<<endl;
        exit(1);
    }

    if(get_size!=0)
    {
        cout<<"we get something "<<endl;
        for(int i=0; i<get_size; i++)
        {
            cout<<"attr "<<i<<": "<<test_get_attr[i].attr<<", value : "<<string(test_get_attr[i].value, test_get_attr[i].value_sz)<<endl;
        }
    }
    else
    {
        cout<<"we get nothing"<<endl;
    }

    cout<<"get ret is "<<ret<<" return code is "<<retcode<<endl;

    //This part will be used to test the search function
    hyperclient_attribute search_attr[1];
    search_attr[0].attr = "first";
    search_attr[0].value = "Fred";
    search_attr[0].value_sz = strlen(search_attr[0].value);
    search_attr[0].datatype = HYPERDATATYPE_STRING;
    ret = test_client.search("phonebook", search_attr, 1, NULL, 0, &retcode, &test_get_attr, &get_size);

    while(1)
    {
        loop_id = test_client.loop(-1, &loop_status);
        if(loop_id < 0)
        {
            cout<<"we break because loop_id < 0"<<endl;
            break;
        }
        if(retcode == HYPERCLIENT_SEARCHDONE)
        {
            cout<<"we break because we finished search"<<endl;
            break;
        }
        if(loop_id == ret)
        {
            cout<<"we get something, the retcode is "<<loop_status<<endl;
            for(int i=0; i<get_size; i++)
            {
                cout<<"search out: attr "<<i<<": "<<test_get_attr[i].attr<<", value : "<<string(test_get_attr[i].value, test_get_attr[i].value_sz)<<endl;
            }
        }
    }

    if(loop_status != HYPERCLIENT_SEARCHDONE)
        cout<<"search error happens loop_status is "<<loop_status<<endl;

    return 0;
}
<|endoftext|>


<commit_before>#include "StageSelectState.h"

#include "MenuState.h"
#include "EditState.h"
#include "CharacterSelectState.h"
#include "Game.h"
#include <string>

#include <cstdlib>

using std::to_string;

StageSelectState::StageSelectState(bool cgo_to_edit) {
	planet = Sprite("stage_select/planet.png", 8, FRAME_TIME);
	planet.set_scale(1.5);
	go_to_edit = cgo_to_edit;
	n_stages = 2 + (go_to_edit ? 0 : 1);

	blocked = Sound("menu/sound/cancel.ogg");
	selected = Sound("menu/sound/select.ogg");
	changed = Sound("menu/sound/cursor.ogg");

	for(int i=0;i<N_BACKGROUNDS;i++){
		background[i] = Sprite("stage_select/background_" + to_string(i) + ".png");
	}

	for(int i=0;i<n_stages;i++){
		stage[i] = Sprite("stage_select/stage_" + to_string(i + 1) + ".png");
	}

	InputManager::get_instance()->map_keyboard_to_joystick(InputManager::MENU_MODE);
}

void StageSelectState::update(float delta) {
	process_input();

	InputManager * input_manager = InputManager::get_instance();

	if(input_manager->quit_requested()){
		m_quit_requested = true;
		return;
	}

	if(pressed[B] || pressed[SELECT]) {
		selected.play();
		m_quit_requested = true;
		Game::get_instance().push(new MenuState(true));
		return;
	}

	if(pressed[LEFT]) {
		selected.play();
		update_stage_select(-1);
	}

	if(pressed[RIGHT]) {
		selected.play();
		update_stage_select(1);
	}

	if(pressed[A] || pressed[START]) {
		selected.play();
		m_quit_requested = true;
		if(stage_select == 2){
			srand(clock());
			stage_select = rand() % (n_stages - (go_to_edit ? 0 : 1));
		}
		if(go_to_edit)
			Game::get_instance().push(new EditState(to_string(stage_select + 1)));
		else
			Game::get_instance().push(new CharacterSelectState(to_string(stage_select + 1)));

	}

	planet.update(delta);
}

void StageSelectState::render() {
	background[0].render();
	planet.render(640 - planet.get_width() / 2, 360 - planet.get_height() / 2);
	background[1].render();

	for(int i=0;i<n_stages;i++){
		stage[i].render(i * 780 - stage_select * 780);
	}
}

void StageSelectState::update_stage_select(int increment) {
	stage_select += increment;
	if(stage_select < 0) stage_select = 0;
	if(stage_select > n_stages - 1) stage_select = n_stages - 1;
}

void StageSelectState::process_input(){
	InputManager * input_manager = InputManager::get_instance();

	//MENU BUTTONS HERE
	vector< pair<int, int> > joystick_buttons = {
		ii(LEFT, InputManager::LEFT),
		ii(RIGHT, InputManager::RIGHT),
		ii(A, InputManager::A),
		ii(B, InputManager::B),
		ii(START, InputManager::START),
		ii(SELECT, InputManager::SELECT)
	};

	for(ii button : joystick_buttons){
		pressed[button.first] = input_manager->joystick_button_press(button.second, 0);
	}
}

void StageSelectState::pause() {

}

void StageSelectState::resume() {

}
<commit_msg>Add cancel sound to stage selection<commit_after>#include "StageSelectState.h"

#include "MenuState.h"
#include "EditState.h"
#include "CharacterSelectState.h"
#include "Game.h"
#include <string>

#include <cstdlib>

using std::to_string;

StageSelectState::StageSelectState(bool cgo_to_edit) {
	planet = Sprite("stage_select/planet.png", 8, FRAME_TIME);
	planet.set_scale(1.5);
	go_to_edit = cgo_to_edit;
	n_stages = 2 + (go_to_edit ? 0 : 1);

	blocked = Sound("menu/sound/cancel.ogg");
	selected = Sound("menu/sound/select.ogg");
	changed = Sound("menu/sound/cursor.ogg");

	for(int i=0;i<N_BACKGROUNDS;i++){
		background[i] = Sprite("stage_select/background_" + to_string(i) + ".png");
	}

	for(int i=0;i<n_stages;i++){
		stage[i] = Sprite("stage_select/stage_" + to_string(i + 1) + ".png");
	}

	InputManager::get_instance()->map_keyboard_to_joystick(InputManager::MENU_MODE);
}

void StageSelectState::update(float delta) {
	process_input();

	InputManager * input_manager = InputManager::get_instance();

	if(input_manager->quit_requested()){
		m_quit_requested = true;
		return;
	}

	if(pressed[B] || pressed[SELECT]) {
		selected.play();
		m_quit_requested = true;
		Game::get_instance().push(new MenuState(true));
		return;
	}

	if(pressed[LEFT]) {
		update_stage_select(-1);
	}

	if(pressed[RIGHT]) {
		update_stage_select(1);
	}

	if(pressed[A] || pressed[START]) {
		selected.play();
		m_quit_requested = true;
		if(stage_select == 2){
			srand(clock());
			stage_select = rand() % (n_stages - (go_to_edit ? 0 : 1));
		}
		if(go_to_edit)
			Game::get_instance().push(new EditState(to_string(stage_select + 1)));
		else
			Game::get_instance().push(new CharacterSelectState(to_string(stage_select + 1)));

	}

	planet.update(delta);
}

void StageSelectState::render() {
	background[0].render();
	planet.render(640 - planet.get_width() / 2, 360 - planet.get_height() / 2);
	background[1].render();

	for(int i=0;i<n_stages;i++){
		stage[i].render(i * 780 - stage_select * 780);
	}
}

void StageSelectState::update_stage_select(int increment) {
	stage_select += increment;
	if(stage_select < 0){
		blocked.play();
		stage_select = 0;
	}
	else if(stage_select > n_stages - 1){
		blocked.play();
		stage_select = n_stages - 1;
	}
	else{
		selected.play();
	}
}

void StageSelectState::process_input(){
	InputManager * input_manager = InputManager::get_instance();

	//MENU BUTTONS HERE
	vector< pair<int, int> > joystick_buttons = {
		ii(LEFT, InputManager::LEFT),
		ii(RIGHT, InputManager::RIGHT),
		ii(A, InputManager::A),
		ii(B, InputManager::B),
		ii(START, InputManager::START),
		ii(SELECT, InputManager::SELECT)
	};

	for(ii button : joystick_buttons){
		pressed[button.first] = input_manager->joystick_button_press(button.second, 0);
	}
}

void StageSelectState::pause() {

}

void StageSelectState::resume() {

}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCloseEvent>
#include <QMimeData>
#include <QUrl>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), speedDialMemory(0),
    settings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()) {

    ui->setupUi(this);
    ui->PauseResume_Button->setFocus();

    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionAbout_Qt, SIGNAL(triggered()), QApplication::instance(), SLOT(aboutQt()));

    connect(ui->actionCenter_All,                       SIGNAL(triggered()),        &ui->centralwidget->universe,   SLOT(centerAll()));
    connect(ui->actionDelete,                           SIGNAL(triggered()),        &ui->centralwidget->universe,   SLOT(deleteSelected()));
    connect(ui->actionDelete_Escapees,                  SIGNAL(triggered()),        &ui->centralwidget->universe,   SLOT(deleteEscapees()));
    connect(ui->actionInteractive_Planet_Placement,     SIGNAL(triggered()),        ui->centralwidget,              SLOT(beginInteractiveCreation()));
    connect(ui->actionInteractive_Planet_Placement,     SIGNAL(triggered(bool)),    ui->toggleFiringModePushButton, SLOT(setChecked(bool)));
    connect(ui->actionInteractive_Orbital_Placement,    SIGNAL(triggered()),        ui->centralwidget,              SLOT(beginOrbitalCreation()));
    connect(ui->toggleFiringModePushButton,             SIGNAL(toggled(bool)),      ui->centralwidget,              SLOT(enableFiringMode(bool)));
    connect(ui->actionTake_Screenshot,                  SIGNAL(triggered()),        ui->centralwidget,              SLOT(takeScreenshot()));
    connect(ui->gridRangeSpinBox,                       SIGNAL(valueChanged(int)),  ui->centralwidget,              SLOT(setGridRange(int)));
    connect(ui->actionPrevious_Planet,                  SIGNAL(triggered()),        ui->centralwidget,              SLOT(followPrevious()));
    connect(ui->actionNext_Planet,                      SIGNAL(triggered()),        ui->centralwidget,              SLOT(followNext()));

    ui->statusbar->addPermanentWidget(planetCountLabel = new QLabel("0 planets", ui->statusbar));
    ui->statusbar->addPermanentWidget(fpsLabel = new QLabel(ui->statusbar));
    ui->statusbar->addPermanentWidget(averagefpsLabel = new QLabel(ui->statusbar));
    fpsLabel->setFixedWidth(120);
    planetCountLabel->setFixedWidth(120);
    averagefpsLabel->setFixedWidth(160);

    connect(&ui->centralwidget->universe,   SIGNAL(updatePlanetCountMessage(QString)),      planetCountLabel, SLOT(setText(QString)));
    connect(ui->centralwidget,              SIGNAL(updateFPSStatusMessage(QString)),        fpsLabel,         SLOT(setText(QString)));
    connect(ui->centralwidget,              SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel,  SLOT(setText(QString)));

    ui->menubar->insertMenu(ui->menuHelp->menuAction(), createPopupMenu())->setText(tr("Tools"));

    ui->firingSettings_DockWidget->hide();
    ui->randomSettings_DockWidget->hide();

    const QStringList &arguments = QApplication::arguments();

    foreach (const QString &argument, arguments) {
        if(QFileInfo(argument).filePath() != QApplication::applicationFilePath() && ui->centralwidget->universe.load(argument)){
            break;
        }
    }

    settings.beginGroup("MainWindow");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("state").toByteArray());
    settings.endGroup();
    settings.beginGroup("Graphics");
    ui->actionGrid->setChecked(settings.value("DrawGrid").toBool());
    ui->actionDraw_Paths->setChecked(settings.value("DrawPaths").toBool());
    settings.endGroup();

    setAcceptDrops(true);
}

MainWindow::~MainWindow(){
    settings.beginGroup("MainWindow");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState());
    settings.endGroup();
    settings.beginGroup("Graphics");
    settings.setValue("DrawGrid", ui->actionGrid->isChecked());
    settings.setValue("DrawPaths", ui->actionDraw_Paths->isChecked());
    settings.endGroup();

    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *e){
    if(!ui->centralwidget->universe.isEmpty()){
        int result = QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"),
                                          QMessageBox::Yes | QMessageBox::Save | QMessageBox::No, QMessageBox::Yes);

        if(result == QMessageBox::No || (result == QMessageBox::Save && !on_actionSave_Simulation_triggered())){
            return e->ignore();
        }
    }
    e->accept();
}

void MainWindow::on_createPlanet_PushButton_clicked(){
    ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet(
                Planet(QVector3D(ui->newPosX_SpinBox->value(),      ui->newPosY_SpinBox->value(),      ui->newPosZ_SpinBox->value()),
                       QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * PlanetsUniverse::velocityfac,
                       ui->newMass_SpinBox->value()));
}

void MainWindow::on_actionClear_Velocity_triggered(){
    if(ui->centralwidget->universe.isSelectedValid()){
        ui->centralwidget->universe.getSelected().velocity = QVector3D();
    }
}

void MainWindow::on_speed_Dial_valueChanged(int value){
    ui->centralwidget->universe.simspeed = float(value * speeddialmax) / ui->speed_Dial->maximum();
    ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed);
    if(ui->speed_Dial->value() == 0){
        ui->PauseResume_Button->setText(tr("Resume"));
        ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png"));
    }else{
        ui->PauseResume_Button->setText(tr("Pause"));
        ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png"));
    }
}

void MainWindow::on_PauseResume_Button_clicked(){
    if(ui->speed_Dial->value() == 0){
        ui->speed_Dial->setValue(speedDialMemory);
    }else{
        speedDialMemory = ui->speed_Dial->value();
        ui->speed_Dial->setValue(0);
    }
}

void MainWindow::on_FastForward_Button_clicked(){
    if(ui->speed_Dial->value() == ui->speed_Dial->maximum() || ui->speed_Dial->value() == 0){
        ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
    }else{
        ui->speed_Dial->setValue(ui->speed_Dial->value() * 2);
    }
}

void MainWindow::on_actionNew_Simulation_triggered(){
    if(!ui->centralwidget->universe.isEmpty() && QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"),
                                                                      QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){
        ui->centralwidget->universe.deleteAll();
    }
}

void MainWindow::on_actionOpen_Simulation_triggered(){
    QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)"));
    if(!filename.isEmpty()){
        ui->centralwidget->universe.load(filename);
    }
}

void MainWindow::on_actionAppend_Simulation_triggered(){
    QString filename = QFileDialog::getOpenFileName(this, tr("Append Simulation"), "", tr("Simulation files (*.xml)"));
    if(!filename.isEmpty()){
        ui->centralwidget->universe.load(filename, false);
    }
}

bool MainWindow::on_actionSave_Simulation_triggered(){
    if(!ui->centralwidget->universe.isEmpty()){
        QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)"));

        if(!filename.isEmpty()){
            return ui->centralwidget->universe.save(filename);
        }
    }else{
        QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!"));
    }
    return false;
}

void MainWindow::on_actionFollow_Selection_triggered(){
    ui->centralwidget->following = ui->centralwidget->universe.selected;
    ui->centralwidget->followState = PlanetsWidget::Single;
}

void MainWindow::on_actionClear_Follow_triggered(){
    ui->centralwidget->following = 0;
    ui->centralwidget->followState = PlanetsWidget::FollowNone;
}

void MainWindow::on_actionPlain_Average_triggered(){
    ui->centralwidget->followState = PlanetsWidget::PlainAverage;
}

void MainWindow::on_actionWeighted_Average_triggered(){
    ui->centralwidget->followState = PlanetsWidget::WeightedAverage;
}

void MainWindow::on_actionAbout_triggered(){
    QMessageBox::about(this, tr("About Planets3D"),
                       tr(""
                          "
Planets3D is a simple 3D gravitational simulator
"
                          "
Website: github.com/chipgw/planets-3d
"
                          "
Build Info:

"
                          "
Git sha1: %2
"
                          "
Build type: %3
"
                          "
Compiler: %4
"
                          "
CMake Version: %5
"
                          "
")
                       .arg(version::git_revision)
                       .arg(version::build_type)
                       .arg(version::compiler)
                       .arg(version::cmake_version));
}

void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){
    ui->centralwidget->universe.stepsPerFrame = value;
}

void MainWindow::on_trailLengthSpinBox_valueChanged(int value){
    Planet::pathLength = value;
}

void MainWindow::on_planetScaleDoubleSpinBox_valueChanged(double value){
    ui->centralwidget->drawScale = value;
}

void MainWindow::on_trailRecordDistanceDoubleSpinBox_valueChanged(double value){
    Planet::pathRecordDistance = value * value;
}

void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){
    ui->centralwidget->firingSpeed = value * PlanetsUniverse::velocityfac;
}

void MainWindow::on_firingMassSpinBox_valueChanged(int value){
    ui->centralwidget->firingMass = value;
}

void MainWindow::on_actionGrid_toggled(bool value){
    ui->centralwidget->drawGrid = value;
}

void MainWindow::on_actionDraw_Paths_toggled(bool value){
    ui->centralwidget->drawPlanetTrails = value;
}

void MainWindow::on_actionPlanet_Colors_toggled(bool value){
    ui->centralwidget->drawPlanetColors = value;
}

void MainWindow::on_actionHide_Planets_toggled(bool value){
    ui->centralwidget->hidePlanets = value;

    if(value){
        ui->actionDraw_Paths->setChecked(true);
    }
}

void MainWindow::on_generateRandomPushButton_clicked(){
    ui->centralwidget->universe.generateRandom(ui->randomAmountSpinBox->value(), ui->randomRangeDoubleSpinBox->value(),
                                               ui->randomSpeedDoubleSpinBox->value() * PlanetsUniverse::velocityfac,
                                               ui->randomMassDoubleSpinBox->value());
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event){
    if(event->mimeData()->hasUrls()){
        foreach(QUrl url, event->mimeData()->urls()){
            QFileInfo info(url.toLocalFile());
            if(info.exists()){
                return event->acceptProposedAction();
            }
        }
    }
}

void MainWindow::dropEvent(QDropEvent *event){
    if(event->mimeData()->hasUrls()){
        foreach(QUrl url, event->mimeData()->urls()){
            if(ui->centralwidget->universe.load(url.toLocalFile())){
                return event->acceptProposedAction();
            }
        }
    }
}

bool MainWindow::event(QEvent *event){
    switch(event->type()) {
    case QEvent::WindowActivate:
        if(ui->centralwidget->universe.simspeed <= 0.0f){
            on_PauseResume_Button_clicked();
        }
        break;
    case QEvent::WindowDeactivate:
        if(ui->centralwidget->universe.simspeed > 0.0f){
            on_PauseResume_Button_clicked();
        }
        break;
    default: break;
    }
    return QMainWindow::event(event);
}

const int MainWindow::speeddialmax = 32;
<commit_msg>added trail settings and steps per frame to settings file. (they have to be manually added for now.)<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCloseEvent>
#include <QMimeData>
#include <QUrl>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), speedDialMemory(0),
    settings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()) {

    ui->setupUi(this);
    ui->PauseResume_Button->setFocus();

    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionAbout_Qt, SIGNAL(triggered()), QApplication::instance(), SLOT(aboutQt()));

    connect(ui->actionCenter_All,                       SIGNAL(triggered()),        &ui->centralwidget->universe,   SLOT(centerAll()));
    connect(ui->actionDelete,                           SIGNAL(triggered()),        &ui->centralwidget->universe,   SLOT(deleteSelected()));
    connect(ui->actionDelete_Escapees,                  SIGNAL(triggered()),        &ui->centralwidget->universe,   SLOT(deleteEscapees()));
    connect(ui->actionInteractive_Planet_Placement,     SIGNAL(triggered()),        ui->centralwidget,              SLOT(beginInteractiveCreation()));
    connect(ui->actionInteractive_Planet_Placement,     SIGNAL(triggered(bool)),    ui->toggleFiringModePushButton, SLOT(setChecked(bool)));
    connect(ui->actionInteractive_Orbital_Placement,    SIGNAL(triggered()),        ui->centralwidget,              SLOT(beginOrbitalCreation()));
    connect(ui->toggleFiringModePushButton,             SIGNAL(toggled(bool)),      ui->centralwidget,              SLOT(enableFiringMode(bool)));
    connect(ui->actionTake_Screenshot,                  SIGNAL(triggered()),        ui->centralwidget,              SLOT(takeScreenshot()));
    connect(ui->gridRangeSpinBox,                       SIGNAL(valueChanged(int)),  ui->centralwidget,              SLOT(setGridRange(int)));
    connect(ui->actionPrevious_Planet,                  SIGNAL(triggered()),        ui->centralwidget,              SLOT(followPrevious()));
    connect(ui->actionNext_Planet,                      SIGNAL(triggered()),        ui->centralwidget,              SLOT(followNext()));

    ui->statusbar->addPermanentWidget(planetCountLabel = new QLabel("0 planets", ui->statusbar));
    ui->statusbar->addPermanentWidget(fpsLabel = new QLabel(ui->statusbar));
    ui->statusbar->addPermanentWidget(averagefpsLabel = new QLabel(ui->statusbar));
    fpsLabel->setFixedWidth(120);
    planetCountLabel->setFixedWidth(120);
    averagefpsLabel->setFixedWidth(160);

    connect(&ui->centralwidget->universe,   SIGNAL(updatePlanetCountMessage(QString)),      planetCountLabel, SLOT(setText(QString)));
    connect(ui->centralwidget,              SIGNAL(updateFPSStatusMessage(QString)),        fpsLabel,         SLOT(setText(QString)));
    connect(ui->centralwidget,              SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel,  SLOT(setText(QString)));

    ui->menubar->insertMenu(ui->menuHelp->menuAction(), createPopupMenu())->setText(tr("Tools"));

    ui->firingSettings_DockWidget->hide();
    ui->randomSettings_DockWidget->hide();

    const QStringList &arguments = QApplication::arguments();

    foreach (const QString &argument, arguments) {
        if(QFileInfo(argument).filePath() != QApplication::applicationFilePath() && ui->centralwidget->universe.load(argument)){
            break;
        }
    }

    settings.beginGroup("MainWindow");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("state").toByteArray());
    settings.endGroup();
    settings.beginGroup("Graphics");
    ui->actionGrid->setChecked(settings.value("DrawGrid").toBool());
    ui->actionDraw_Paths->setChecked(settings.value("DrawPaths").toBool());

    /* These aren't auto-saved, so for the moment they must be manually added to the config file. */
    if(settings.contains("TrailLength")){
        ui->trailLengthSpinBox->setValue(settings.value("TrailLength").toInt());
    }
    if(settings.contains("TrailDelta")){
        ui->trailRecordDistanceDoubleSpinBox->setValue(settings.value("TrailDelta").toDouble());
    }
    settings.endGroup();

    if(settings.contains("StepsPerFrame")){
        ui->stepsPerFrameSpinBox->setValue(settings.value("StepsPerFrame").toInt());
    }

    setAcceptDrops(true);
}

MainWindow::~MainWindow(){
    settings.beginGroup("MainWindow");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState());
    settings.endGroup();
    settings.beginGroup("Graphics");
    settings.setValue("DrawGrid", ui->actionGrid->isChecked());
    settings.setValue("DrawPaths", ui->actionDraw_Paths->isChecked());
    settings.endGroup();

    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *e){
    if(!ui->centralwidget->universe.isEmpty()){
        int result = QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"),
                                          QMessageBox::Yes | QMessageBox::Save | QMessageBox::No, QMessageBox::Yes);

        if(result == QMessageBox::No || (result == QMessageBox::Save && !on_actionSave_Simulation_triggered())){
            return e->ignore();
        }
    }
    e->accept();
}

void MainWindow::on_createPlanet_PushButton_clicked(){
    ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet(
                Planet(QVector3D(ui->newPosX_SpinBox->value(),      ui->newPosY_SpinBox->value(),      ui->newPosZ_SpinBox->value()),
                       QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * PlanetsUniverse::velocityfac,
                       ui->newMass_SpinBox->value()));
}

void MainWindow::on_actionClear_Velocity_triggered(){
    if(ui->centralwidget->universe.isSelectedValid()){
        ui->centralwidget->universe.getSelected().velocity = QVector3D();
    }
}

void MainWindow::on_speed_Dial_valueChanged(int value){
    ui->centralwidget->universe.simspeed = float(value * speeddialmax) / ui->speed_Dial->maximum();
    ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed);
    if(ui->speed_Dial->value() == 0){
        ui->PauseResume_Button->setText(tr("Resume"));
        ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png"));
    }else{
        ui->PauseResume_Button->setText(tr("Pause"));
        ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png"));
    }
}

void MainWindow::on_PauseResume_Button_clicked(){
    if(ui->speed_Dial->value() == 0){
        ui->speed_Dial->setValue(speedDialMemory);
    }else{
        speedDialMemory = ui->speed_Dial->value();
        ui->speed_Dial->setValue(0);
    }
}

void MainWindow::on_FastForward_Button_clicked(){
    if(ui->speed_Dial->value() == ui->speed_Dial->maximum() || ui->speed_Dial->value() == 0){
        ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
    }else{
        ui->speed_Dial->setValue(ui->speed_Dial->value() * 2);
    }
}

void MainWindow::on_actionNew_Simulation_triggered(){
    if(!ui->centralwidget->universe.isEmpty() && QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"),
                                                                      QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){
        ui->centralwidget->universe.deleteAll();
    }
}

void MainWindow::on_actionOpen_Simulation_triggered(){
    QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)"));
    if(!filename.isEmpty()){
        ui->centralwidget->universe.load(filename);
    }
}

void MainWindow::on_actionAppend_Simulation_triggered(){
    QString filename = QFileDialog::getOpenFileName(this, tr("Append Simulation"), "", tr("Simulation files (*.xml)"));
    if(!filename.isEmpty()){
        ui->centralwidget->universe.load(filename, false);
    }
}

bool MainWindow::on_actionSave_Simulation_triggered(){
    if(!ui->centralwidget->universe.isEmpty()){
        QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)"));

        if(!filename.isEmpty()){
            return ui->centralwidget->universe.save(filename);
        }
    }else{
        QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!"));
    }
    return false;
}

void MainWindow::on_actionFollow_Selection_triggered(){
    ui->centralwidget->following = ui->centralwidget->universe.selected;
    ui->centralwidget->followState = PlanetsWidget::Single;
}

void MainWindow::on_actionClear_Follow_triggered(){
    ui->centralwidget->following = 0;
    ui->centralwidget->followState = PlanetsWidget::FollowNone;
}

void MainWindow::on_actionPlain_Average_triggered(){
    ui->centralwidget->followState = PlanetsWidget::PlainAverage;
}

void MainWindow::on_actionWeighted_Average_triggered(){
    ui->centralwidget->followState = PlanetsWidget::WeightedAverage;
}

void MainWindow::on_actionAbout_triggered(){
    QMessageBox::about(this, tr("About Planets3D"),
                       tr(""
                          "
Planets3D is a simple 3D gravitational simulator
"
                          "
Website: github.com/chipgw/planets-3d
"
                          "
Build Info:

"
                          "
Git sha1: %2
"
                          "
Build type: %3
"
                          "
Compiler: %4
"
                          "
CMake Version: %5
"
                          "
")
                       .arg(version::git_revision)
                       .arg(version::build_type)
                       .arg(version::compiler)
                       .arg(version::cmake_version));
}

void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){
    ui->centralwidget->universe.stepsPerFrame = value;
}

void MainWindow::on_trailLengthSpinBox_valueChanged(int value){
    Planet::pathLength = value;
}

void MainWindow::on_planetScaleDoubleSpinBox_valueChanged(double value){
    ui->centralwidget->drawScale = value;
}

void MainWindow::on_trailRecordDistanceDoubleSpinBox_valueChanged(double value){
    Planet::pathRecordDistance = value * value;
}

void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){
    ui->centralwidget->firingSpeed = value * PlanetsUniverse::velocityfac;
}

void MainWindow::on_firingMassSpinBox_valueChanged(int value){
    ui->centralwidget->firingMass = value;
}

void MainWindow::on_actionGrid_toggled(bool value){
    ui->centralwidget->drawGrid = value;
}

void MainWindow::on_actionDraw_Paths_toggled(bool value){
    ui->centralwidget->drawPlanetTrails = value;
}

void MainWindow::on_actionPlanet_Colors_toggled(bool value){
    ui->centralwidget->drawPlanetColors = value;
}

void MainWindow::on_actionHide_Planets_toggled(bool value){
    ui->centralwidget->hidePlanets = value;

    if(value){
        ui->actionDraw_Paths->setChecked(true);
    }
}

void MainWindow::on_generateRandomPushButton_clicked(){
    ui->centralwidget->universe.generateRandom(ui->randomAmountSpinBox->value(), ui->randomRangeDoubleSpinBox->value(),
                                               ui->randomSpeedDoubleSpinBox->value() * PlanetsUniverse::velocityfac,
                                               ui->randomMassDoubleSpinBox->value());
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event){
    if(event->mimeData()->hasUrls()){
        foreach(QUrl url, event->mimeData()->urls()){
            QFileInfo info(url.toLocalFile());
            if(info.exists()){
                return event->acceptProposedAction();
            }
        }
    }
}

void MainWindow::dropEvent(QDropEvent *event){
    if(event->mimeData()->hasUrls()){
        foreach(QUrl url, event->mimeData()->urls()){
            if(ui->centralwidget->universe.load(url.toLocalFile())){
                return event->acceptProposedAction();
            }
        }
    }
}

bool MainWindow::event(QEvent *event){
    switch(event->type()) {
    case QEvent::WindowActivate:
        if(ui->centralwidget->universe.simspeed <= 0.0f){
            on_PauseResume_Button_clicked();
        }
        break;
    case QEvent::WindowDeactivate:
        if(ui->centralwidget->universe.simspeed > 0.0f){
            on_PauseResume_Button_clicked();
        }
        break;
    default: break;
    }
    return QMainWindow::event(event);
}

const int MainWindow::speeddialmax = 32;
<|endoftext|>


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

#include "base/file_util_proxy.h"

#include <map>

#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/platform_file.h"
#include "base/scoped_temp_dir.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

class FileUtilProxyTest : public testing::Test {
 public:
  FileUtilProxyTest()
      : message_loop_(MessageLoop::TYPE_IO),
        file_thread_("FileUtilProxyTestFileThread"),
        error_(PLATFORM_FILE_OK),
        created_(false),
        file_(kInvalidPlatformFileValue),
        bytes_written_(-1),
        weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {}

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(dir_.CreateUniqueTempDir());
    ASSERT_TRUE(file_thread_.Start());
  }

  virtual void TearDown() OVERRIDE {
    if (file_ != kInvalidPlatformFileValue)
      ClosePlatformFile(file_);
  }

  void DidFinish(PlatformFileError error) {
    error_ = error;
    MessageLoop::current()->Quit();
  }

  void DidCreateOrOpen(PlatformFileError error,
                       PassPlatformFile file,
                       bool created) {
    error_ = error;
    file_ = file.ReleaseValue();
    created_ = created;
    MessageLoop::current()->Quit();
  }

  void DidCreateTemporary(PlatformFileError error,
                          PassPlatformFile file,
                          const FilePath& path) {
    error_ = error;
    file_ = file.ReleaseValue();
    path_ = path;
    MessageLoop::current()->Quit();
  }

  void DidGetFileInfo(PlatformFileError error,
                      const PlatformFileInfo& file_info) {
    error_ = error;
    file_info_ = file_info;
    MessageLoop::current()->Quit();
  }

  void DidRead(PlatformFileError error,
               const char* data,
               int bytes_read) {
    error_ = error;
    buffer_.resize(bytes_read);
    memcpy(&buffer_[0], data, bytes_read);
    MessageLoop::current()->Quit();
  }

  void DidWrite(PlatformFileError error,
                int bytes_written) {
    error_ = error;
    bytes_written_ = bytes_written;
    MessageLoop::current()->Quit();
  }

 protected:
  PlatformFile GetTestPlatformFile(int flags) {
    if (file_ != kInvalidPlatformFileValue)
      return file_;
    bool created;
    PlatformFileError error;
    file_ = CreatePlatformFile(test_path(), flags, &created, &error);
    EXPECT_EQ(PLATFORM_FILE_OK, error);
    EXPECT_NE(kInvalidPlatformFileValue, file_);
    return file_;
  }

  TaskRunner* file_task_runner() const {
    return file_thread_.message_loop_proxy().get();
  }
  const FilePath& test_dir_path() const { return dir_.path(); }
  const FilePath test_path() const { return dir_.path().AppendASCII("test"); }

  MessageLoop message_loop_;
  Thread file_thread_;

  ScopedTempDir dir_;
  PlatformFileError error_;
  bool created_;
  PlatformFile file_;
  FilePath path_;
  PlatformFileInfo file_info_;
  std::vector<char> buffer_;
  int bytes_written_;
  WeakPtrFactory<FileUtilProxyTest> weak_factory_;
};

TEST_F(FileUtilProxyTest, CreateOrOpen_Create) {
  FileUtilProxy::CreateOrOpen(
      file_task_runner(),
      test_path(),
      PLATFORM_FILE_CREATE | PLATFORM_FILE_READ,
      Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_TRUE(created_);
  EXPECT_NE(kInvalidPlatformFileValue, file_);
  EXPECT_TRUE(file_util::PathExists(test_path()));
}

TEST_F(FileUtilProxyTest, CreateOrOpen_Open) {
  // Creates a file.
  file_util::WriteFile(test_path(), NULL, 0);
  ASSERT_TRUE(file_util::PathExists(test_path()));

  // Opens the created file.
  FileUtilProxy::CreateOrOpen(
      file_task_runner(),
      test_path(),
      PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
      Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_FALSE(created_);
  EXPECT_NE(kInvalidPlatformFileValue, file_);
}

TEST_F(FileUtilProxyTest, CreateOrOpen_OpenNonExistent) {
  FileUtilProxy::CreateOrOpen(
      file_task_runner(),
      test_path(),
      PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
      Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_ERROR_NOT_FOUND, error_);
  EXPECT_FALSE(created_);
  EXPECT_EQ(kInvalidPlatformFileValue, file_);
  EXPECT_FALSE(file_util::PathExists(test_path()));
}

TEST_F(FileUtilProxyTest, Close) {
  // Creates a file.
  PlatformFile file = GetTestPlatformFile(
      PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);

#if defined(OS_WIN)
  // This fails on Windows if the file is not closed.
  EXPECT_FALSE(file_util::Move(test_path(),
                               test_dir_path().AppendASCII("new")));
#endif

  FileUtilProxy::Close(
      file_task_runner(),
      file,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);

  // Now it should pass on all platforms.
  EXPECT_TRUE(file_util::Move(test_path(), test_dir_path().AppendASCII("new")));
}

TEST_F(FileUtilProxyTest, CreateTemporary) {
  FileUtilProxy::CreateTemporary(
      file_task_runner(), 0 /* additional_file_flags */,
      Bind(&FileUtilProxyTest::DidCreateTemporary, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_TRUE(file_util::PathExists(path_));
  EXPECT_NE(kInvalidPlatformFileValue, file_);

  // The file should be writable.
#if defined(OS_WIN)
   HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
   OVERLAPPED overlapped = {0};
   overlapped.hEvent = hEvent;
   DWORD bytes_written;
   if (!::WriteFile(file_, "test", 4, &bytes_written, &overlapped)) {
     // Temporary file is created with ASYNC flag, so WriteFile may return 0
     // with ERROR_IO_PENDING.
     EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
     GetOverlappedResult(file_, &overlapped, &bytes_written, TRUE);
   }
   EXPECT_EQ(4, bytes_written);
#else
  // On POSIX ASYNC flag does not affect synchronous read/write behavior.
  EXPECT_EQ(4, WritePlatformFile(file_, 0, "test", 4));
#endif
  EXPECT_TRUE(ClosePlatformFile(file_));
  file_ = kInvalidPlatformFileValue;

  // Make sure the written data can be read from the returned path.
  std::string data;
  EXPECT_TRUE(file_util::ReadFileToString(path_, &data));
  EXPECT_EQ("test", data);
}

TEST_F(FileUtilProxyTest, GetFileInfo_File) {
  // Setup.
  ASSERT_EQ(4, file_util::WriteFile(test_path(), "test", 4));
  PlatformFileInfo expected_info;
  file_util::GetFileInfo(test_path(), &expected_info);

  // Run.
  FileUtilProxy::GetFileInfo(
      file_task_runner(),
      test_path(),
      Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(expected_info.size, file_info_.size);
  EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
  EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
  EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
  EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
  EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}

TEST_F(FileUtilProxyTest, GetFileInfo_Directory) {
  // Setup.
  ASSERT_TRUE(file_util::CreateDirectory(test_path()));
  PlatformFileInfo expected_info;
  file_util::GetFileInfo(test_path(), &expected_info);

  // Run.
  FileUtilProxy::GetFileInfo(
      file_task_runner(),
      test_path(),
      Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(expected_info.size, file_info_.size);
  EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
  EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
  EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
  EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
  EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}

TEST_F(FileUtilProxyTest, Read) {
  // Setup.
  const char expected_data[] = "bleh";
  int expected_bytes = arraysize(expected_data);
  ASSERT_EQ(expected_bytes,
            file_util::WriteFile(test_path(), expected_data, expected_bytes));

  // Run.
  FileUtilProxy::Read(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_READ),
      0,  // offset
      128,
      Bind(&FileUtilProxyTest::DidRead, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(expected_bytes, static_cast<int>(buffer_.size()));
  for (size_t i = 0; i < buffer_.size(); ++i) {
    EXPECT_EQ(expected_data[i], buffer_[i]);
  }
}

TEST_F(FileUtilProxyTest, WriteAndFlush) {
  const char data[] = "foo!";
  int data_bytes = ARRAYSIZE_UNSAFE(data);
  PlatformFile file = GetTestPlatformFile(
      PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);

  FileUtilProxy::Write(
      file_task_runner(),
      file,
      0,  // offset
      data,
      data_bytes,
      Bind(&FileUtilProxyTest::DidWrite, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(data_bytes, bytes_written_);

  // Flush the written data.  (So that the following read should always
  // succeed.  On some platforms it may work with or without this flush.)
  FileUtilProxy::Flush(
      file_task_runner(),
      file,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);

  // Verify the written data.
  char buffer[10];
  EXPECT_EQ(data_bytes, file_util::ReadFile(test_path(), buffer, data_bytes));
  for (int i = 0; i < data_bytes; ++i) {
    EXPECT_EQ(data[i], buffer[i]);
  }
}

TEST_F(FileUtilProxyTest, Touch) {
  Time last_accessed_time = Time::Now() - TimeDelta::FromDays(12345);
  Time last_modified_time = Time::Now() - TimeDelta::FromHours(98765);

  FileUtilProxy::Touch(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_CREATE |
                          PLATFORM_FILE_WRITE |
                          PLATFORM_FILE_WRITE_ATTRIBUTES),
      last_accessed_time,
      last_modified_time,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);

  PlatformFileInfo info;
  file_util::GetFileInfo(test_path(), &info);

  // The returned values may only have the seconds precision, so we cast
  // the double values to int here.
  EXPECT_EQ(static_cast<int>(last_modified_time.ToDoubleT()),
            static_cast<int>(info.last_modified.ToDoubleT()));
  EXPECT_EQ(static_cast<int>(last_accessed_time.ToDoubleT()),
            static_cast<int>(info.last_accessed.ToDoubleT()));
}

TEST_F(FileUtilProxyTest, Truncate_Shrink) {
  // Setup.
  const char kTestData[] = "0123456789";
  ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
  PlatformFileInfo info;
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(10, info.size);

  // Run.
  FileUtilProxy::Truncate(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
      7,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(7, info.size);

  char buffer[7];
  EXPECT_EQ(7, file_util::ReadFile(test_path(), buffer, 7));
  int i = 0;
  for (; i < 7; ++i)
    EXPECT_EQ(kTestData[i], buffer[i]);
}

TEST_F(FileUtilProxyTest, Truncate_Expand) {
  // Setup.
  const char kTestData[] = "9876543210";
  ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
  PlatformFileInfo info;
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(10, info.size);

  // Run.
  FileUtilProxy::Truncate(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
      53,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(53, info.size);

  char buffer[53];
  EXPECT_EQ(53, file_util::ReadFile(test_path(), buffer, 53));
  int i = 0;
  for (; i < 10; ++i)
    EXPECT_EQ(kTestData[i], buffer[i]);
  for (; i < 53; ++i)
    EXPECT_EQ(0, buffer[i]);
}

}  // namespace base
<commit_msg>Fixed file leak in test.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util_proxy.h"

#include <map>

#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/platform_file.h"
#include "base/scoped_temp_dir.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

class FileUtilProxyTest : public testing::Test {
 public:
  FileUtilProxyTest()
      : message_loop_(MessageLoop::TYPE_IO),
        file_thread_("FileUtilProxyTestFileThread"),
        error_(PLATFORM_FILE_OK),
        created_(false),
        file_(kInvalidPlatformFileValue),
        bytes_written_(-1),
        weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {}

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(dir_.CreateUniqueTempDir());
    ASSERT_TRUE(file_thread_.Start());
  }

  virtual void TearDown() OVERRIDE {
    if (file_ != kInvalidPlatformFileValue)
      ClosePlatformFile(file_);
  }

  void DidFinish(PlatformFileError error) {
    error_ = error;
    MessageLoop::current()->Quit();
  }

  void DidCreateOrOpen(PlatformFileError error,
                       PassPlatformFile file,
                       bool created) {
    error_ = error;
    file_ = file.ReleaseValue();
    created_ = created;
    MessageLoop::current()->Quit();
  }

  void DidCreateTemporary(PlatformFileError error,
                          PassPlatformFile file,
                          const FilePath& path) {
    error_ = error;
    file_ = file.ReleaseValue();
    path_ = path;
    MessageLoop::current()->Quit();
  }

  void DidGetFileInfo(PlatformFileError error,
                      const PlatformFileInfo& file_info) {
    error_ = error;
    file_info_ = file_info;
    MessageLoop::current()->Quit();
  }

  void DidRead(PlatformFileError error,
               const char* data,
               int bytes_read) {
    error_ = error;
    buffer_.resize(bytes_read);
    memcpy(&buffer_[0], data, bytes_read);
    MessageLoop::current()->Quit();
  }

  void DidWrite(PlatformFileError error,
                int bytes_written) {
    error_ = error;
    bytes_written_ = bytes_written;
    MessageLoop::current()->Quit();
  }

 protected:
  PlatformFile GetTestPlatformFile(int flags) {
    if (file_ != kInvalidPlatformFileValue)
      return file_;
    bool created;
    PlatformFileError error;
    file_ = CreatePlatformFile(test_path(), flags, &created, &error);
    EXPECT_EQ(PLATFORM_FILE_OK, error);
    EXPECT_NE(kInvalidPlatformFileValue, file_);
    return file_;
  }

  TaskRunner* file_task_runner() const {
    return file_thread_.message_loop_proxy().get();
  }
  const FilePath& test_dir_path() const { return dir_.path(); }
  const FilePath test_path() const { return dir_.path().AppendASCII("test"); }

  MessageLoop message_loop_;
  Thread file_thread_;

  ScopedTempDir dir_;
  PlatformFileError error_;
  bool created_;
  PlatformFile file_;
  FilePath path_;
  PlatformFileInfo file_info_;
  std::vector<char> buffer_;
  int bytes_written_;
  WeakPtrFactory<FileUtilProxyTest> weak_factory_;
};

TEST_F(FileUtilProxyTest, CreateOrOpen_Create) {
  FileUtilProxy::CreateOrOpen(
      file_task_runner(),
      test_path(),
      PLATFORM_FILE_CREATE | PLATFORM_FILE_READ,
      Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_TRUE(created_);
  EXPECT_NE(kInvalidPlatformFileValue, file_);
  EXPECT_TRUE(file_util::PathExists(test_path()));
}

TEST_F(FileUtilProxyTest, CreateOrOpen_Open) {
  // Creates a file.
  file_util::WriteFile(test_path(), NULL, 0);
  ASSERT_TRUE(file_util::PathExists(test_path()));

  // Opens the created file.
  FileUtilProxy::CreateOrOpen(
      file_task_runner(),
      test_path(),
      PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
      Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_FALSE(created_);
  EXPECT_NE(kInvalidPlatformFileValue, file_);
}

TEST_F(FileUtilProxyTest, CreateOrOpen_OpenNonExistent) {
  FileUtilProxy::CreateOrOpen(
      file_task_runner(),
      test_path(),
      PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
      Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_ERROR_NOT_FOUND, error_);
  EXPECT_FALSE(created_);
  EXPECT_EQ(kInvalidPlatformFileValue, file_);
  EXPECT_FALSE(file_util::PathExists(test_path()));
}

TEST_F(FileUtilProxyTest, Close) {
  // Creates a file.
  PlatformFile file = GetTestPlatformFile(
      PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);

#if defined(OS_WIN)
  // This fails on Windows if the file is not closed.
  EXPECT_FALSE(file_util::Move(test_path(),
                               test_dir_path().AppendASCII("new")));
#endif

  FileUtilProxy::Close(
      file_task_runner(),
      file,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);

  // Now it should pass on all platforms.
  EXPECT_TRUE(file_util::Move(test_path(), test_dir_path().AppendASCII("new")));
}

TEST_F(FileUtilProxyTest, CreateTemporary) {
  FileUtilProxy::CreateTemporary(
      file_task_runner(), 0 /* additional_file_flags */,
      Bind(&FileUtilProxyTest::DidCreateTemporary, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_TRUE(file_util::PathExists(path_));
  EXPECT_NE(kInvalidPlatformFileValue, file_);

  // The file should be writable.
#if defined(OS_WIN)
   HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
   OVERLAPPED overlapped = {0};
   overlapped.hEvent = hEvent;
   DWORD bytes_written;
   if (!::WriteFile(file_, "test", 4, &bytes_written, &overlapped)) {
     // Temporary file is created with ASYNC flag, so WriteFile may return 0
     // with ERROR_IO_PENDING.
     EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
     GetOverlappedResult(file_, &overlapped, &bytes_written, TRUE);
   }
   EXPECT_EQ(4, bytes_written);
#else
  // On POSIX ASYNC flag does not affect synchronous read/write behavior.
  EXPECT_EQ(4, WritePlatformFile(file_, 0, "test", 4));
#endif
  EXPECT_TRUE(ClosePlatformFile(file_));
  file_ = kInvalidPlatformFileValue;

  // Make sure the written data can be read from the returned path.
  std::string data;
  EXPECT_TRUE(file_util::ReadFileToString(path_, &data));
  EXPECT_EQ("test", data);

  // Make sure we can & do delete the created file to prevent leaks on the bots.
  EXPECT_TRUE(file_util::Delete(path_, false));
}

TEST_F(FileUtilProxyTest, GetFileInfo_File) {
  // Setup.
  ASSERT_EQ(4, file_util::WriteFile(test_path(), "test", 4));
  PlatformFileInfo expected_info;
  file_util::GetFileInfo(test_path(), &expected_info);

  // Run.
  FileUtilProxy::GetFileInfo(
      file_task_runner(),
      test_path(),
      Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(expected_info.size, file_info_.size);
  EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
  EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
  EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
  EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
  EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}

TEST_F(FileUtilProxyTest, GetFileInfo_Directory) {
  // Setup.
  ASSERT_TRUE(file_util::CreateDirectory(test_path()));
  PlatformFileInfo expected_info;
  file_util::GetFileInfo(test_path(), &expected_info);

  // Run.
  FileUtilProxy::GetFileInfo(
      file_task_runner(),
      test_path(),
      Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(expected_info.size, file_info_.size);
  EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
  EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
  EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
  EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
  EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}

TEST_F(FileUtilProxyTest, Read) {
  // Setup.
  const char expected_data[] = "bleh";
  int expected_bytes = arraysize(expected_data);
  ASSERT_EQ(expected_bytes,
            file_util::WriteFile(test_path(), expected_data, expected_bytes));

  // Run.
  FileUtilProxy::Read(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_READ),
      0,  // offset
      128,
      Bind(&FileUtilProxyTest::DidRead, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(expected_bytes, static_cast<int>(buffer_.size()));
  for (size_t i = 0; i < buffer_.size(); ++i) {
    EXPECT_EQ(expected_data[i], buffer_[i]);
  }
}

TEST_F(FileUtilProxyTest, WriteAndFlush) {
  const char data[] = "foo!";
  int data_bytes = ARRAYSIZE_UNSAFE(data);
  PlatformFile file = GetTestPlatformFile(
      PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);

  FileUtilProxy::Write(
      file_task_runner(),
      file,
      0,  // offset
      data,
      data_bytes,
      Bind(&FileUtilProxyTest::DidWrite, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);
  EXPECT_EQ(data_bytes, bytes_written_);

  // Flush the written data.  (So that the following read should always
  // succeed.  On some platforms it may work with or without this flush.)
  FileUtilProxy::Flush(
      file_task_runner(),
      file,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);

  // Verify the written data.
  char buffer[10];
  EXPECT_EQ(data_bytes, file_util::ReadFile(test_path(), buffer, data_bytes));
  for (int i = 0; i < data_bytes; ++i) {
    EXPECT_EQ(data[i], buffer[i]);
  }
}

TEST_F(FileUtilProxyTest, Touch) {
  Time last_accessed_time = Time::Now() - TimeDelta::FromDays(12345);
  Time last_modified_time = Time::Now() - TimeDelta::FromHours(98765);

  FileUtilProxy::Touch(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_CREATE |
                          PLATFORM_FILE_WRITE |
                          PLATFORM_FILE_WRITE_ATTRIBUTES),
      last_accessed_time,
      last_modified_time,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();
  EXPECT_EQ(PLATFORM_FILE_OK, error_);

  PlatformFileInfo info;
  file_util::GetFileInfo(test_path(), &info);

  // The returned values may only have the seconds precision, so we cast
  // the double values to int here.
  EXPECT_EQ(static_cast<int>(last_modified_time.ToDoubleT()),
            static_cast<int>(info.last_modified.ToDoubleT()));
  EXPECT_EQ(static_cast<int>(last_accessed_time.ToDoubleT()),
            static_cast<int>(info.last_accessed.ToDoubleT()));
}

TEST_F(FileUtilProxyTest, Truncate_Shrink) {
  // Setup.
  const char kTestData[] = "0123456789";
  ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
  PlatformFileInfo info;
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(10, info.size);

  // Run.
  FileUtilProxy::Truncate(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
      7,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(7, info.size);

  char buffer[7];
  EXPECT_EQ(7, file_util::ReadFile(test_path(), buffer, 7));
  int i = 0;
  for (; i < 7; ++i)
    EXPECT_EQ(kTestData[i], buffer[i]);
}

TEST_F(FileUtilProxyTest, Truncate_Expand) {
  // Setup.
  const char kTestData[] = "9876543210";
  ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
  PlatformFileInfo info;
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(10, info.size);

  // Run.
  FileUtilProxy::Truncate(
      file_task_runner(),
      GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
      53,
      Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
  MessageLoop::current()->Run();

  // Verify.
  file_util::GetFileInfo(test_path(), &info);
  ASSERT_EQ(53, info.size);

  char buffer[53];
  EXPECT_EQ(53, file_util::ReadFile(test_path(), buffer, 53));
  int i = 0;
  for (; i < 10; ++i)
    EXPECT_EQ(kTestData[i], buffer[i]);
  for (; i < 53; ++i)
    EXPECT_EQ(0, buffer[i]);
}

}  // namespace base
<|endoftext|>


<commit_before>/*
 * Adapted from the Willow Garage pose_graph package by Paul Furgale on October 22, 2010.
 *
 * Original file:
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * 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 the Willow Garage, Inc. 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.
 *
 */

#ifndef SM_ID_HPP
#define SM_ID_HPP

#include <boost/cstdint.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
// The definition of std::tr1::hash
#ifdef _WIN32
#include <functional>
#else
#include <tr1/functional>
#endif

#include <boost/serialization/nvp.hpp>
namespace sm {
    typedef boost::uint64_t id_type;

  ///
  /// \class Id
  /// \brief superclass for stronly-typed uint64 ids
  ///
  /// Usage:
  /// \code
  /// // MyId is a stronly typed Id for my object.
  /// class MyId : public Id
  /// {
  /// public:
  ///
  ///   explicit MyId (id_type id = -1) : Id(id) {}
  ///
  ///   template<class Archive>
  ///   void serialize(Archive & ar, const unsigned int version)
  ///   {
  ///     ar & id_;
  ///   }
  /// };
  /// \endcode
  ///
  class Id
  {
  public:

    explicit Id (id_type id) : _id(id) {}

    /// Only for stl use
    Id () : _id(-1) {}

    friend std::ostream& operator<< (std::ostream& str, const Id& n)
    {
      str << n._id;
      return str;
    }

    bool operator== (const Id& other) const
    {
      return other._id == _id;
    }

    bool operator!= (const Id& other) const
    {
      return other._id != _id;
    }

    bool operator< (const Id& other) const
    {
      return _id < other._id;
    }

    bool operator> (const Id& other) const
    {
      return _id > other._id;
    }

    bool operator<=(const Id& other) const
    {
      return _id <= other._id;
    }

    bool operator>=(const Id& other) const
    {
      return _id >= other._id;
    }

    id_type getId () const
    {
      return _id;
    }

    // postincrement.
    Id operator++ (int unused)
    {
        Id rval(_id);
      ++_id;
      return rval;
    }

    // preincrement
    Id & operator++ ()
    {
      ++_id;
      return (*this);
    }

    Id& operator= (const Id& other)
    {
      _id = other._id;
      return *this;
    }

    bool isSet() const
    {
      return _id != id_type(-1);
    }

    id_type value() const
    {
      return _id;
    }

    void clear()
    {
      _id = -1;
    }

    void swap( Id & rhs)
    {
      std::swap(_id,rhs._id);
    }

    void setRandom()
    {
      _id = rand();
    }

    bool isBinaryEqual(const Id & rhs)
    {
      return _id == rhs._id;
    }
  protected:
    id_type _id;

  };

} // namespace aslam

#define SM_DEFINE_ID(IdTypeName)                                        \
    class IdTypeName : public sm::Id                                    \
    {                                                                   \
    public:                                                             \
        explicit IdTypeName (sm::id_type id = -1) : sm::Id(id) {}       \
        IdTypeName(const sm::Id & id) : sm::Id(id){}                    \
        template<class Archive>                                         \
            void serialize(Archive & ar, const unsigned int version)    \
        {                                                               \
            ar & BOOST_SERIALIZATION_NVP(_id);                          \
        }                                                               \
    };

#ifdef _WIN32
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName)                 \
    namespace std {                                                 \
        template<>                                                  \
        struct hash<FullyQualifiedIdTypeName>                       \
        {                                                           \
            hash<boost::uint64_t> _hash;                            \
            size_t operator()(const FullyQualifiedIdTypeName & id)	\
            {                                                       \
                return _hash(id.getId());                           \
            }                                                       \
        };                                                          \
    }                                                                   \
    namespace boost {                                                   \
        template<>                                                      \
        struct hash<FullyQualifiedIdTypeName>                           \
        {                                                               \
            hash<boost::uint64_t> _hash;                                \
            size_t operator()(const FullyQualifiedIdTypeName & id) const \
            {                                                           \
                return _hash(id.getId());                               \
            }                                                           \
        };                                                              \
        } // namespace boost
#else
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName)                     \
    namespace std { namespace tr1 {                                     \
            template<>                                                  \
            struct hash<FullyQualifiedIdTypeName>                       \
            {                                                           \
                hash<boost::uint64_t> _hash;                            \
                size_t operator()(const FullyQualifiedIdTypeName & id)	\
                {                                                       \
                    return _hash(id.getId());                           \
                }                                                       \
            };                                                          \
        }}                                                              \
    namespace boost {                                                   \
        template<>                                                      \
        struct hash<FullyQualifiedIdTypeName>                           \
        {                                                               \
            boost::hash<boost::uint64_t> _hash;                         \
            size_t operator()(const FullyQualifiedIdTypeName & id) const \
            {                                                           \
                return _hash(id.getId());                               \
            }                                                           \
        };                                                              \
        } // namespace boost

#endif

#endif /* SM_ID_HPP */
<commit_msg>added "const" specifier in Id.hpp<commit_after>/*
 * Adapted from the Willow Garage pose_graph package by Paul Furgale on October 22, 2010.
 *
 * Original file:
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * 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 the Willow Garage, Inc. 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.
 *
 */

#ifndef SM_ID_HPP
#define SM_ID_HPP

#include <boost/cstdint.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
// The definition of std::tr1::hash
#ifdef _WIN32
#include <functional>
#else
#include <tr1/functional>
#endif

#include <boost/serialization/nvp.hpp>
namespace sm {
    typedef boost::uint64_t id_type;

  ///
  /// \class Id
  /// \brief superclass for stronly-typed uint64 ids
  ///
  /// Usage:
  /// \code
  /// // MyId is a stronly typed Id for my object.
  /// class MyId : public Id
  /// {
  /// public:
  ///
  ///   explicit MyId (id_type id = -1) : Id(id) {}
  ///
  ///   template<class Archive>
  ///   void serialize(Archive & ar, const unsigned int version)
  ///   {
  ///     ar & id_;
  ///   }
  /// };
  /// \endcode
  ///
  class Id
  {
  public:

    explicit Id (id_type id) : _id(id) {}

    /// Only for stl use
    Id () : _id(-1) {}

    friend std::ostream& operator<< (std::ostream& str, const Id& n)
    {
      str << n._id;
      return str;
    }

    bool operator== (const Id& other) const
    {
      return other._id == _id;
    }

    bool operator!= (const Id& other) const
    {
      return other._id != _id;
    }

    bool operator< (const Id& other) const
    {
      return _id < other._id;
    }

    bool operator> (const Id& other) const
    {
      return _id > other._id;
    }

    bool operator<=(const Id& other) const
    {
      return _id <= other._id;
    }

    bool operator>=(const Id& other) const
    {
      return _id >= other._id;
    }

    id_type getId () const
    {
      return _id;
    }

    // postincrement.
    Id operator++ (int unused)
    {
        Id rval(_id);
      ++_id;
      return rval;
    }

    // preincrement
    Id & operator++ ()
    {
      ++_id;
      return (*this);
    }

    Id& operator= (const Id& other)
    {
      _id = other._id;
      return *this;
    }

    bool isSet() const
    {
      return _id != id_type(-1);
    }

    id_type value() const
    {
      return _id;
    }

    void clear()
    {
      _id = -1;
    }

    void swap( Id & rhs)
    {
      std::swap(_id,rhs._id);
    }

    void setRandom()
    {
      _id = rand();
    }

    bool isBinaryEqual(const Id & rhs)
    {
      return _id == rhs._id;
    }
  protected:
    id_type _id;

  };

} // namespace aslam

#define SM_DEFINE_ID(IdTypeName)                                        \
    class IdTypeName : public sm::Id                                    \
    {                                                                   \
    public:                                                             \
        explicit IdTypeName (sm::id_type id = -1) : sm::Id(id) {}       \
        IdTypeName(const sm::Id & id) : sm::Id(id){}                    \
        template<class Archive>                                         \
            void serialize(Archive & ar, const unsigned int version)    \
        {                                                               \
            ar & BOOST_SERIALIZATION_NVP(_id);                          \
        }                                                               \
    };

#ifdef _WIN32
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName)                 \
    namespace std {                                                 \
        template<>                                                  \
        struct hash<FullyQualifiedIdTypeName>                       \
        {                                                           \
            hash<boost::uint64_t> _hash;                            \
            size_t operator()(const FullyQualifiedIdTypeName & id)	\
            {                                                       \
                return _hash(id.getId());                           \
            }                                                       \
        };                                                          \
    }                                                                   \
    namespace boost {                                                   \
        template<>                                                      \
        struct hash<FullyQualifiedIdTypeName>                           \
        {                                                               \
            hash<boost::uint64_t> _hash;                                \
            size_t operator()(const FullyQualifiedIdTypeName & id) const \
            {                                                           \
                return _hash(id.getId());                               \
            }                                                           \
        };                                                              \
        } // namespace boost
#else
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName)                     \
    namespace std { namespace tr1 {                                     \
            template<>                                                  \
            struct hash<FullyQualifiedIdTypeName>                       \
            {                                                           \
                hash<boost::uint64_t> _hash;                            \
                size_t operator()(const FullyQualifiedIdTypeName & id) const	\
                {                                                       \
                    return _hash(id.getId());                           \
                }                                                       \
            };                                                          \
        }}                                                              \
    namespace boost {                                                   \
        template<>                                                      \
        struct hash<FullyQualifiedIdTypeName>                           \
        {                                                               \
            boost::hash<boost::uint64_t> _hash;                         \
            size_t operator()(const FullyQualifiedIdTypeName & id) const \
            {                                                           \
                return _hash(id.getId());                               \
            }                                                           \
        };                                                              \
        } // namespace boost

#endif

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