<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "tools.h"
#include <QDebug>
#include <QTextStream>

using namespace Gost;

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_currentState = NULL;
    m_history = NULL;
    m_movesNumber = 0;

    m_xmlChoiceWindow = NULL;

    m_scene = NULL;

    ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft); //permet d'aligner le (0,0) en haut et à gauche
    ui->graphicsView->setMouseTracking(true);

    this->setCentralWidget(ui->centralWidget);

    QList<QKeySequence> raccourcisChoixJeu;
    raccourcisChoixJeu.push_back(QKeySequence("Ctrl+o"));//o comme ouvrir
    raccourcisChoixJeu.push_back(QKeySequence("Ctrl+c"));//c comme choisir. Plus accessible pour la main gauche
    ui->actionChoixJeu->setShortcuts(raccourcisChoixJeu);

    m_labelMovesNumber = new QLabel(QString());
    ui->statusBar->addPermanentWidget(m_labelMovesNumber);

    m_finalStateWindow = NULL;
    m_historicalWindow = NULL;
    m_debugHistoricalwindow = NULL;
    QObject::connect(ui->actionQuitter,SIGNAL(triggered()),qApp,SLOT(quit()));
    QObject::connect(ui->actionChoixJeu,SIGNAL(triggered()),this,SLOT(callChoiceGameFile()));
    QObject::connect(ui->actionAnnuler,SIGNAL(triggered()),this,SLOT(cancel()));
    QObject::connect(ui->actionRefaire_le_dernier_coup,SIGNAL(triggered()),this,SLOT(redo()));
}

bool MainWindow::loadGameFromPath(QString &path, QString *error)
{
    //on prépare la sortie d'erreur
    QString* log;
    if(error)
        log = error;
    else
        log = new QString();

    QFile file(path);
    if(!file.exists())
    {
        *log += QString("Pas de fichier");
        return false;
    }

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        *log += QString("Pas de fichier lisible");
        return false;
    }

    QTextStream in(&file);
    QString toLoad = in.readAll();

    QDomDocument xmlDomDocument;

    if(xmlDomDocument.setContent(toLoad))
    {
        if(!m_game.load(xmlDomDocument,log))
        {
            QMessageBox::information(this, "Erreur de chargement du fichier", QString::fromUtf8(log->toStdString().c_str()));
            file.close();
            return false;
        }
    }
    else
    {
        if(!m_game.load(toLoad,log))
        {
            QMessageBox::information(this,"Erreur de chargement du fichier", QString::fromUtf8(log->toStdString().c_str()));
            file.close();
            return false;
        }
    }
    file.close();

    //si on arrive jusqu'ici, ça veut dire que le chargement du nouveau jeu a fonctionné.
    //on supprime l'ancien
    if(m_scene)
    {
        delete m_scene;
        m_scene = NULL;
    }
    if(m_finalStateWindow)
    {
        m_finalStateWindow->close();
        delete m_finalStateWindow;
        m_finalStateWindow = NULL;
    }
    if(m_historicalWindow)
    {
        m_historicalWindow->close();
        delete m_historicalWindow;
        m_historicalWindow = NULL;
    }
    if(m_debugHistoricalwindow)
    {
        m_debugHistoricalwindow->close();
        delete m_debugHistoricalwindow;
        m_debugHistoricalwindow = NULL;
    }
    List::clearDelete(m_history);
    m_currentState = NULL;
    m_movesNumber = 0;
    m_labelMovesNumber->setText(QString());

    //on met en place le nouveau jeu
    m_scene = new MyGraphicsScene();
    ui->graphicsView->setScene(m_scene);

    //Appel de la fonction resize qui redimensionne la GUI en fonction de la graphicsView
    QObject::connect(m_scene,SIGNAL(sendResize(int,int)),this,SLOT(resize(int,int)));

    //appelle de la fonction qui vérifie si le déplacement est bon et récupérer la pièce correspondante
    QObject::connect(m_scene,SIGNAL(sendPositions(QPointF*,QPointF*)),this,SLOT(callIAPossibleMove(QPointF*,QPointF*)));

    List::push_front<const State *>(m_game.getInitialStateCopy(), m_history);
    m_currentState = m_history;//Au début du jeu, l'état courant est le premier de l'historique
    m_scene->associateGame(&m_game);

    m_scene->callResize();

    m_finalStateWindow = new EndWindow;

    QObject::connect(ui->actionAfficher_Fin,SIGNAL(triggered()),m_finalStateWindow,SLOT(show()));

    m_finalStateWindow->display(m_game);

    m_historicalWindow = new HistoricalWindow;
    m_historicalWindow->setWindowTitle("Historique");
    m_debugHistoricalwindow = new HistoricalWindow;
    m_debugHistoricalwindow->setWindowTitle("Fenêtre de debug");
    QObject::connect(ui->actionAfficher_l_Historique,SIGNAL(triggered()),m_historicalWindow,SLOT(show()));
    QObject::connect(ui->actionDebug,SIGNAL(triggered()),m_debugHistoricalwindow,SLOT(show()));

    setState();
    return true;
}

void MainWindow::setState()
{
    m_scene->setState(m_currentState->info);
    m_historicalWindow->displayGameHistory(m_currentState, m_game, true);
    if(m_movesNumber == 1)
        m_labelMovesNumber->setText(QString("Vous avez fait %1 coup.").arg(m_movesNumber));
    else if(m_movesNumber > 1)
        m_labelMovesNumber->setText(QString("Vous avez fait %1 coups.").arg(m_movesNumber));
    else
        m_labelMovesNumber->setText(QString::fromUtf8("Début du jeu"));

    if(IA::isEnd(*(m_currentState->info),m_game.getFinalState(),&m_game))
        QMessageBox::information(NULL,"Fin du jeu",QString::fromUtf8("Bien joué"));
    else
        showDifferentsPossibleStates();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_scene;

    if(m_xmlChoiceWindow)
        delete m_xmlChoiceWindow;

    if(m_finalStateWindow)
    {
        m_finalStateWindow->close();
        delete m_finalStateWindow;
    }
    if(m_historicalWindow)
    {
        m_historicalWindow->close();
        delete m_historicalWindow;
    }
    if(m_debugHistoricalwindow)
    {
        m_debugHistoricalwindow->close();
        delete m_debugHistoricalwindow;
    }

    List::clearDelete(m_history);
}

void MainWindow::resize(int w, int h)
{
    ui->graphicsView->setFixedSize(w,h);
}

void MainWindow::callChoiceGameFile()
{
    m_xmlChoiceWindow = new GameFileChoice;
    QObject::connect(m_xmlChoiceWindow,SIGNAL(returnSelectedPath(QString)),this,SLOT(saveSelectedPathFromXml(QString)));
    m_xmlChoiceWindow->show();
}

void MainWindow::saveSelectedPathFromXml(QString path)
{
    m_loadedPath = path;
    m_xmlChoiceWindow->close();
    loadGameFromPath(path);
}

void MainWindow::callIAPossibleMove(QPointF *init, QPointF *final)
{
    if(m_game.getBoardMatrix()->inRange(init->y(),init->x()) && m_game.getBoardMatrix()->inRange(final->y(),final->x()))
    {
        State *newState = IA::possibleMove(*(m_currentState->info),
                                           m_game.getBoardMatrix()->get(init->y(),init->x()),
                                           m_game.getBoardMatrix()->get(final->y(),final->x()),
                                           m_game);
        if(newState)
        {
            if(m_currentState && m_currentState->next && (*newState) == (*m_currentState->next->info))//si on fait marche arrière
            {
                cancel();
            }
            else//sinon
            {
                //on recherche le coup joué après l'état courant
                List::Node<const State *> *it = m_history;
                while(it && it != m_currentState && it->next != m_currentState)
                {
                    it = it->next;
                }

                if(it && *(it->info) == (*newState))//si c'est le même que le nouveau coup
                {
                    redo();
                }
                else//si c'est un coup quelconque
                {
                    while(m_history != m_currentState)
                    {
                        List::pop_front(m_history);
                    }
                    List::push_front<const State *>(newState, m_history);
                    m_currentState = m_history;
                    m_movesNumber++;
                    setState();
                }
            }
        }
    }
}

void MainWindow::cancel()
{
    if(!m_currentState)
        return;//on ne fait rien si il n'y a pas de jeu en cours
    else if(m_currentState->next)//si il y a un coup précédent
    {
        m_currentState = m_currentState->next;
        if(m_movesNumber > 0)//protection contre l'overflow !
            m_movesNumber--;
        setState();
    }
}

void MainWindow::redo()
{
    if(!m_currentState)
        return;//on ne fait rien si il n'y a pas de jeu en cours
    else if(m_history && m_currentState != m_history)
    {
        List::Node<const State *> *it = m_history;
        //on recherche le coup joué après l'état courant
        while(it && it->next != m_currentState)
        {
            it = it->next;
        }
        m_currentState = it;
        m_movesNumber++;
        setState();
    }
}

void MainWindow::showDifferentsPossibleStates()
{
    List::Node<const State *>* IAResult = NULL;
    try
    {
         IAResult = IA::aStar(m_game.getInitialState(),m_game.getFinalState(),m_game);
    }catch(const BadAllocation& e)
    {
        QMessageBox::warning(this,"Erreur", "Une erreur est survenue en mémoire, rendant impossible la recherche de la solution. Cela est probablement dû à un manque de mémoire vive sur votre ordinateur, par rapport à l'implémentation actuelles de l'algorithme de recherche, et par rapport à la complexité du jeu.");
    }

    //if(IAResult)
     //   m_debugHistoricalwindow->displayGameHistory(IAResult,m_game);

    //List::Node<const State *>* possibleStates = IA::getPossibleMove(*(m_currentState->info),m_game);

    //m_debugHistoricalwindow->displayGameHistory(possibleStates,m_game);

    /*qDebug() << possibleStates;
    while(possibleStates)
    {
        QMessageBox::information(NULL,"","on recommence");
        m_scene->setState(m_currentState);
        QMessageBox::information(NULL,"","on avance");
        m_scene->setState(possibleStates->info);
        possibleStates = possibleStates->next;
    }*/
}

<commit_msg>Suppression du démarrage de l'IA.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "tools.h"
#include <QDebug>
#include <QTextStream>

using namespace Gost;

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_currentState = NULL;
    m_history = NULL;
    m_movesNumber = 0;

    m_xmlChoiceWindow = NULL;

    m_scene = NULL;

    ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft); //permet d'aligner le (0,0) en haut et à gauche
    ui->graphicsView->setMouseTracking(true);

    this->setCentralWidget(ui->centralWidget);

    QList<QKeySequence> raccourcisChoixJeu;
    raccourcisChoixJeu.push_back(QKeySequence("Ctrl+o"));//o comme ouvrir
    raccourcisChoixJeu.push_back(QKeySequence("Ctrl+c"));//c comme choisir. Plus accessible pour la main gauche
    ui->actionChoixJeu->setShortcuts(raccourcisChoixJeu);

    m_labelMovesNumber = new QLabel(QString());
    ui->statusBar->addPermanentWidget(m_labelMovesNumber);

    m_finalStateWindow = NULL;
    m_historicalWindow = NULL;
    m_debugHistoricalwindow = NULL;
    QObject::connect(ui->actionQuitter,SIGNAL(triggered()),qApp,SLOT(quit()));
    QObject::connect(ui->actionChoixJeu,SIGNAL(triggered()),this,SLOT(callChoiceGameFile()));
    QObject::connect(ui->actionAnnuler,SIGNAL(triggered()),this,SLOT(cancel()));
    QObject::connect(ui->actionRefaire_le_dernier_coup,SIGNAL(triggered()),this,SLOT(redo()));
}

bool MainWindow::loadGameFromPath(QString &path, QString *error)
{
    //on prépare la sortie d'erreur
    QString* log;
    if(error)
        log = error;
    else
        log = new QString();

    QFile file(path);
    if(!file.exists())
    {
        *log += QString("Pas de fichier");
        return false;
    }

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        *log += QString("Pas de fichier lisible");
        return false;
    }

    QTextStream in(&file);
    QString toLoad = in.readAll();

    QDomDocument xmlDomDocument;

    if(xmlDomDocument.setContent(toLoad))
    {
        if(!m_game.load(xmlDomDocument,log))
        {
            QMessageBox::information(this, "Erreur de chargement du fichier", QString::fromUtf8(log->toStdString().c_str()));
            file.close();
            return false;
        }
    }
    else
    {
        if(!m_game.load(toLoad,log))
        {
            QMessageBox::information(this,"Erreur de chargement du fichier", QString::fromUtf8(log->toStdString().c_str()));
            file.close();
            return false;
        }
    }
    file.close();

    //si on arrive jusqu'ici, ça veut dire que le chargement du nouveau jeu a fonctionné.
    //on supprime l'ancien
    if(m_scene)
    {
        delete m_scene;
        m_scene = NULL;
    }
    if(m_finalStateWindow)
    {
        m_finalStateWindow->close();
        delete m_finalStateWindow;
        m_finalStateWindow = NULL;
    }
    if(m_historicalWindow)
    {
        m_historicalWindow->close();
        delete m_historicalWindow;
        m_historicalWindow = NULL;
    }
    if(m_debugHistoricalwindow)
    {
        m_debugHistoricalwindow->close();
        delete m_debugHistoricalwindow;
        m_debugHistoricalwindow = NULL;
    }
    List::clearDelete(m_history);
    m_currentState = NULL;
    m_movesNumber = 0;
    m_labelMovesNumber->setText(QString());

    //on met en place le nouveau jeu
    m_scene = new MyGraphicsScene();
    ui->graphicsView->setScene(m_scene);

    //Appel de la fonction resize qui redimensionne la GUI en fonction de la graphicsView
    QObject::connect(m_scene,SIGNAL(sendResize(int,int)),this,SLOT(resize(int,int)));

    //appelle de la fonction qui vérifie si le déplacement est bon et récupérer la pièce correspondante
    QObject::connect(m_scene,SIGNAL(sendPositions(QPointF*,QPointF*)),this,SLOT(callIAPossibleMove(QPointF*,QPointF*)));

    List::push_front<const State *>(m_game.getInitialStateCopy(), m_history);
    m_currentState = m_history;//Au début du jeu, l'état courant est le premier de l'historique
    m_scene->associateGame(&m_game);

    m_scene->callResize();

    m_finalStateWindow = new EndWindow;

    QObject::connect(ui->actionAfficher_Fin,SIGNAL(triggered()),m_finalStateWindow,SLOT(show()));

    m_finalStateWindow->display(m_game);

    m_historicalWindow = new HistoricalWindow;
    m_historicalWindow->setWindowTitle("Historique");
    m_debugHistoricalwindow = new HistoricalWindow;
    m_debugHistoricalwindow->setWindowTitle("Fenêtre de debug");
    QObject::connect(ui->actionAfficher_l_Historique,SIGNAL(triggered()),m_historicalWindow,SLOT(show()));
    QObject::connect(ui->actionDebug,SIGNAL(triggered()),m_debugHistoricalwindow,SLOT(show()));

    setState();
    return true;
}

void MainWindow::setState()
{
    m_scene->setState(m_currentState->info);
    m_historicalWindow->displayGameHistory(m_currentState, m_game, true);
    if(m_movesNumber == 1)
        m_labelMovesNumber->setText(QString("Vous avez fait %1 coup.").arg(m_movesNumber));
    else if(m_movesNumber > 1)
        m_labelMovesNumber->setText(QString("Vous avez fait %1 coups.").arg(m_movesNumber));
    else
        m_labelMovesNumber->setText(QString::fromUtf8("Début du jeu"));

    if(IA::isEnd(*(m_currentState->info),m_game.getFinalState(),&m_game))
        QMessageBox::information(NULL,"Fin du jeu",QString::fromUtf8("Bien joué"));
    else
        showDifferentsPossibleStates();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_scene;

    if(m_xmlChoiceWindow)
        delete m_xmlChoiceWindow;

    if(m_finalStateWindow)
    {
        m_finalStateWindow->close();
        delete m_finalStateWindow;
    }
    if(m_historicalWindow)
    {
        m_historicalWindow->close();
        delete m_historicalWindow;
    }
    if(m_debugHistoricalwindow)
    {
        m_debugHistoricalwindow->close();
        delete m_debugHistoricalwindow;
    }

    List::clearDelete(m_history);
}

void MainWindow::resize(int w, int h)
{
    ui->graphicsView->setFixedSize(w,h);
}

void MainWindow::callChoiceGameFile()
{
    m_xmlChoiceWindow = new GameFileChoice;
    QObject::connect(m_xmlChoiceWindow,SIGNAL(returnSelectedPath(QString)),this,SLOT(saveSelectedPathFromXml(QString)));
    m_xmlChoiceWindow->show();
}

void MainWindow::saveSelectedPathFromXml(QString path)
{
    m_loadedPath = path;
    m_xmlChoiceWindow->close();
    loadGameFromPath(path);
}

void MainWindow::callIAPossibleMove(QPointF *init, QPointF *final)
{
    if(m_game.getBoardMatrix()->inRange(init->y(),init->x()) && m_game.getBoardMatrix()->inRange(final->y(),final->x()))
    {
        State *newState = IA::possibleMove(*(m_currentState->info),
                                           m_game.getBoardMatrix()->get(init->y(),init->x()),
                                           m_game.getBoardMatrix()->get(final->y(),final->x()),
                                           m_game);
        if(newState)
        {
            if(m_currentState && m_currentState->next && (*newState) == (*m_currentState->next->info))//si on fait marche arrière
            {
                cancel();
            }
            else//sinon
            {
                //on recherche le coup joué après l'état courant
                List::Node<const State *> *it = m_history;
                while(it && it != m_currentState && it->next != m_currentState)
                {
                    it = it->next;
                }

                if(it && *(it->info) == (*newState))//si c'est le même que le nouveau coup
                {
                    redo();
                }
                else//si c'est un coup quelconque
                {
                    while(m_history != m_currentState)
                    {
                        List::pop_front(m_history);
                    }
                    List::push_front<const State *>(newState, m_history);
                    m_currentState = m_history;
                    m_movesNumber++;
                    setState();
                }
            }
        }
    }
}

void MainWindow::cancel()
{
    if(!m_currentState)
        return;//on ne fait rien si il n'y a pas de jeu en cours
    else if(m_currentState->next)//si il y a un coup précédent
    {
        m_currentState = m_currentState->next;
        if(m_movesNumber > 0)//protection contre l'overflow !
            m_movesNumber--;
        setState();
    }
}

void MainWindow::redo()
{
    if(!m_currentState)
        return;//on ne fait rien si il n'y a pas de jeu en cours
    else if(m_history && m_currentState != m_history)
    {
        List::Node<const State *> *it = m_history;
        //on recherche le coup joué après l'état courant
        while(it && it->next != m_currentState)
        {
            it = it->next;
        }
        m_currentState = it;
        m_movesNumber++;
        setState();
    }
}

void MainWindow::showDifferentsPossibleStates()
{
    /*List::Node<const State *>* IAResult = NULL;
    try
    {
         IAResult = IA::aStar(m_game.getInitialState(),m_game.getFinalState(),m_game);
    }catch(const BadAllocation& e)
    {
        QMessageBox::warning(this,"Erreur", "Une erreur est survenue en mémoire, rendant impossible la recherche de la solution. Cela est probablement dû à un manque de mémoire vive sur votre ordinateur, par rapport à l'implémentation actuelles de l'algorithme de recherche, et par rapport à la complexité du jeu.");
    }*/

    //if(IAResult)
     //   m_debugHistoricalwindow->displayGameHistory(IAResult,m_game);

    //List::Node<const State *>* possibleStates = IA::getPossibleMove(*(m_currentState->info),m_game);

    //m_debugHistoricalwindow->displayGameHistory(possibleStates,m_game);

    /*qDebug() << possibleStates;
    while(possibleStates)
    {
        QMessageBox::information(NULL,"","on recommence");
        m_scene->setState(m_currentState);
        QMessageBox::information(NULL,"","on avance");
        m_scene->setState(possibleStates->info);
        possibleStates = possibleStates->next;
    }*/
}

<|endoftext|>


<commit_before>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
	std::string address;
	std::string amount;
};
void VerifySnapShot()
{
}
void SendSnapShotPayment(const std::string &strSend)
{
	currentTx++;
	std::string strSendMany = "sendmany \"\" {" + strSend + "}";
	UniValue r;
	printf("strSendMany #%d\n", currentTx);
	BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", strSendMany, false));
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
	int numberOfTxPerBlock = 1000;
	std::string sendManyString = "";
	for(int i =0;i<paymentAmounts.size();i++)
	{
		if(sendManyString != "")
			sendManyString += ",";
		sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
		if(i != 0 && (i%numberOfTxPerBlock) == 0)
		{
			SendSnapShotPayment(sendManyString);
			GenerateMainNetBlocks(1, "mainnet1");
			sendManyString = "";
		}
	}
	if(sendManyString != "")
	{
		SendSnapShotPayment(sendManyString);
		GenerateMainNetBlocks(1, "mainnet1");
	}

}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
    UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
    for (unsigned int idx = 0; idx < tests.size(); idx++) {
        UniValue test = tests[idx];
        std::string strTest = test.write();
        if (test.size() < 2) // Allow for extra stuff (useful for comments)
        {
            BOOST_ERROR("Bad test: " << strTest);
            continue;
        }
		PaymentAmount payment;
        payment.address  = test[0].get_str();
		CAmount amount = test[1].get_int64() / 300;
        payment.amount = ValueFromAmount(amount).write();
		paymentAmounts.push_back(payment);
    }
}
bool IsMainNetAlreadyCreated()
{
	int height;
	UniValue r;
	BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false));
	height = find_value(r.get_obj(), "blocks").get_int();
	return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
	std::vector<PaymentAmount> paymentAmounts;
	// generate snapshot payments
	GenerateMainNetBlocks(1, "mainnet1");
	GetUTXOs(paymentAmounts);
	if(IsMainNetAlreadyCreated())
	{
		VerifySnapShot();
	}
	else
	{
		GenerateSnapShot(paymentAmounts);
		VerifySnapShot();
	}
}
BOOST_AUTO_TEST_SUITE_END ()<commit_msg>create snapshot in the right place<commit_after>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
	std::string address;
	std::string amount;
};
void VerifySnapShot()
{
}
void SendSnapShotPayment(const std::string &strSend)
{
	currentTx++;
	std::string strSendMany = "sendmany \"\" {" + strSend + "}";
	UniValue r;
	printf("strSendMany #%d\n", currentTx);
	BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", strSendMany, false));
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
	// generate snapshot payments
	GenerateMainNetBlocks(1, "mainnet1");

	int numberOfTxPerBlock = 1000;
	std::string sendManyString = "";
	for(int i =0;i<paymentAmounts.size();i++)
	{
		if(sendManyString != "")
			sendManyString += ",";
		sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
		if(i != 0 && (i%numberOfTxPerBlock) == 0)
		{
			SendSnapShotPayment(sendManyString);
			GenerateMainNetBlocks(1, "mainnet1");
			sendManyString = "";
		}
	}
	if(sendManyString != "")
	{
		SendSnapShotPayment(sendManyString);
		GenerateMainNetBlocks(1, "mainnet1");
	}

}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
    UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
    for (unsigned int idx = 0; idx < tests.size(); idx++) {
        UniValue test = tests[idx];
        std::string strTest = test.write();
        if (test.size() < 2) // Allow for extra stuff (useful for comments)
        {
            BOOST_ERROR("Bad test: " << strTest);
            continue;
        }
		PaymentAmount payment;
        payment.address  = test[0].get_str();
		CAmount amount = test[1].get_int64() / 300;
        payment.amount = ValueFromAmount(amount).write();
		paymentAmounts.push_back(payment);
    }
}
bool IsMainNetAlreadyCreated()
{
	int height;
	UniValue r;
	BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false));
	height = find_value(r.get_obj(), "blocks").get_int();
	return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
	std::vector<PaymentAmount> paymentAmounts;
	GetUTXOs(paymentAmounts);
	if(IsMainNetAlreadyCreated())
	{
		VerifySnapShot();
	}
	else
	{
		GenerateSnapShot(paymentAmounts);
		VerifySnapShot();
	}
}
BOOST_AUTO_TEST_SUITE_END ()<|endoftext|>


<commit_before>/*Copyright (c) 2014 Gennady Gaidukov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "World.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //this->setFixedSize(this->size());

    //CREATING ACTIONS FIRST!!! THEN CREATING MENUS...
    createActions();
    createMenus();
    //------------------
    createStatusBar();
    //------------------
    //Setting amount of graphWindows
    graphWindows.fill(nullptr, 2); //два окна с графоном... пока
    //------------------
}

MainWindow::~MainWindow()
{
    delete ui;
    delete New;
    delete open;
    delete save;
    delete saveAs;
    delete print;
    delete printPrev;
    delete printSetup;
    delete recFile;
    delete exit;

    delete undo;
    delete cut;
    delete copy;
    delete paste;

    delete heightDist;
    delete MaxwellDist;

    delete toolBar;
    delete statusBr;
    delete about;

    deleteStatusBar();
    //delete scene;
}

void MainWindow::toolBarSlot(bool checked)
{
    if (checked)
        ui->mainToolBar->setVisible(true);
    else
        ui->mainToolBar->setVisible(false);
}

void MainWindow::statusBarSlot(bool checked)
{
    if (checked)
    {
        ui->statusBar->setVisible(true);
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-ui->statusBar->geometry().height()-44);
    }
    else
    {
        ui->statusBar->setVisible(false);
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-43);
    }
}

void MainWindow::exitSlot()
{
    qApp->quit();
}

void MainWindow::onAboutClick()
{
    AboutWindow* aboutW = new AboutWindow(this);
    aboutW->show();
}

void MainWindow::onOpenClick()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "",
                                                     tr("Files (*.*)"));
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly))
        return;
    //working with opend file here...

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

void MainWindow::onSaveClick()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                     "",
                                                     tr("Files (*.txt)"));
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    //generating file here...

    //------
    file.close();
}

void MainWindow::onSaveAsClick()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                     "",
                                                     tr("Files (*.*)"));
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    //generating file here...

    //------
    file.close();
}

void MainWindow::onNewClick()
{
}

void MainWindow::onHeightDistClick()
{
    if (senderW)
    {
        if (!graphWindows[0])
        {
            graphWindows[0] = new GraphWindow;
            senderW->setHeightDistActive(true);
            connect(senderW, SIGNAL(RedrawHeightGraph(const QVector<double>*)), graphWindows[0], SLOT(updateHeightGraph(const QVector<double>*)));
            connect(graphWindows[0], SIGNAL(destroyed()), this, SLOT(onHeightDistClose()));
            qDebug()<<"new GraphWindow";
        }

        graphWindows[0]->setWindowFlags( Qt::Window );
        graphWindows[0]->setWindowTitle("Height Distribution");
        graphWindows[0]->show();
    }
}

void MainWindow::onMaxwellDistClick()
{
    if (senderW)
    {
        if (!graphWindows[1])
        {
            graphWindows[1] = new GraphWindow;
            senderW->setMaxwellDistActive(true);
            connect(senderW, SIGNAL(RedrawMaxwellDistGraph(const QVector<double>*)), graphWindows[1], SLOT(updateMaxwellDistGraph(const QVector<double>*)));
            connect(graphWindows[1], SIGNAL(destroyed()), this, SLOT(onMaxwellDistClose()));
            qDebug()<<"new GraphWindow";
        }

        graphWindows[1]->setWindowFlags( Qt::Window );
        graphWindows[1]->setWindowTitle("Maxwell Distribution");
        graphWindows[1]->show();
    }
}

void MainWindow::onMaxwellDistClose()
{
    graphWindows[1] = nullptr;
    senderW->setMaxwellDistActive(false);
}

void MainWindow::onHeightDistClose()
{
    graphWindows[0] = nullptr;
    senderW->setHeightDistActive(false);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    if(ui->statusBar->isVisible() || statusBr->isChecked())
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-ui->statusBar->geometry().height()-44);
    else
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-43);
    ui->Particles->resizeGL(ui->Particles->width(), ui->Particles->height());

    //Если кривой ресайз, раскомментить это:
    //QSize partSize = ui->Particles->size();
    //ui->Particles->resize(partSize.width() - 50, partSize.height() - 50);
    //ui->Particles->resize(partSize.width(), partSize.height());

    QMainWindow::resizeEvent(event);
}

void MainWindow::createActions()
{
    //Creating actions...
    New = new QAction(tr("&New"), this);
    New->setShortcut(QKeySequence::New);
    New->setToolTip(tr("Create a new file"));
    open = new QAction(tr("&Open"), this);
    open->setShortcut(QKeySequence::Open);
    open->setToolTip(tr("open a file"));
    save = new QAction(tr("&Save"), this);
    save->setShortcut(QKeySequence::Save);
    save->setToolTip(tr("Save a file"));
    saveAs = new QAction(tr("&Save As..."), this);
    saveAs->setShortcut(QKeySequence::SaveAs);
    saveAs->setToolTip(tr("Save a file as..."));
    print = new QAction(tr("&Print"), this);
    print->setShortcut(QKeySequence::Print);
    print->setToolTip(tr("Print a file"));
    printPrev = new QAction(tr("&Print Preview"), this);
    printSetup = new QAction(tr("&Print Setup..."), this);
    recFile = new QAction(tr("&Recent File"), this);
    exit = new QAction(tr("&Exit"), this);
    exit->setToolTip(tr("Exit"));

    undo = new QAction(tr("&Undo"), this);
    undo->setShortcut(QKeySequence::Undo);
    undo->setToolTip(tr("Undo the action"));
    cut = new QAction(tr("&Cut"), this);
    cut->setShortcut(QKeySequence::Cut);
    copy = new QAction(tr("&Copy"), this);
    copy->setShortcut(QKeySequence::Copy);
    paste =  new QAction(tr("&Paste"), this);
    paste->setShortcut(QKeySequence::Paste);

    heightDist = new QAction(tr("&Height distribution"), this);
    MaxwellDist = new QAction(tr("&Maxwell distribution"), this);

    toolBar = new QAction(tr("&Toolbar"), this);
    toolBar->setCheckable(true);
    toolBar->setChecked(true);
    statusBr =  new QAction(tr("&Status Bar"), this);
    statusBr->setCheckable(true);
    statusBr->setChecked(true);

    about = new QAction(tr("&About ParticlesInBox"), this);
    //-------------------

    //some actions are disabled here by default
    recFile->setEnabled(false);
    undo->setEnabled(false);
    cut->setEnabled(false);
    copy->setEnabled(false);
    paste->setEnabled(false);
    //---------------------

    //connecting signals of actions to slots...
    connect(New, SIGNAL(triggered()), this, SLOT(onNewClick()));
    connect(saveAs, SIGNAL(triggered()), this, SLOT(onSaveAsClick()));
    connect(save, SIGNAL(triggered()), this, SLOT(onSaveClick()));
    connect(open, SIGNAL(triggered()), this, SLOT(onOpenClick()));
    connect(heightDist, SIGNAL(triggered()), this, SLOT(onHeightDistClick()));
    connect(MaxwellDist, SIGNAL(triggered()), this, SLOT(onMaxwellDistClick()));

    connect(toolBar, SIGNAL(triggered(bool)), this, SLOT(toolBarSlot(bool)));
    connect(statusBr, SIGNAL(triggered(bool)), this, SLOT(statusBarSlot(bool)));
    connect(about, SIGNAL(triggered()), this, SLOT(onAboutClick()));
    connect(exit, SIGNAL(triggered()), this, SLOT(exitSlot()));
    //-------------------
}

void MainWindow::createMenus()
{
    //Creating menus...
    fileMenu = ui->menuBar->addMenu(tr("&File"));
    fileMenu->addAction(New);
    fileMenu->addAction(open);
    fileMenu->addAction(save);
    fileMenu->addAction(saveAs);
    fileMenu->addSeparator();
    fileMenu->addAction(print);
    fileMenu->addAction(printPrev);
    fileMenu->addAction(printSetup);
    fileMenu->addSeparator();
    fileMenu->addAction(recFile);
    fileMenu->addSeparator();
    fileMenu->addAction(exit);

    editMenu = ui->menuBar->addMenu(tr("&Edit"));
    editMenu->addAction(undo);
    editMenu->addSeparator();
    editMenu->addAction(cut);
    editMenu->addAction(copy);
    editMenu->addAction(paste);

    charts = ui->menuBar->addMenu(tr("&Charts"));
    charts->addAction(heightDist);
    charts->addAction(MaxwellDist);

    viewMenu = ui->menuBar->addMenu(tr("&View"));
    viewMenu->addAction(toolBar);
    viewMenu->addAction(statusBr);

    helpMenu = ui->menuBar->addMenu(tr("&Help"));
    helpMenu->addAction(about);
    //------------
}

void MainWindow::createStatusBar()
{
    statusTime = new QLabel(this);
    statusTime->setAlignment(Qt::AlignRight);
    statusTime->setIndent(3);
    statusTime->setMargin(8);

    statusLeft = new QLabel(this);
    statusLeft->setAlignment(Qt::AlignRight);
    statusLeft->setIndent(3);
    statusLeft->setMargin(8);

    statusRight = new QLabel(this);
    statusRight->setAlignment(Qt::AlignRight);
    statusRight->setIndent(3);
    statusRight->setMargin(8);

    statusBar()->addWidget(statusTime, 1);
    statusBar()->addWidget(statusLeft, 1);
    statusBar()->addWidget(statusRight, 1);

    statusBar()->showMessage("Ready");
}

void MainWindow::deleteStatusBar()
{
    if (statusTime)
        delete statusTime;
    if (statusLeft)
        delete statusLeft;
    if (statusRight)
        delete statusRight;
}

void MainWindow::onWorldInitialized() {
    // Show a window since it is hidden
    //CWorld* senderW = qobject_cast<CWorld*>(sender());
    senderW = qobject_cast<CWorld*>(sender());
    this->show();
    this->ui->Particles->resizeGL(ui->Particles->width(), ui->Particles->height());

    this->ui->Particles->initializeWorld(senderW);
    connect(senderW, SIGNAL(RedrawWorld(SGeometry)), this->ui->Particles, SLOT(OnRenderScene(SGeometry)));
    connect(senderW, SIGNAL(onParticleSCountChange()), this, SLOT(updateStatusBar()));

    //QSize partSize = ui->Particles->size();
    //ui->Particles->resize(partSize.width() - 50, partSize.height() - 50);
    //ui->Particles->resize(partSize.width(), partSize.height());

    return;
}

void MainWindow::updateStatusBar()
{
    if (senderW)
    {
        float nLeftPercent = senderW->nLeft*100.0f/senderW->GetParticleCount();
        float nRightPercent = senderW->nRight*100.0f/senderW->GetParticleCount();
        statusLeft->setText("Left: "+QString::number(senderW->nLeft)+" ("+QString::number(nLeftPercent)+"%) <V> = "+QString::number(senderW->VaverageL));
        statusRight->setText("Right: "+QString::number(senderW->nRight)+"("+QString::number(nRightPercent)+"%) <V> = "+QString::number(senderW->VaverageR));
        statusTime->setText("Time="+QString::number(senderW->Time)+" Step="+QString::number(senderW->DeltaTime));
    }

}
<commit_msg>Восстановил отображение GLWidget на Linux<commit_after>/*Copyright (c) 2014 Gennady Gaidukov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "World.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //this->setFixedSize(this->size());

    //CREATING ACTIONS FIRST!!! THEN CREATING MENUS...
    createActions();
    createMenus();
    //------------------
    createStatusBar();
    //------------------
    //Setting amount of graphWindows
    graphWindows.fill(nullptr, 2); //два окна с графоном... пока
    //------------------
}

MainWindow::~MainWindow()
{
    delete ui;
    delete New;
    delete open;
    delete save;
    delete saveAs;
    delete print;
    delete printPrev;
    delete printSetup;
    delete recFile;
    delete exit;

    delete undo;
    delete cut;
    delete copy;
    delete paste;

    delete heightDist;
    delete MaxwellDist;

    delete toolBar;
    delete statusBr;
    delete about;

    deleteStatusBar();
    //delete scene;
}

void MainWindow::toolBarSlot(bool checked)
{
    if (checked)
        ui->mainToolBar->setVisible(true);
    else
        ui->mainToolBar->setVisible(false);
}

void MainWindow::statusBarSlot(bool checked)
{
    if (checked)
    {
        ui->statusBar->setVisible(true);
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-ui->statusBar->geometry().height()-44);
    }
    else
    {
        ui->statusBar->setVisible(false);
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-43);
    }
}

void MainWindow::exitSlot()
{
    qApp->quit();
}

void MainWindow::onAboutClick()
{
    AboutWindow* aboutW = new AboutWindow(this);
    aboutW->show();
}

void MainWindow::onOpenClick()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "",
                                                     tr("Files (*.*)"));
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly))
        return;
    //working with opend file here...

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

void MainWindow::onSaveClick()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                     "",
                                                     tr("Files (*.txt)"));
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    //generating file here...

    //------
    file.close();
}

void MainWindow::onSaveAsClick()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                     "",
                                                     tr("Files (*.*)"));
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    //generating file here...

    //------
    file.close();
}

void MainWindow::onNewClick()
{
}

void MainWindow::onHeightDistClick()
{
    if (senderW)
    {
        if (!graphWindows[0])
        {
            graphWindows[0] = new GraphWindow;
            senderW->setHeightDistActive(true);
            connect(senderW, SIGNAL(RedrawHeightGraph(const QVector<double>*)), graphWindows[0], SLOT(updateHeightGraph(const QVector<double>*)));
            connect(graphWindows[0], SIGNAL(destroyed()), this, SLOT(onHeightDistClose()));
            qDebug()<<"new GraphWindow";
        }

        graphWindows[0]->setWindowFlags( Qt::Window );
        graphWindows[0]->setWindowTitle("Height Distribution");
        graphWindows[0]->show();
    }
}

void MainWindow::onMaxwellDistClick()
{
    if (senderW)
    {
        if (!graphWindows[1])
        {
            graphWindows[1] = new GraphWindow;
            senderW->setMaxwellDistActive(true);
            connect(senderW, SIGNAL(RedrawMaxwellDistGraph(const QVector<double>*)), graphWindows[1], SLOT(updateMaxwellDistGraph(const QVector<double>*)));
            connect(graphWindows[1], SIGNAL(destroyed()), this, SLOT(onMaxwellDistClose()));
            qDebug()<<"new GraphWindow";
        }

        graphWindows[1]->setWindowFlags( Qt::Window );
        graphWindows[1]->setWindowTitle("Maxwell Distribution");
        graphWindows[1]->show();
    }
}

void MainWindow::onMaxwellDistClose()
{
    graphWindows[1] = nullptr;
    senderW->setMaxwellDistActive(false);
}

void MainWindow::onHeightDistClose()
{
    graphWindows[0] = nullptr;
    senderW->setHeightDistActive(false);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    if(ui->statusBar->isVisible() || statusBr->isChecked())
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-ui->statusBar->geometry().height()-44);
    else
        ui->Particles->setGeometry(0, 10, this->width(), this->height()-43);
    ui->Particles->resizeGL(ui->Particles->width(), ui->Particles->height());

    //Если кривой ресайз, раскомментить это:
    //QSize partSize = ui->Particles->size();
    //ui->Particles->resize(partSize.width() - 50, partSize.height() - 50);
    //ui->Particles->resize(partSize.width(), partSize.height());

    QMainWindow::resizeEvent(event);
}

void MainWindow::createActions()
{
    //Creating actions...
    New = new QAction(tr("&New"), this);
    New->setShortcut(QKeySequence::New);
    New->setToolTip(tr("Create a new file"));
    open = new QAction(tr("&Open"), this);
    open->setShortcut(QKeySequence::Open);
    open->setToolTip(tr("open a file"));
    save = new QAction(tr("&Save"), this);
    save->setShortcut(QKeySequence::Save);
    save->setToolTip(tr("Save a file"));
    saveAs = new QAction(tr("&Save As..."), this);
    saveAs->setShortcut(QKeySequence::SaveAs);
    saveAs->setToolTip(tr("Save a file as..."));
    print = new QAction(tr("&Print"), this);
    print->setShortcut(QKeySequence::Print);
    print->setToolTip(tr("Print a file"));
    printPrev = new QAction(tr("&Print Preview"), this);
    printSetup = new QAction(tr("&Print Setup..."), this);
    recFile = new QAction(tr("&Recent File"), this);
    exit = new QAction(tr("&Exit"), this);
    exit->setToolTip(tr("Exit"));

    undo = new QAction(tr("&Undo"), this);
    undo->setShortcut(QKeySequence::Undo);
    undo->setToolTip(tr("Undo the action"));
    cut = new QAction(tr("&Cut"), this);
    cut->setShortcut(QKeySequence::Cut);
    copy = new QAction(tr("&Copy"), this);
    copy->setShortcut(QKeySequence::Copy);
    paste =  new QAction(tr("&Paste"), this);
    paste->setShortcut(QKeySequence::Paste);

    heightDist = new QAction(tr("&Height distribution"), this);
    MaxwellDist = new QAction(tr("&Maxwell distribution"), this);

    toolBar = new QAction(tr("&Toolbar"), this);
    toolBar->setCheckable(true);
    toolBar->setChecked(true);
    statusBr =  new QAction(tr("&Status Bar"), this);
    statusBr->setCheckable(true);
    statusBr->setChecked(true);

    about = new QAction(tr("&About ParticlesInBox"), this);
    //-------------------

    //some actions are disabled here by default
    recFile->setEnabled(false);
    undo->setEnabled(false);
    cut->setEnabled(false);
    copy->setEnabled(false);
    paste->setEnabled(false);
    //---------------------

    //connecting signals of actions to slots...
    connect(New, SIGNAL(triggered()), this, SLOT(onNewClick()));
    connect(saveAs, SIGNAL(triggered()), this, SLOT(onSaveAsClick()));
    connect(save, SIGNAL(triggered()), this, SLOT(onSaveClick()));
    connect(open, SIGNAL(triggered()), this, SLOT(onOpenClick()));
    connect(heightDist, SIGNAL(triggered()), this, SLOT(onHeightDistClick()));
    connect(MaxwellDist, SIGNAL(triggered()), this, SLOT(onMaxwellDistClick()));

    connect(toolBar, SIGNAL(triggered(bool)), this, SLOT(toolBarSlot(bool)));
    connect(statusBr, SIGNAL(triggered(bool)), this, SLOT(statusBarSlot(bool)));
    connect(about, SIGNAL(triggered()), this, SLOT(onAboutClick()));
    connect(exit, SIGNAL(triggered()), this, SLOT(exitSlot()));
    //-------------------
}

void MainWindow::createMenus()
{
    //Creating menus...
    fileMenu = ui->menuBar->addMenu(tr("&File"));
    fileMenu->addAction(New);
    fileMenu->addAction(open);
    fileMenu->addAction(save);
    fileMenu->addAction(saveAs);
    fileMenu->addSeparator();
    fileMenu->addAction(print);
    fileMenu->addAction(printPrev);
    fileMenu->addAction(printSetup);
    fileMenu->addSeparator();
    fileMenu->addAction(recFile);
    fileMenu->addSeparator();
    fileMenu->addAction(exit);

    editMenu = ui->menuBar->addMenu(tr("&Edit"));
    editMenu->addAction(undo);
    editMenu->addSeparator();
    editMenu->addAction(cut);
    editMenu->addAction(copy);
    editMenu->addAction(paste);

    charts = ui->menuBar->addMenu(tr("&Charts"));
    charts->addAction(heightDist);
    charts->addAction(MaxwellDist);

    viewMenu = ui->menuBar->addMenu(tr("&View"));
    viewMenu->addAction(toolBar);
    viewMenu->addAction(statusBr);

    helpMenu = ui->menuBar->addMenu(tr("&Help"));
    helpMenu->addAction(about);
    //------------
}

void MainWindow::createStatusBar()
{
    statusTime = new QLabel(this);
    statusTime->setAlignment(Qt::AlignRight);
    statusTime->setIndent(3);
    statusTime->setMargin(8);

    statusLeft = new QLabel(this);
    statusLeft->setAlignment(Qt::AlignRight);
    statusLeft->setIndent(3);
    statusLeft->setMargin(8);

    statusRight = new QLabel(this);
    statusRight->setAlignment(Qt::AlignRight);
    statusRight->setIndent(3);
    statusRight->setMargin(8);

    statusBar()->addWidget(statusTime, 1);
    statusBar()->addWidget(statusLeft, 1);
    statusBar()->addWidget(statusRight, 1);

    statusBar()->showMessage("Ready");
}

void MainWindow::deleteStatusBar()
{
    if (statusTime)
        delete statusTime;
    if (statusLeft)
        delete statusLeft;
    if (statusRight)
        delete statusRight;
}

void MainWindow::onWorldInitialized() {
    // Show a window since it is hidden
    //CWorld* senderW = qobject_cast<CWorld*>(sender());
    senderW = qobject_cast<CWorld*>(sender());
    this->show();
    this->ui->Particles->resizeGL(ui->Particles->width(), ui->Particles->height());

    this->ui->Particles->initializeWorld(senderW);
    connect(senderW, SIGNAL(RedrawWorld(SGeometry)), this->ui->Particles, SLOT(OnRenderScene(SGeometry)));
    connect(senderW, SIGNAL(onParticleSCountChange()), this, SLOT(updateStatusBar()));

    QSize partSize = ui->Particles->size();
    ui->Particles->resize(partSize.width() - 50, partSize.height() - 50);
    ui->Particles->resize(partSize.width(), partSize.height());

    return;
}

void MainWindow::updateStatusBar()
{
    if (senderW)
    {
        float nLeftPercent = senderW->nLeft*100.0f/senderW->GetParticleCount();
        float nRightPercent = senderW->nRight*100.0f/senderW->GetParticleCount();
        statusLeft->setText("Left: "+QString::number(senderW->nLeft)+" ("+QString::number(nLeftPercent)+"%) <V> = "+QString::number(senderW->VaverageL));
        statusRight->setText("Right: "+QString::number(senderW->nRight)+"("+QString::number(nRightPercent)+"%) <V> = "+QString::number(senderW->VaverageR));
        statusTime->setText("Time="+QString::number(senderW->Time)+" Step="+QString::number(senderW->DeltaTime));
    }

}
<|endoftext|>


<commit_before>/*=============================================================================

  Library: CppMicroServices

  Copyright (c) The CppMicroServices developers. See the COPYRIGHT
  file at the top-level directory of this distribution and at
  https://github.com/saschazelzer/CppMicroServices/COPYRIGHT .

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "usTestDriverActivator.h"
#include "usBundleImport.h"

namespace us {

TestDriverActivator* TestDriverActivator::m_Instance = nullptr;

TestDriverActivator::TestDriverActivator()
  : m_StartCalled(false)
{
}

bool TestDriverActivator::StartCalled()
{
  return m_Instance ? m_Instance->m_StartCalled : false;
}

void TestDriverActivator::Start(BundleContext*)
{
  this->m_Instance = this;
  this->m_StartCalled = true;
}

void TestDriverActivator::Stop(BundleContext*)
{
  this->m_Instance = nullptr;
}

}

US_EXPORT_BUNDLE_ACTIVATOR(us::TestDriverActivator)

#ifndef US_BUILD_SHARED_LIBS
US_IMPORT_BUNDLE(CppMicroServices)
US_IMPORT_BUNDLE(TestBundleA)
US_IMPORT_BUNDLE(TestBundleA2)
US_IMPORT_BUNDLE(TestBundleB)
US_IMPORT_BUNDLE(TestBundleH)
US_IMPORT_BUNDLE(TestBundleM)
US_INITIALIZE_STATIC_BUNDLE(TestBundleR)
US_INITIALIZE_STATIC_BUNDLE(TestBundleRL)
US_INITIALIZE_STATIC_BUNDLE(TestBundleRA)
US_IMPORT_BUNDLE(TestBundleS)
US_IMPORT_BUNDLE(TestBundleSL1)
US_IMPORT_BUNDLE(TestBundleSL3)
US_IMPORT_BUNDLE(TestBundleSL4)
US_IMPORT_BUNDLE(main)
#endif
<commit_msg>Import static test bundle for concurrency tests.<commit_after>/*=============================================================================

  Library: CppMicroServices

  Copyright (c) The CppMicroServices developers. See the COPYRIGHT
  file at the top-level directory of this distribution and at
  https://github.com/saschazelzer/CppMicroServices/COPYRIGHT .

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "usTestDriverActivator.h"
#include "usBundleImport.h"

namespace us {

TestDriverActivator* TestDriverActivator::m_Instance = nullptr;

TestDriverActivator::TestDriverActivator()
  : m_StartCalled(false)
{
}

bool TestDriverActivator::StartCalled()
{
  return m_Instance ? m_Instance->m_StartCalled : false;
}

void TestDriverActivator::Start(BundleContext*)
{
  this->m_Instance = this;
  this->m_StartCalled = true;
}

void TestDriverActivator::Stop(BundleContext*)
{
  this->m_Instance = nullptr;
}

}

US_EXPORT_BUNDLE_ACTIVATOR(us::TestDriverActivator)

#ifndef US_BUILD_SHARED_LIBS
US_IMPORT_BUNDLE(CppMicroServices)
US_IMPORT_BUNDLE(TestBundleA)
US_IMPORT_BUNDLE(TestBundleA2)
US_IMPORT_BUNDLE(TestBundleB)
#ifdef US_ENABLE_THREADING_SUPPORT
US_IMPORT_BUNDLE(TestBundleC1)
#endif
US_IMPORT_BUNDLE(TestBundleH)
US_IMPORT_BUNDLE(TestBundleM)
US_INITIALIZE_STATIC_BUNDLE(TestBundleR)
US_INITIALIZE_STATIC_BUNDLE(TestBundleRL)
US_INITIALIZE_STATIC_BUNDLE(TestBundleRA)
US_IMPORT_BUNDLE(TestBundleS)
US_IMPORT_BUNDLE(TestBundleSL1)
US_IMPORT_BUNDLE(TestBundleSL3)
US_IMPORT_BUNDLE(TestBundleSL4)
US_IMPORT_BUNDLE(main)
#endif
<|endoftext|>


<commit_before>// @(#)root/thread
// Author: Danilo Piparo, 2016

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_TSpinMutex
#define ROOT_TSpinMutex

#include <atomic>

namespace ROOT {

   /**
    * \class ROOT::TSpinMutex
    * \brief A spin mutex class which respects the STL interface for mutexes.
    * \ingroup Multicore
    * This class allows to acquire spin locks also in combination with templates in the STL such as
    * std::unique_lock or
    * std::condition_variable_any.
    * For example:
    *
    * ~~~ {.cpp}
    * ROOT::TSpinMutex m;
    * std::condition_variable cv;
    * bool ready = false;
    *
    * void worker_thread()
    * {
    *    // Wait until main() sends data
    *    std::unique_lock<ROOT::TSpinMutex> lk(m);
    *    cv.wait(lk, []{return ready;});
    * [...]
    * ~~~ {.cpp}
    */
   class TSpinMutex {

   private:
      std::atomic_flag fAFlag = ATOMIC_FLAG_INIT;

   public:
      TSpinMutex() = default;
      TSpinMutex(const TSpinMutex&) = delete;
      ~TSpinMutex() = default;
      TSpinMutex& operator=(const TSpinMutex&) = delete;

      void lock() { while (fAFlag.test_and_set(std::memory_order_acquire)); }
      void unlock() { fAFlag.clear(std::memory_order_release); }
      bool try_lock() { return !fAFlag.test_and_set(std::memory_order_acquire); }

   };
}

#endif
<commit_msg>[NFC] Close braces in documentation<commit_after>// @(#)root/thread
// Author: Danilo Piparo, 2016

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_TSpinMutex
#define ROOT_TSpinMutex

#include <atomic>

namespace ROOT {

   /**
    * \class ROOT::TSpinMutex
    * \brief A spin mutex class which respects the STL interface for mutexes.
    * \ingroup Multicore
    * This class allows to acquire spin locks also in combination with templates in the STL such as
    * std::unique_lock or
    * std::condition_variable_any.
    * For example:
    *
    * ~~~ {.cpp}
    * ROOT::TSpinMutex m;
    * std::condition_variable cv;
    * bool ready = false;
    *
    * void worker_thread()
    * {
    *    // Wait until main() sends data
    *    std::unique_lock<ROOT::TSpinMutex> lk(m);
    *    cv.wait(lk, []{return ready;});
    *    [...]
    * }
    * ~~~ {.cpp}
    */
   class TSpinMutex {

   private:
      std::atomic_flag fAFlag = ATOMIC_FLAG_INIT;

   public:
      TSpinMutex() = default;
      TSpinMutex(const TSpinMutex&) = delete;
      ~TSpinMutex() = default;
      TSpinMutex& operator=(const TSpinMutex&) = delete;

      void lock() { while (fAFlag.test_and_set(std::memory_order_acquire)); }
      void unlock() { fAFlag.clear(std::memory_order_release); }
      bool try_lock() { return !fAFlag.test_and_set(std::memory_order_acquire); }

   };
}

#endif
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "settingsdialog.h"

#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QDataStream>
#include <QDateTime>
#include <QDir>
#include <QStandardPaths>
#include <QUrl>
#include <QPushButton>

using namespace uva;

const QString DefaultProblemListFileName = "problemlist.json";

const QString UVAProblemHTMLUrl = "https://uva.onlinejudge.org/external/%1/%2.html"; // 1 = container, 2 = problem number
const QString UVAProblemPDFUrl = "https://uva.onlinejudge.org/external/%1/%2.pdf"; // 1 = container, 2 = problem number

MainWindow::MainWindow(std::shared_ptr<QNetworkAccessManager> networkManager, QWidget *parent) :
    QMainWindow(parent),
    mNetworkManager(networkManager),
    mUi(new Ui::MainWindow)
{
    mUi->setupUi(this);

    this->setWindowState(Qt::WindowState::WindowMaximized);
    statusBar()->showMessage("Welcome to UVA-Arena.");

    mUhuntApi = std::make_shared<Uhunt>(mNetworkManager);

#ifdef _DEBUG
    // if we're testing, save to test directories
    QStandardPaths::setTestModeEnabled(true);
#endif

    initialize();
}

MainWindow::~MainWindow()
{
}

std::shared_ptr<Uhunt::ProblemMap> MainWindow::getProblemMap()
{
    return mProblems;
}

void MainWindow::onUVAArenaEvent(UVAArenaWidget::UVAArenaEvent arenaEvent, QVariant metaData)
{
    typedef UVAArenaWidget::UVAArenaEvent UVAArenaEvent;

    switch (arenaEvent)
    {
    case UVAArenaEvent::UPDATE_STATUS:
        statusBar()->showMessage(metaData.toString(), 2000);
        break;

    case UVAArenaEvent::SHOW_PROBLEM:
        showProblem(metaData.toInt());
        break;

    default:
        break;
    }
}

void MainWindow::onAllProblemsDownloaded(QByteArray data)
{
    // set the file to save to
    QDir saveDirectory(
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
    );

    if (!saveDirectory.exists())
        saveDirectory.mkpath(saveDirectory.path());

    QString fileName = saveDirectory.filePath(DefaultProblemListFileName);
    QFile file(fileName);

    if (!file.open(QIODevice::WriteOnly)) {

        // couldn't open the file
        QMessageBox::critical(this, "Write failure",
            "Could not write to the default problem list file:\n"
            + fileName);

        return;
    }

    // write the problem list data to the default problems list file
    QDataStream dataStream(&file);
    dataStream << data;

    setProblemMap(Uhunt::problemMapFromJson(data));
}

void MainWindow::setProblemMap(Uhunt::ProblemMap problemMap)
{
    mProblems.reset(new Uhunt::ProblemMap);
    *mProblems = std::move(problemMap);

    Uhunt::ProblemMap::const_iterator it = mProblems->begin();

    mUi->problemsWidget->setProblemMap(getProblemMap());
    mUi->liveEventsWidget->setProblemMap(getProblemMap());
    statusBar()->showMessage("Problem list loaded", 2000);
}

void MainWindow::initialize()
{
    initializeData();
    initializeWidgets();
}

void MainWindow::initializeData()
{
    //connect problem list byte downloaded array signal
    QObject::connect(mUhuntApi.get(), &Uhunt::allProblemsDownloaded,
        this, &MainWindow::onAllProblemsDownloaded);

    // check if problem list is already downloaded
    QString result = QStandardPaths::locate(QStandardPaths::AppDataLocation,
        DefaultProblemListFileName);

    if (result.isEmpty()) {
        // download the problem list and save it
        mUhuntApi->allOnlineJudgeProblems();
    } else {
        // file found, load the data
        loadProblemListFromFile(result);
    }
}

void MainWindow::initializeWidgets()
{
    QPushButton *settingsButton = new QPushButton(mUi->tabWidget);
    settingsButton->setText("Settings");
    QObject::connect(settingsButton, &QPushButton::clicked, this, &MainWindow::openSettings);
    mUi->tabWidget->setCornerWidget(settingsButton);

    mUi->pdfViewer->setSaveOnDownload(mSettings.savePDFDocumentsOnDownload());
    mUi->pdfViewer->setNetworkManager(mNetworkManager);
    // Initialize all UVAArenaWidgets and connect them
    mUVAArenaWidgets.push_back(mUi->problemsWidget);
    mUVAArenaWidgets.push_back(mUi->editorWidget);
    mUVAArenaWidgets.push_back(mUi->liveEventsWidget);
    mUVAArenaWidgets.push_back(mUi->profilesWidget);

    for (UVAArenaWidget* widget : mUVAArenaWidgets) {

        widget->setNetworkManager(mNetworkManager);
        widget->setUhuntApi(mUhuntApi);

        // Allow each widget to communicate with the MainWindow
        QObject::connect(widget, &UVAArenaWidget::newUVAArenaEvent,
            this, &MainWindow::onUVAArenaEvent);

        // Allow MainWindow to communicate with each widget
        QObject::connect(this, &MainWindow::newUVAArenaEvent,
            widget, &UVAArenaWidget::onUVAArenaEvent);

        widget->initialize();
    }
}

void MainWindow::loadProblemListFromFile(QString fileName)
{

    QFile file(fileName);

    if (!file.open(QIODevice::ReadOnly)) {

        // TODO: couldn't open the file
        QMessageBox::critical(this, "Read failure",
            "Could not read the default problem list file.");

        return;
    }

    // make sure the default problem list file is not too old
    QFileInfo fileInfo(file);
    QDateTime lastModified = fileInfo.lastModified();

    if (lastModified.daysTo(QDateTime::currentDateTime())
                            > mSettings.problemsUpdateInterval()) {

        // the problem list file is too old, redownload it
        mUhuntApi->allOnlineJudgeProblems();

        return;
    }

    QDataStream dataStream(&file);
    QByteArray data;

    dataStream >> data;

    setProblemMap(Uhunt::problemMapFromJson(data));
}

void MainWindow::loadPDFByProblemNumber(int problemNumber)
{
    QDir saveDirectory(
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
        );

    if (!saveDirectory.exists())
        saveDirectory.mkpath(".");

    if (!saveDirectory.cd("problems")) {
        saveDirectory.mkdir("problems");
        saveDirectory.cd("problems");
    }

    QString pdfFileName =
        saveDirectory.filePath(tr("%1.pdf").arg(problemNumber));

    if (QFile::exists(pdfFileName)) {

        mUi->tabWidget->setCurrentWidget(mUi->solveTab);
        mUi->pdfViewer->loadDocument(pdfFileName);

    } else {
        mUi->pdfViewer->downloadPDF(UVAProblemPDFUrl.arg(problemNumber / 100)
                                                   .arg(problemNumber)
                                                   , pdfFileName);
    }
}
#include <QDesktopServices>
void MainWindow::showProblem(int problemNumber)
{
    typedef UVAArenaSettings::ProblemFormat ProblemFormat;

    if (mSettings.problemFormatPreference() == ProblemFormat::HTML) {

        QDesktopServices::openUrl(QUrl(UVAProblemHTMLUrl.arg(problemNumber / 100).arg(problemNumber)));

    } else { // PDF

        mUi->tabWidget->setCurrentWidget(mUi->solveTab);
        loadPDFByProblemNumber(problemNumber);
    }
}

void MainWindow::openSettings()
{
    SettingsDialog dialog;
    QString oldUserName = mSettings.userName();
    if (dialog.exec() == QDialog::Accepted) {
        // emit new uva arena event
        mUi->pdfViewer->setSaveOnDownload(mSettings.savePDFDocumentsOnDownload());
        QString newUserName = mSettings.userName();
        if (oldUserName != newUserName) {// new user, get the id

            QObject::connect(mUhuntApi.get(), &Uhunt::userIDDownloaded,
                [this, newUserName](QString userName, int userId) {
                if (userName == newUserName) { // Make sure we're talking about the same person
                    this->mSettings.setUserId(userId);
                }

                emit newUVAArenaEvent(UVAArenaWidget::UVAArenaEvent::UPDATE_SETTINGS, QVariant());
            });

            mUhuntApi->userIDFromUserName(mSettings.userName());
        }
    }
}
<commit_msg>MainWindow: window title changes based on current user<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "settingsdialog.h"

#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QDataStream>
#include <QDateTime>
#include <QDir>
#include <QStandardPaths>
#include <QUrl>
#include <QPushButton>

using namespace uva;

const QString DefaultProblemListFileName = "problemlist.json";

const QString UVAProblemHTMLUrl = "https://uva.onlinejudge.org/external/%1/%2.html"; // 1 = container, 2 = problem number
const QString UVAProblemPDFUrl = "https://uva.onlinejudge.org/external/%1/%2.pdf"; // 1 = container, 2 = problem number

MainWindow::MainWindow(std::shared_ptr<QNetworkAccessManager> networkManager, QWidget *parent) :
    QMainWindow(parent),
    mNetworkManager(networkManager),
    mUi(new Ui::MainWindow)
{
    mUi->setupUi(this);

    this->setWindowState(Qt::WindowState::WindowMaximized);
    statusBar()->showMessage("Welcome to UVA-Arena.");

    mUhuntApi = std::make_shared<Uhunt>(mNetworkManager);

#ifdef _DEBUG
    // if we're testing, save to test directories
    QStandardPaths::setTestModeEnabled(true);
#endif

    initialize();
}

MainWindow::~MainWindow()
{
}

std::shared_ptr<Uhunt::ProblemMap> MainWindow::getProblemMap()
{
    return mProblems;
}

void MainWindow::onUVAArenaEvent(UVAArenaWidget::UVAArenaEvent arenaEvent, QVariant metaData)
{
    typedef UVAArenaWidget::UVAArenaEvent UVAArenaEvent;

    switch (arenaEvent)
    {
    case UVAArenaEvent::UPDATE_STATUS:
        statusBar()->showMessage(metaData.toString(), 2000);
        break;

    case UVAArenaEvent::SHOW_PROBLEM:
        showProblem(metaData.toInt());
        break;

    default:
        break;
    }
}

void MainWindow::onAllProblemsDownloaded(QByteArray data)
{
    // set the file to save to
    QDir saveDirectory(
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
    );

    if (!saveDirectory.exists())
        saveDirectory.mkpath(saveDirectory.path());

    QString fileName = saveDirectory.filePath(DefaultProblemListFileName);
    QFile file(fileName);

    if (!file.open(QIODevice::WriteOnly)) {

        // couldn't open the file
        QMessageBox::critical(this, "Write failure",
            "Could not write to the default problem list file:\n"
            + fileName);

        return;
    }

    // write the problem list data to the default problems list file
    QDataStream dataStream(&file);
    dataStream << data;

    setProblemMap(Uhunt::problemMapFromJson(data));
}

void MainWindow::setProblemMap(Uhunt::ProblemMap problemMap)
{
    mProblems.reset(new Uhunt::ProblemMap);
    *mProblems = std::move(problemMap);

    Uhunt::ProblemMap::const_iterator it = mProblems->begin();

    mUi->problemsWidget->setProblemMap(getProblemMap());
    mUi->liveEventsWidget->setProblemMap(getProblemMap());
    statusBar()->showMessage("Problem list loaded", 2000);
}

void MainWindow::initialize()
{
    initializeData();
    initializeWidgets();
}

void MainWindow::initializeData()
{
    //connect problem list byte downloaded array signal
    QObject::connect(mUhuntApi.get(), &Uhunt::allProblemsDownloaded,
        this, &MainWindow::onAllProblemsDownloaded);

    // check if problem list is already downloaded
    QString result = QStandardPaths::locate(QStandardPaths::AppDataLocation,
        DefaultProblemListFileName);

    if (result.isEmpty()) {
        // download the problem list and save it
        mUhuntApi->allOnlineJudgeProblems();
    } else {
        // file found, load the data
        loadProblemListFromFile(result);
    }
}

void MainWindow::initializeWidgets()
{
    if (mSettings.userId() != -1)
        setWindowTitle("UVA Arena - " + mSettings.userName());

    QPushButton *settingsButton = new QPushButton(mUi->tabWidget);
    settingsButton->setText("Settings");
    QObject::connect(settingsButton, &QPushButton::clicked, this, &MainWindow::openSettings);
    mUi->tabWidget->setCornerWidget(settingsButton);

    mUi->pdfViewer->setSaveOnDownload(mSettings.savePDFDocumentsOnDownload());
    mUi->pdfViewer->setNetworkManager(mNetworkManager);
    // Initialize all UVAArenaWidgets and connect them
    mUVAArenaWidgets.push_back(mUi->problemsWidget);
    mUVAArenaWidgets.push_back(mUi->editorWidget);
    mUVAArenaWidgets.push_back(mUi->liveEventsWidget);
    mUVAArenaWidgets.push_back(mUi->profilesWidget);

    for (UVAArenaWidget* widget : mUVAArenaWidgets) {

        widget->setNetworkManager(mNetworkManager);
        widget->setUhuntApi(mUhuntApi);

        // Allow each widget to communicate with the MainWindow
        QObject::connect(widget, &UVAArenaWidget::newUVAArenaEvent,
            this, &MainWindow::onUVAArenaEvent);

        // Allow MainWindow to communicate with each widget
        QObject::connect(this, &MainWindow::newUVAArenaEvent,
            widget, &UVAArenaWidget::onUVAArenaEvent);

        widget->initialize();
    }
}

void MainWindow::loadProblemListFromFile(QString fileName)
{

    QFile file(fileName);

    if (!file.open(QIODevice::ReadOnly)) {

        // TODO: couldn't open the file
        QMessageBox::critical(this, "Read failure",
            "Could not read the default problem list file.");

        return;
    }

    // make sure the default problem list file is not too old
    QFileInfo fileInfo(file);
    QDateTime lastModified = fileInfo.lastModified();

    if (lastModified.daysTo(QDateTime::currentDateTime())
                            > mSettings.problemsUpdateInterval()) {

        // the problem list file is too old, redownload it
        mUhuntApi->allOnlineJudgeProblems();

        return;
    }

    QDataStream dataStream(&file);
    QByteArray data;

    dataStream >> data;

    setProblemMap(Uhunt::problemMapFromJson(data));
}

void MainWindow::loadPDFByProblemNumber(int problemNumber)
{
    QDir saveDirectory(
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
        );

    if (!saveDirectory.exists())
        saveDirectory.mkpath(".");

    if (!saveDirectory.cd("problems")) {
        saveDirectory.mkdir("problems");
        saveDirectory.cd("problems");
    }

    QString pdfFileName =
        saveDirectory.filePath(tr("%1.pdf").arg(problemNumber));

    if (QFile::exists(pdfFileName)) {

        mUi->tabWidget->setCurrentWidget(mUi->solveTab);
        mUi->pdfViewer->loadDocument(pdfFileName);

    } else {
        mUi->pdfViewer->downloadPDF(UVAProblemPDFUrl.arg(problemNumber / 100)
                                                   .arg(problemNumber)
                                                   , pdfFileName);
    }
}
#include <QDesktopServices>
void MainWindow::showProblem(int problemNumber)
{
    typedef UVAArenaSettings::ProblemFormat ProblemFormat;

    if (mSettings.problemFormatPreference() == ProblemFormat::HTML) {

        QDesktopServices::openUrl(QUrl(UVAProblemHTMLUrl.arg(problemNumber / 100).arg(problemNumber)));

    } else { // PDF

        mUi->tabWidget->setCurrentWidget(mUi->solveTab);
        loadPDFByProblemNumber(problemNumber);
    }
}

void MainWindow::openSettings()
{
    SettingsDialog dialog;
    QString oldUserName = mSettings.userName();
    if (dialog.exec() == QDialog::Accepted) {
        // emit new uva arena event
        mUi->pdfViewer->setSaveOnDownload(mSettings.savePDFDocumentsOnDownload());
        QString newUserName = mSettings.userName();
        if (oldUserName != newUserName) {// new user, get the id

            QObject::connect(mUhuntApi.get(), &Uhunt::userIDDownloaded,
                [this, newUserName](QString userName, int userId) {
                if (userName == newUserName) { // Make sure we're talking about the same person
                    this->mSettings.setUserId(userId);
                    setWindowTitle("UVA Arena - " + mSettings.userName());
                }

                emit newUVAArenaEvent(UVAArenaWidget::UVAArenaEvent::UPDATE_SETTINGS, QVariant());
            });

            mUhuntApi->userIDFromUserName(mSettings.userName());
        }
    }
}
<|endoftext|>


<commit_before>#include "game.hpp"

bool Game::uciHandler(std::string str) {
	std::vector<std::string> cmd = getStringArray(str);
		if(cmd[0] == "isready") {
			std::cout << "readyok" << std::endl;
		} else if(cmd[0] == "position") {
			gameHash.clear();
			gameHash.resize(0);
			hash_decrement = 0;
			if(cmd[1] == "startpos") {
				game_board.setFen(game_board.startpos_fen);
				hash_decrement = 0;
				hashAge = 0;
				if(cmd.size() > 3) {
					if(cmd[2] == "moves") {
						for(unsigned int i = 3; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			} else if(cmd[1] == "fen") {
				std::string fen;
				unsigned int pos = 2;

				for(unsigned int i = 2; i < 8; ++i) {
					fen += cmd[i];
					if(i != cmd.size() - 1) {
						fen.push_back(' ');
					}
					++pos;
				}

				game_board.setFen(fen);
				if(cmd.size() > pos) {
					if(cmd[pos] == "moves") {
						for(unsigned int i = pos + 1; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			}
		} else if(cmd[0] == "go") {
			if(cmd[1] == "depth") {
				max_depth = std::stoi(cmd[2]);
			  goFixedDepth();
			} else if(cmd[1] == "movetime") {
				goFixedTime(std::stoi(cmd[2]), false);
			} else if(cmd[1] == "infinite") {
				max_depth = 99;
				goFixedDepth();
			} else {
				wtime = 0, btime = 0;
				winc = 0, binc = 0, movestogo = 0, movestogoEnable = false;
				for(unsigned int i = 1; i < cmd.size(); ++i) {
					if(cmd[i] == "wtime") {
						wtime = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "btime") {
						btime = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "winc") {
						winc = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "binc") {
						binc = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "movestogo") {
						movestogoEnable = true;
						movestogo = std::stoi(cmd[i+1]);
					}
				}

				goTournament();
			}
		} else if(cmd[0] == "posmoves") {
			MoveArray moves;
			game_board.bitBoardMoveGenerator(moves, stress);

			for(unsigned int i = 0; i < moves.count; ++i) {
				std::cout << moves.moveArray[i].getMoveString();
				std::cout << std::endl;
			}

			std::cout << game_board.getEvaluate() / PAWN_EV.mg * 100 << std::endl;
			std::cout << game_board.getFen() << std::endl;

			std::cout << "inCheck (WHITE) : " << game_board.inCheck(WHITE) << std::endl;
			std::cout << "inCheck (BLACK) : " << game_board.inCheck(BLACK) << std::endl;
			std::cout << "color_hash: " << game_board.getColorHash() << std::endl;
		} else if(cmd[0] == "move") {
			move(cmd[1]);
		} else if(cmd[0] == "quit") {
			return false;
		} else if(cmd[0] == "uci") {
			idPrint();
			option.print();
			std::cout << "uciok" << std::endl;
		} else if(cmd[0] == "bench") {
			std::cout << "Benchmarking (15 sec)..." << std::endl;
			game_board.stress = 0;
			double st = clock();
			while((clock() - st) / CLOCKS_PER_SEC < 15) {
				for(unsigned int i = 0; i < 10000000; ++i) {
					game_board.bitBoardMoveGenerator(moveArray[0], game_board.stress);
				}
			}
			std::cout << (int64_t)(game_board.stress / ((clock() - st) / CLOCKS_PER_SEC)) / 10000 << " scores" << std::endl;
		} else if(cmd[0] == "goback") {
			game_board.goBack();
			--hash_decrement;
		} else if(cmd[0] == "perft") {
			int k;
			k = std::stoi(cmd[1]);
			for(int i = 1; i <= k; ++i) {
				combinations = 0;
				double st = clock();
				uint64_t count = perft(i);
				std::cout << "Depth: " << i << "; count: " << combinations;
				std::cout << "; speed: " << (int64_t)((double)count / (((double)clock() - (double)st) / (double)CLOCKS_PER_SEC)) << std::endl;
			}
		} else if(cmd[0] == "setoption" && cmd[1] == "name") {
			if(cmd[2] == "Clear" && cmd[3] == "Hash") {
				clearCash();
				std::cout << "info hashfull 0" << std::endl;
			} else if(cmd[2] == "Hash" && cmd[3] == "value") {
				int hash_size = std::stoi(cmd[4]);

				hash_size = std::min(hash_size, option.max_hash_size);
				hash_size = std::max(hash_size, option.min_hash_size);

				setHashSize(hash_size);
			}  else if(cmd[2] == "Move" && cmd[3] == "Overhead" && cmd[4] == "value") {
				option.moveOverhead = std::stoi(cmd[5]);
				option.moveOverhead = std::min(option.moveOverhead, option.maxMoveOverhead);
				option.moveOverhead = std::max(option.moveOverhead, option.minMoveOverhead);
			} else if(cmd[2] == "UCI_AnalyseMode" && cmd[3] == "value") {
				if(cmd[4] == "true") {
					option.UCI_AnalyseMode = true;
				} else if(cmd[4] == "false") {
					option.UCI_AnalyseMode = false;
				}
			}
		}

		return true;
}

void Game::idPrint() {
	std::cout << "id name Zevra 20180128" << std::endl;
	std::cout << "id author Oleg Smirnov @sovaz1997" << std::endl;
}<commit_msg>Обновление id name<commit_after>#include "game.hpp"

bool Game::uciHandler(std::string str) {
	std::vector<std::string> cmd = getStringArray(str);
		if(cmd[0] == "isready") {
			std::cout << "readyok" << std::endl;
		} else if(cmd[0] == "position") {
			gameHash.clear();
			gameHash.resize(0);
			hash_decrement = 0;
			if(cmd[1] == "startpos") {
				game_board.setFen(game_board.startpos_fen);
				hash_decrement = 0;
				hashAge = 0;
				if(cmd.size() > 3) {
					if(cmd[2] == "moves") {
						for(unsigned int i = 3; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			} else if(cmd[1] == "fen") {
				std::string fen;
				unsigned int pos = 2;

				for(unsigned int i = 2; i < 8; ++i) {
					fen += cmd[i];
					if(i != cmd.size() - 1) {
						fen.push_back(' ');
					}
					++pos;
				}

				game_board.setFen(fen);
				if(cmd.size() > pos) {
					if(cmd[pos] == "moves") {
						for(unsigned int i = pos + 1; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			}
		} else if(cmd[0] == "go") {
			if(cmd[1] == "depth") {
				max_depth = std::stoi(cmd[2]);
			  goFixedDepth();
			} else if(cmd[1] == "movetime") {
				goFixedTime(std::stoi(cmd[2]), false);
			} else if(cmd[1] == "infinite") {
				max_depth = 99;
				goFixedDepth();
			} else {
				wtime = 0, btime = 0;
				winc = 0, binc = 0, movestogo = 0, movestogoEnable = false;
				for(unsigned int i = 1; i < cmd.size(); ++i) {
					if(cmd[i] == "wtime") {
						wtime = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "btime") {
						btime = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "winc") {
						winc = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "binc") {
						binc = std::stoll(cmd[i + 1]);
					} else if(cmd[i] == "movestogo") {
						movestogoEnable = true;
						movestogo = std::stoi(cmd[i+1]);
					}
				}

				goTournament();
			}
		} else if(cmd[0] == "posmoves") {
			MoveArray moves;
			game_board.bitBoardMoveGenerator(moves, stress);

			for(unsigned int i = 0; i < moves.count; ++i) {
				std::cout << moves.moveArray[i].getMoveString();
				std::cout << std::endl;
			}

			std::cout << game_board.getEvaluate() / PAWN_EV.mg * 100 << std::endl;
			std::cout << game_board.getFen() << std::endl;

			std::cout << "inCheck (WHITE) : " << game_board.inCheck(WHITE) << std::endl;
			std::cout << "inCheck (BLACK) : " << game_board.inCheck(BLACK) << std::endl;
			std::cout << "color_hash: " << game_board.getColorHash() << std::endl;
		} else if(cmd[0] == "move") {
			move(cmd[1]);
		} else if(cmd[0] == "quit") {
			return false;
		} else if(cmd[0] == "uci") {
			idPrint();
			option.print();
			std::cout << "uciok" << std::endl;
		} else if(cmd[0] == "bench") {
			std::cout << "Benchmarking (15 sec)..." << std::endl;
			game_board.stress = 0;
			double st = clock();
			while((clock() - st) / CLOCKS_PER_SEC < 15) {
				for(unsigned int i = 0; i < 10000000; ++i) {
					game_board.bitBoardMoveGenerator(moveArray[0], game_board.stress);
				}
			}
			std::cout << (int64_t)(game_board.stress / ((clock() - st) / CLOCKS_PER_SEC)) / 10000 << " scores" << std::endl;
		} else if(cmd[0] == "goback") {
			game_board.goBack();
			--hash_decrement;
		} else if(cmd[0] == "perft") {
			int k;
			k = std::stoi(cmd[1]);
			for(int i = 1; i <= k; ++i) {
				combinations = 0;
				double st = clock();
				uint64_t count = perft(i);
				std::cout << "Depth: " << i << "; count: " << combinations;
				std::cout << "; speed: " << (int64_t)((double)count / (((double)clock() - (double)st) / (double)CLOCKS_PER_SEC)) << std::endl;
			}
		} else if(cmd[0] == "setoption" && cmd[1] == "name") {
			if(cmd[2] == "Clear" && cmd[3] == "Hash") {
				clearCash();
				std::cout << "info hashfull 0" << std::endl;
			} else if(cmd[2] == "Hash" && cmd[3] == "value") {
				int hash_size = std::stoi(cmd[4]);

				hash_size = std::min(hash_size, option.max_hash_size);
				hash_size = std::max(hash_size, option.min_hash_size);

				setHashSize(hash_size);
			}  else if(cmd[2] == "Move" && cmd[3] == "Overhead" && cmd[4] == "value") {
				option.moveOverhead = std::stoi(cmd[5]);
				option.moveOverhead = std::min(option.moveOverhead, option.maxMoveOverhead);
				option.moveOverhead = std::max(option.moveOverhead, option.minMoveOverhead);
			} else if(cmd[2] == "UCI_AnalyseMode" && cmd[3] == "value") {
				if(cmd[4] == "true") {
					option.UCI_AnalyseMode = true;
				} else if(cmd[4] == "false") {
					option.UCI_AnalyseMode = false;
				}
			}
		}

		return true;
}

void Game::idPrint() {
	std::cout << "id name Zevra 20180131" << std::endl;
	std::cout << "id author Oleg Smirnov @sovaz1997" << std::endl;
}<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkImageGenerator.h>

#include <itksys/SystemTools.hxx>

class mitkIOUtilTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkIOUtilTestSuite);
  MITK_TEST(TestTempMethods);
  MITK_TEST(TestLoadAndSaveImage);
  MITK_TEST(TestLoadAndSavePointSet);
  MITK_TEST(TestLoadAndSaveSurface);
  CPPUNIT_TEST_SUITE_END();

private:

  std::string m_ImagePath;
  std::string m_SurfacePath;
  std::string m_PointSetPath;

public:

  void setUp()
  {
    m_ImagePath = GetTestDataFilePath("Pic3D.nrrd");
    m_SurfacePath = GetTestDataFilePath("binary.stl");
    m_PointSetPath = GetTestDataFilePath("pointSet.mps");
  }

  void TestTempMethods()
  {
    std::string tmpPath = mitk::IOUtil::GetTempPath();
    CPPUNIT_ASSERT(!tmpPath.empty());

    std::ofstream tmpFile;
    std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpFile);
    CPPUNIT_ASSERT(tmpFile && tmpFile.is_open());
    CPPUNIT_ASSERT(tmpFilePath.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpFilePath.substr(0, tmpPath.size()) == tmpPath);

    tmpFile.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath.c_str()) == 0);

    std::string programPath = mitk::IOUtil::GetProgramPath();
    CPPUNIT_ASSERT(!programPath.empty());
    std::ofstream tmpFile2;
    std::string tmpFilePath2 = mitk::IOUtil::CreateTemporaryFile(tmpFile2, "my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpFile2 && tmpFile2.is_open());
    CPPUNIT_ASSERT(tmpFilePath2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath2.substr(0, programPath.size()) == programPath);
    tmpFile2.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath2.c_str()) == 0);

    std::ofstream tmpFile3;
    std::string tmpFilePath3 = mitk::IOUtil::CreateTemporaryFile(tmpFile3, std::ios_base::binary,
                                                                 "my-XXXXXX.TXT", programPath);
    CPPUNIT_ASSERT(tmpFile3 && tmpFile3.is_open());
    CPPUNIT_ASSERT(tmpFilePath3.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath3.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 13, 3) == "my-");
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 4) == ".TXT");
    tmpFile3.close();
    //CPPUNIT_ASSERT(std::remove(tmpFilePath3.c_str()) == 0)

    CPPUNIT_ASSERT_THROW(mitk::IOUtil::CreateTemporaryFile(tmpFile2, "XX"), mitk::Exception);

    std::string tmpDir = mitk::IOUtil::CreateTemporaryDirectory();
    CPPUNIT_ASSERT(tmpDir.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpDir.substr(0, tmpPath.size()) == tmpPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir.c_str()));

    std::string tmpDir2 = mitk::IOUtil::CreateTemporaryDirectory("my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpDir2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpDir2.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir2.c_str()));
  }

  void TestLoadAndSaveImage()
  {
    mitk::Image::Pointer img1 = mitk::IOUtil::LoadImage(m_ImagePath);
    CPPUNIT_ASSERT( img1.IsNotNull());

    std::ofstream tmpStream;
    std::string imagePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nrrd");
    tmpStream.close();
    std::string imagePath2 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nii.gz");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveImage(img1, imagePath));
    CPPUNIT_ASSERT(mitk::IOUtil::SaveBaseData(img1.GetPointer(), imagePath2));

    //load data which does not exist
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::LoadImage("fileWhichDoesNotExist.nrrd"), mitk::Exception);

    //delete the files after the test is done
    std::remove(imagePath.c_str());
    std::remove(imagePath2.c_str());

    mitk::Image::Pointer relativImage = mitk::ImageGenerator::GenerateGradientImage<float>(4,4,4,1);
    std::string imagePath3 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd");
    tmpStream.close();
    mitk::IOUtil::SaveImage(relativImage, imagePath3);
    CPPUNIT_ASSERT_NO_THROW(mitk::IOUtil::LoadImage(imagePath3));
    std::remove(imagePath3.c_str());
  }

  void TestLoadAndSavePointSet()
  {
    mitk::PointSet::Pointer pointset = mitk::IOUtil::LoadPointSet(m_PointSetPath);
    CPPUNIT_ASSERT( pointset.IsNotNull());

    std::ofstream tmpStream;
    std::string pointSetPath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithoutDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.xXx");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithDefaultExtension));

    // test if defaultextension is inserted if no extension is present
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithoutDefaultExtension.c_str()));

    //delete the files after the test is done
    std::remove(pointSetPath.c_str());
    std::remove(pointSetPathWithDefaultExtension.c_str());
    std::remove(pointSetPathWithoutDefaultExtension.c_str());
  }

  void TestLoadAndSaveSurface()
  {
    mitk::Surface::Pointer surface = mitk::IOUtil::LoadSurface(m_SurfacePath);
    CPPUNIT_ASSERT( surface.IsNotNull());

    std::ofstream tmpStream;
    std::string surfacePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffsurface-XXXXXX.stl");

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveSurface(surface, surfacePath));

    // test if exception is thrown as expected on unknown extsension
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveSurface(surface,"testSurface.xXx"), mitk::Exception);

    //delete the files after the test is done
    std::remove(surfacePath.c_str());
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkIOUtil)
<commit_msg>added test for new method mitk::IOUtil::CreateTemporaryFile()<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkImageGenerator.h>

#include <itksys/SystemTools.hxx>

class mitkIOUtilTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkIOUtilTestSuite);
  MITK_TEST(TestTempMethods);
  MITK_TEST(TestLoadAndSaveImage);
  MITK_TEST(TestLoadAndSavePointSet);
  MITK_TEST(TestLoadAndSaveSurface);
  CPPUNIT_TEST_SUITE_END();

private:

  std::string m_ImagePath;
  std::string m_SurfacePath;
  std::string m_PointSetPath;

public:

  void setUp()
  {
    m_ImagePath = GetTestDataFilePath("Pic3D.nrrd");
    m_SurfacePath = GetTestDataFilePath("binary.stl");
    m_PointSetPath = GetTestDataFilePath("pointSet.mps");
  }

  void TestTempMethods()
  {
    std::string tmpPath = mitk::IOUtil::GetTempPath();
    CPPUNIT_ASSERT(!tmpPath.empty());

    std::ofstream tmpFile;
    std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpFile);
    CPPUNIT_ASSERT(tmpFile && tmpFile.is_open());
    CPPUNIT_ASSERT(tmpFilePath.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpFilePath.substr(0, tmpPath.size()) == tmpPath);

    tmpFile.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath.c_str()) == 0);

    std::string programPath = mitk::IOUtil::GetProgramPath();
    CPPUNIT_ASSERT(!programPath.empty());
    std::ofstream tmpFile2;
    std::string tmpFilePath2 = mitk::IOUtil::CreateTemporaryFile(tmpFile2, "my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpFile2 && tmpFile2.is_open());
    CPPUNIT_ASSERT(tmpFilePath2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath2.substr(0, programPath.size()) == programPath);
    tmpFile2.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath2.c_str()) == 0);

    std::ofstream tmpFile3;
    std::string tmpFilePath3 = mitk::IOUtil::CreateTemporaryFile(tmpFile3, std::ios_base::binary,
                                                                 "my-XXXXXX.TXT", programPath);
    CPPUNIT_ASSERT(tmpFile3 && tmpFile3.is_open());
    CPPUNIT_ASSERT(tmpFilePath3.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath3.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 13, 3) == "my-");
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 4) == ".TXT");
    tmpFile3.close();
    //CPPUNIT_ASSERT(std::remove(tmpFilePath3.c_str()) == 0)

    std::string tmpFilePath4 = mitk::IOUtil::CreateTemporaryFile();
    std::ofstream file;
    file.open(tmpFilePath4.c_str());
    CPPUNIT_ASSERT_MESSAGE("Testing if file exists after CreateTemporaryFile()",file.is_open());

    CPPUNIT_ASSERT_THROW(mitk::IOUtil::CreateTemporaryFile(tmpFile2, "XX"), mitk::Exception);

    std::string tmpDir = mitk::IOUtil::CreateTemporaryDirectory();
    CPPUNIT_ASSERT(tmpDir.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpDir.substr(0, tmpPath.size()) == tmpPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir.c_str()));

    std::string tmpDir2 = mitk::IOUtil::CreateTemporaryDirectory("my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpDir2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpDir2.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir2.c_str()));
  }

  void TestLoadAndSaveImage()
  {
    mitk::Image::Pointer img1 = mitk::IOUtil::LoadImage(m_ImagePath);
    CPPUNIT_ASSERT( img1.IsNotNull());

    std::ofstream tmpStream;
    std::string imagePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nrrd");
    tmpStream.close();
    std::string imagePath2 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nii.gz");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveImage(img1, imagePath));
    CPPUNIT_ASSERT(mitk::IOUtil::SaveBaseData(img1.GetPointer(), imagePath2));

    //load data which does not exist
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::LoadImage("fileWhichDoesNotExist.nrrd"), mitk::Exception);

    //delete the files after the test is done
    std::remove(imagePath.c_str());
    std::remove(imagePath2.c_str());

    mitk::Image::Pointer relativImage = mitk::ImageGenerator::GenerateGradientImage<float>(4,4,4,1);
    std::string imagePath3 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd");
    tmpStream.close();
    mitk::IOUtil::SaveImage(relativImage, imagePath3);
    CPPUNIT_ASSERT_NO_THROW(mitk::IOUtil::LoadImage(imagePath3));
    std::remove(imagePath3.c_str());
  }

  void TestLoadAndSavePointSet()
  {
    mitk::PointSet::Pointer pointset = mitk::IOUtil::LoadPointSet(m_PointSetPath);
    CPPUNIT_ASSERT( pointset.IsNotNull());

    std::ofstream tmpStream;
    std::string pointSetPath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithoutDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.xXx");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithDefaultExtension));

    // test if defaultextension is inserted if no extension is present
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithoutDefaultExtension.c_str()));

    //delete the files after the test is done
    std::remove(pointSetPath.c_str());
    std::remove(pointSetPathWithDefaultExtension.c_str());
    std::remove(pointSetPathWithoutDefaultExtension.c_str());
  }

  void TestLoadAndSaveSurface()
  {
    mitk::Surface::Pointer surface = mitk::IOUtil::LoadSurface(m_SurfacePath);
    CPPUNIT_ASSERT( surface.IsNotNull());

    std::ofstream tmpStream;
    std::string surfacePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffsurface-XXXXXX.stl");

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveSurface(surface, surfacePath));

    // test if exception is thrown as expected on unknown extsension
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveSurface(surface,"testSurface.xXx"), mitk::Exception);

    //delete the files after the test is done
    std::remove(surfacePath.c_str());
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkIOUtil)
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "Console.hpp"

#include <memory>

using namespace warbler;

class ConsoleTest
{
public:
    static void noopCommandHandler(const std::shared_ptr<const std::vector<ConsoleArg>> &args) {};
    static const std::shared_ptr<std::vector<ConsoleArgType>> args;
};

const std::shared_ptr<std::vector<ConsoleArgType>> ConsoleTest::args = std::make_shared<std::vector<ConsoleArgType>>();

TEST(constructor, default_constructor)
{
    Console c;
}

TEST(methods, registerCommand)
{
    Console c;
    c.registerCommand("test", ConsoleTest::noopCommandHandler, ConsoleTest::args);
}

TEST(methods, registerCommand_null_func_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("test", nullptr, ConsoleTest::args));
}

TEST(methods, registerCommand_empty_name_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}<commit_msg>Modify a couple tests to use asserts.<commit_after>#include "gtest/gtest.h"
#include "Console.hpp"

#include <memory>

using namespace warbler;

class ConsoleTest
{
public:
    static void noopCommandHandler(const std::shared_ptr<const std::vector<ConsoleArg>> &args) {};
    static const std::shared_ptr<std::vector<ConsoleArgType>> args;
};

const std::shared_ptr<std::vector<ConsoleArgType>> ConsoleTest::args = std::make_shared<std::vector<ConsoleArgType>>();

TEST(constructor, default_constructor)
{
    ASSERT_NO_THROW(Console c);
}

TEST(methods, registerCommand)
{
    Console c;
    ASSERT_NO_THROW(c.registerCommand("test", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}

TEST(methods, registerCommand_null_func_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("test", nullptr, ConsoleTest::args));
}

TEST(methods, registerCommand_empty_name_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}<|endoftext|>