<commit_before>#include <iostream>

#include "Socket.h"
#include "client.h"
#include "GameState.h"
#include "utilitary.h"

//Les définitions ci dessous sont toutes les valeurs que peut avoir l'attribut 'status' de la class de base GameState.
//Valeurs générales :
enum STATUS
{
    STATUS_DEFAULT = 0,
    STATUS_BAD_ENTRY = -1,
    STATUS_DISCONNECT = -2,
    STATUS_RETURNMENU = -3,
    STATUS_QUIT = -4
};

enum UNLOGGED
{
    UNLOGGED_CONNECTED = 1,
    UNLOGGED_CONNECT = 2,
    UNLOGGED_REGISTER = 3
};

enum MENU
{
    MENU_MANAGEPLAYERS = 1,
    MENU_MANAGEINFRASTRUCTURES = 2,
    MENU_AUCTIONHOUSE = 3,
    MENU_CONNECTEDLIST = 4
};

using namespace std;

GameState::GameState(Client * client) : client_(client), status_(STATUS_DEFAULT) {}

GameState::~GameState() {}

//Intro-------------------------------------------------------------------------------
IntroState::IntroState(Client * client) : GameState(client) {}
void IntroState::handleEvents() {}
void IntroState::logic()
{
    client_->setNextState(STATE_UNLOGGED);
}
void IntroState::display()
{
    cout<<"BienvenuS dans le systme !"<<endl; //Rework
}

//Unlogged-------------------------------------------------------------------------
UnloggedState::UnloggedState(Client * client) : GameState(client)
{
    cout<<"Entrez l'option souhaité avec les paramètres requis délimités par un espace."<<endl;
    cout<<"Exemple : '1 Usr mdp'"<<endl;
    cout<<endl;
    display();
}
void UnloggedState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec); //Status est modifié dans parse.
}

void UnloggedState::logic()
{
    switch (status_) { //status_ est modifié dans handleEvent
    case UNLOGGED_CONNECT :
        //envoyer et traiter les données du serveur.
        status_ = UNLOGGED_CONNECTED;
        client_->setNextState(STATE_MENU);
        break;
    case UNLOGGED_REGISTER :
        //envoyer et traiter les données du serveur.
        break;
    case STATUS_QUIT :
        client_->setNextState(STATE_EXIT);
        break;
    }
}
void UnloggedState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Se connecter : 1 - Nom d'utilisateur - Mot de passe"<<endl;
        cout<<"S'enregistrer : 2 - Nom d'utilisateur - Mot de passe"<<endl;
        cout<<"Quitter : Q"<<endl;
        cout<<endl;
        break;
    case UNLOGGED_CONNECTED :
        cout<<"Connecté."<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }

}

void UnloggedState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true) //S'il n'y a pas d'entrée utilisateur
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1) //Si le premier token est plus long qu'un caractèred
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) { //On switch sur le premier caractère
            case '1' : //Demande de connection
                if (inputVec.size() == 3) {
                    nameInput = inputVec[1];
                    passInput = inputVec[2];
                    status_ = UNLOGGED_CONNECT;
                }
                else {
                    status_ = STATUS_BAD_ENTRY;
                }
                break;
            case '2' : //Demande d'enregistrement
                if (inputVec.size() == 3) {
                    nameInput = inputVec[1];
                    passInput = inputVec[2];
                    status_ = UNLOGGED_REGISTER;
                }
                else {
                    status_ = STATUS_BAD_ENTRY;
                }
                break;
            case 'q' : //Demande de quit
            case 'Q' :
                status_ = STATUS_QUIT;
                break;
            default : //Si n'importe quoi d'autre est entré
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}
//Menu-------------------------------------------------------------------------

MenuState::MenuState(Client * client) : GameState(client)
{
    display();
}
void MenuState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}
void MenuState::logic()
{
    switch (status_) {
    case MENU_MANAGEPLAYERS :
        client_->setNextState(STATE_MANAGE_PLAYERS);
        break;
    case MENU_MANAGEINFRASTRUCTURES :
        client_->setNextState(STATE_MANAGE_INFRASTRUCTURES);
        break;
    case MENU_AUCTIONHOUSE :
        client_->setNextState(STATE_AUCTION_HOUSE);
        break;
    case MENU_CONNECTEDLIST :
        client_->setNextState(STATE_CONNECTEDLIST);
        break;
    case STATUS_DISCONNECT : //!! effectuer tout ce qui est nécéssaire pour la déconnection ici
        client_->setNextState(STATE_INTRO);
        break;
    case STATUS_QUIT :
        client_->setNextState(STATE_EXIT);
        break;
    }
}
void MenuState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Gérer votre équipe : 1"<<endl;
        cout<<"Gérer vos infrastructures : 2"<<endl;
        cout<<"Accéder à l'hotel de vente : 3"<<endl;
        cout<<"Voir la liste de connectés. : 4"<<endl;
        cout<<"Se déconnecter : 5"<<endl;
        cout<<"Quitter : Q"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void MenuState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else
        {
            switch (option.c_str()[0]) {
            case '1' : //Gestion d'équipe
                status_ = MENU_MANAGEPLAYERS;
                break;
            case '2' : //Gestion des infrastructures
                status_ = MENU_MANAGEINFRASTRUCTURES;
                break;
            case '3' : //Hotel des ventes
                status_ = MENU_AUCTIONHOUSE;
                break;
            case '4' : //Liste de connectés
                status_ = MENU_CONNECTEDLIST;
                break;
            case '5' : //Demande de déconnection
                status_ = STATUS_DISCONNECT;
                break;
            case 'q' :
            case 'Q' : //Demande de quit
                status_ = STATUS_QUIT;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//ManagePlayer-------------------------------------------------------------------------

ManagePlayerState::ManagePlayerState(Client * client) : GameState(client)
{
    display();
}
void ManagePlayerState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}
void ManagePlayerState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}
void ManagePlayerState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Retourner au menu : 1"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void ManagePlayerState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '1' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//ManageInfrastructure-------------------------------------------------------------------------

ManageInfrastructureState::ManageInfrastructureState(Client * client) : GameState(client)
{
    display();
}
void ManageInfrastructureState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}

void ManageInfrastructureState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}

void ManageInfrastructureState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Infrastructures : "<<endl;
        cout<<"Créer une infirmerie. : 1"<<endl; //pour plus tard, spécialiser les messages (créer -> améliorer)
        cout<<"Créer un shop : 2"<<endl;
        cout<<"Revenir au menu : 3"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void ManageInfrastructureState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '3' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//AuctionHouse-------------------------------------------------------------------------

AuctionHouseState::AuctionHouseState(Client * client) : GameState(client)
{
    display();
}
void AuctionHouseState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}

void AuctionHouseState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}

void AuctionHouseState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Hotel des ventes : "<<endl;
        cout<<"Revenir au menu : 1"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void AuctionHouseState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '1' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//ConnectedList--------------------------------------------------------------------------

ConnectedListState::ConnectedListState(Client * client) : GameState(client)
{
    display();
}
void ConnectedListState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}
void ConnectedListState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}
void ConnectedListState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Joueurs connectés : "<<endl;
        cout<<"Revenir au menu : 1"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void ConnectedListState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '1' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//InGame-------------------------------------------------------------------------

InGameState::InGameState(Client * client) : GameState(client) {}
void InGameState::handleEvents() {}
void InGameState::logic() {}
void InGameState::display() {}
<commit_msg>[code]Removed disconnect option (usr can only quit, it will include discon)<commit_after>#include <iostream>

#include "Socket.h"
#include "client.h"
#include "GameState.h"
#include "utilitary.h"

//Les définitions ci dessous sont toutes les valeurs que peut avoir l'attribut 'status' de la class de base GameState.
//Valeurs générales :
enum STATUS
{
    STATUS_DEFAULT = 0,
    STATUS_BAD_ENTRY = -1,
    STATUS_RETURNMENU = -2,
    STATUS_QUIT = -3
};

enum UNLOGGED
{
    UNLOGGED_CONNECTED = 1,
    UNLOGGED_CONNECT = 2,
    UNLOGGED_REGISTER = 3
};

enum MENU
{
    MENU_MANAGEPLAYERS = 1,
    MENU_MANAGEINFRASTRUCTURES = 2,
    MENU_AUCTIONHOUSE = 3,
    MENU_CONNECTEDLIST = 4
};

using namespace std;

GameState::GameState(Client * client) : client_(client), status_(STATUS_DEFAULT) {}

GameState::~GameState() {}

//Intro-------------------------------------------------------------------------------
IntroState::IntroState(Client * client) : GameState(client) {}
void IntroState::handleEvents() {}
void IntroState::logic()
{
    client_->setNextState(STATE_UNLOGGED);
}
void IntroState::display()
{
    cout<<"BienvenuS dans le systme !"<<endl; //Rework
}

//Unlogged-------------------------------------------------------------------------
UnloggedState::UnloggedState(Client * client) : GameState(client)
{
    cout<<"Entrez l'option souhaité avec les paramètres requis délimités par un espace."<<endl;
    cout<<"Exemple : '1 Usr mdp'"<<endl;
    cout<<endl;
    display();
}
void UnloggedState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec); //Status est modifié dans parse.
}

void UnloggedState::logic()
{
    switch (status_) { //status_ est modifié dans handleEvent
    case UNLOGGED_CONNECT :
        //envoyer et traiter les données du serveur.
        status_ = UNLOGGED_CONNECTED;
        client_->setNextState(STATE_MENU);
        break;
    case UNLOGGED_REGISTER :
        //envoyer et traiter les données du serveur.
        break;
    case STATUS_QUIT :
        client_->setNextState(STATE_EXIT);
        break;
    }
}
void UnloggedState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Se connecter : 1 - Nom d'utilisateur - Mot de passe"<<endl;
        cout<<"S'enregistrer : 2 - Nom d'utilisateur - Mot de passe"<<endl;
        cout<<"Quitter : Q"<<endl;
        cout<<endl;
        break;
    case UNLOGGED_CONNECTED :
        cout<<"Connecté."<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }

}

void UnloggedState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true) //S'il n'y a pas d'entrée utilisateur
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1) //Si le premier token est plus long qu'un caractèred
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) { //On switch sur le premier caractère
            case '1' : //Demande de connection
                if (inputVec.size() == 3) {
                    nameInput = inputVec[1];
                    passInput = inputVec[2];
                    status_ = UNLOGGED_CONNECT;
                }
                else {
                    status_ = STATUS_BAD_ENTRY;
                }
                break;
            case '2' : //Demande d'enregistrement
                if (inputVec.size() == 3) {
                    nameInput = inputVec[1];
                    passInput = inputVec[2];
                    status_ = UNLOGGED_REGISTER;
                }
                else {
                    status_ = STATUS_BAD_ENTRY;
                }
                break;
            case 'q' : //Demande de quit
            case 'Q' :
                status_ = STATUS_QUIT;
                break;
            default : //Si n'importe quoi d'autre est entré
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}
//Menu-------------------------------------------------------------------------

MenuState::MenuState(Client * client) : GameState(client)
{
    display();
}
void MenuState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}
void MenuState::logic()
{
    switch (status_) {
    case MENU_MANAGEPLAYERS :
        client_->setNextState(STATE_MANAGE_PLAYERS);
        break;
    case MENU_MANAGEINFRASTRUCTURES :
        client_->setNextState(STATE_MANAGE_INFRASTRUCTURES);
        break;
    case MENU_AUCTIONHOUSE :
        client_->setNextState(STATE_AUCTION_HOUSE);
        break;
    case MENU_CONNECTEDLIST :
        client_->setNextState(STATE_CONNECTEDLIST);
        break;
    case STATUS_QUIT :
        client_->setNextState(STATE_EXIT);
        break;
    }
}
void MenuState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Gérer votre équipe : 1"<<endl;
        cout<<"Gérer vos infrastructures : 2"<<endl;
        cout<<"Accéder à l'hotel de vente : 3"<<endl;
        cout<<"Voir la liste de connectés. : 4"<<endl;
        cout<<"Quitter : Q"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void MenuState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else
        {
            switch (option.c_str()[0]) {
            case '1' : //Gestion d'équipe
                status_ = MENU_MANAGEPLAYERS;
                break;
            case '2' : //Gestion des infrastructures
                status_ = MENU_MANAGEINFRASTRUCTURES;
                break;
            case '3' : //Hotel des ventes
                status_ = MENU_AUCTIONHOUSE;
                break;
            case '4' : //Liste de connectés
                status_ = MENU_CONNECTEDLIST;
                break;
            case 'q' :
            case 'Q' : //Demande de quit
                status_ = STATUS_QUIT;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//ManagePlayer-------------------------------------------------------------------------

ManagePlayerState::ManagePlayerState(Client * client) : GameState(client)
{
    display();
}
void ManagePlayerState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}
void ManagePlayerState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}
void ManagePlayerState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Retourner au menu : 1"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void ManagePlayerState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '1' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//ManageInfrastructure-------------------------------------------------------------------------

ManageInfrastructureState::ManageInfrastructureState(Client * client) : GameState(client)
{
    display();
}
void ManageInfrastructureState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}

void ManageInfrastructureState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}

void ManageInfrastructureState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Infrastructures : "<<endl;
        cout<<"Créer une infirmerie. : 1"<<endl; //pour plus tard, spécialiser les messages (créer -> améliorer)
        cout<<"Créer un shop : 2"<<endl;
        cout<<"Revenir au menu : 3"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void ManageInfrastructureState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '3' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//AuctionHouse-------------------------------------------------------------------------

AuctionHouseState::AuctionHouseState(Client * client) : GameState(client)
{
    display();
}
void AuctionHouseState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}

void AuctionHouseState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}

void AuctionHouseState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Hotel des ventes : "<<endl;
        cout<<"Revenir au menu : 1"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void AuctionHouseState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '1' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//ConnectedList--------------------------------------------------------------------------

ConnectedListState::ConnectedListState(Client * client) : GameState(client)
{
    display();
}
void ConnectedListState::handleEvents()
{
    string inputString;
    getline(cin, inputString);
    vector<string> inputVec = split(inputString, ' ');
    parse(inputVec);
}
void ConnectedListState::logic()
{
    switch (status_) {
    case STATUS_RETURNMENU :
        client_->setNextState(STATE_MENU);
        break;
    }
}
void ConnectedListState::display()
{
    switch (status_) {
    case STATUS_DEFAULT :
        cout<<"Joueurs connectés : "<<endl;
        cout<<"Revenir au menu : 1"<<endl;
        cout<<endl;
        break;
    case STATUS_BAD_ENTRY :
        cout<<"Erreur : votre entrée est incorrecte."<<endl;
        cout<<endl;
        break;
    }
}

void ConnectedListState::parse(vector<string> & inputVec)
{
    if (inputVec.empty() == true)
        status_ = STATUS_BAD_ENTRY;
    else {
        string option = inputVec[0];
        if (option.size() != 1 or inputVec.size() != 1)
            status_ = STATUS_BAD_ENTRY;
        else {
            switch (option.c_str()[0]) {
            case '1' : //Retour au menu
                status_ = STATUS_RETURNMENU;
                break;
            default :
                status_ = STATUS_BAD_ENTRY;
                break;
            }
        }
    }
}

//InGame-------------------------------------------------------------------------

InGameState::InGameState(Client * client) : GameState(client) {}
void InGameState::handleEvents() {}
void InGameState::logic() {}
void InGameState::display() {}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "pthread.h"
#include <atomic>
#include <stdlib.h>
#ifndef XV6_USER
#include <string.h>
#else
#include "types.h"
#include "user.h"
#endif
#include "mtrace.h"
#include "fstest.h"

#ifndef XV6_USER
#include <stdlib.h>
#include <sched.h>

int
setaffinity(int cpu)
{
  cpu_set_t mask;
  CPU_ZERO(&mask);
  CPU_SET(cpu, &mask);
  return sched_setaffinity(0, sizeof(mask), &mask);
}
#endif

static bool verbose = false;
static bool check_commutativity = false;
static bool check_threads = true;

static std::atomic<int> waiters;
static std::atomic<int> ready;

static void*
callthread(void* arg)
{
  int (*callf)(void) = (int (*)(void)) arg;

  waiters++;
  while (ready.load() == 0)
    ;

  callf();

  waiters--;
  while (ready.load() == 1)
    ;

  return 0;
}

int
main(int ac, char** av)
{
  setaffinity(0);

  int max = 0;
  if (ac > 1)
    max = atoi(av[1]);

  for (int i = 0; (max == 0 || i < max) && fstests[i].setup; i++) {
    if (check_commutativity) {
      fstests[i].setup();
      int ra0 = fstests[i].call0();
      int ra1 = fstests[i].call1();
      fstests[i].cleanup();

      fstests[i].setup();
      int rb1 = fstests[i].call1();
      int rb0 = fstests[i].call0();
      fstests[i].cleanup();

      if (ra0 == rb0 && ra1 == rb1) {
        if (verbose)
          printf("test %d: commutes: %s->%d %s->%d\n",
                 i, fstests[i].call0name, ra0, fstests[i].call1name, ra1);
      } else {
        printf("test %d: diverges: %s->%d %s->%d vs %s->%d %s->%d\n",
               i, fstests[i].call0name, ra0, fstests[i].call1name, ra1,
                  fstests[i].call0name, rb0, fstests[i].call1name, rb1);
      }
    }

    if (!check_threads)
      continue;

    fstests[i].setup();

    waiters = 0;
    ready = 0;
    pthread_t tid0, tid1;
    setaffinity(0);
    pthread_create(&tid0, 0, callthread, (void*) fstests[i].call0);
    setaffinity(1);
    pthread_create(&tid1, 0, callthread, (void*) fstests[i].call1);
    setaffinity(0);

    while (waiters.load() != 2)
      ;

    char mtname[64];
    snprintf(mtname, sizeof(mtname), "fstest-%d", i);
#ifdef XV6_USER
    mtenable_type(mtrace_record_ascope, mtname);
#else
    mtenable_type(mtrace_record_kernelscope, mtname);
#endif

    ready = 1;

    while (waiters.load() != 0)
      ;

    mtdisable(mtname);

    ready = 2;

    pthread_join(tid0, 0);
    pthread_join(tid1, 0);

    fstests[i].cleanup();

    printf("test %d completed threads\n", i);
  }
}
<commit_msg>better fstest arg parsing<commit_after>#include <stdio.h>
#include "pthread.h"
#include <atomic>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef XV6_USER
#include "types.h"
#include "user.h"
#endif
#include "mtrace.h"
#include "fstest.h"

#ifndef XV6_USER
#include <stdlib.h>
#include <sched.h>

int
setaffinity(int cpu)
{
  cpu_set_t mask;
  CPU_ZERO(&mask);
  CPU_SET(cpu, &mask);
  return sched_setaffinity(0, sizeof(mask), &mask);
}
#endif

static bool verbose = false;
static bool check_commutativity = false;
static bool run_threads = false;

static std::atomic<int> waiters;
static std::atomic<int> ready;

static void*
callthread(void* arg)
{
  int (*callf)(void) = (int (*)(void)) arg;

  waiters++;
  while (ready.load() == 0)
    ;

  callf();

  waiters--;
  while (ready.load() == 1)
    ;

  return 0;
}

static void
usage(const char* prog)
{
  fprintf(stderr, "Usage: %s [-v] [-c] [-t] [min[-max]]\n", prog);
}

int
main(int ac, char** av)
{
  setaffinity(0);

  uint32_t min = 0;
  uint32_t max = __UINT32_MAX__;

  for (;;) {
    int opt = getopt(ac, av, "vct");
    if (opt == -1)
      break;

    switch (opt) {
    case 'v':
      verbose = true;
      break;

    case 'c':
      check_commutativity = true;
      break;

    case 't':
      run_threads = true;
      break;

    default:
      usage(av[0]);
      return -1;
    }
  }

  if (optind < ac) {
    char* dash = strchr(av[optind], '-');
    if (!dash) {
      min = max = atoi(av[optind]);
    } else {
      *dash = '\0';
      min = atoi(av[optind]);
      max = atoi(dash + 1);
    }
  }

  if (!check_commutativity && !run_threads) {
    fprintf(stderr, "Must specify one of -c or -t\n");
    usage(av[0]);
    return -1;
  }

  printf("fstest:");
  if (verbose)
    printf(" verbose");
  if (check_commutativity)
    printf(" check");
  if (run_threads)
    printf(" threads");
  if (min == 0 && max == __UINT32_MAX__)
    printf(" all");
  else if (min == max)
    printf(" %d", min);
  else
    printf(" %d-%d", min, max);
  printf("\n");

  for (uint32_t i = min; i <= max && fstests[i].setup; i++) {
    if (check_commutativity) {
      fstests[i].setup();
      int ra0 = fstests[i].call0();
      int ra1 = fstests[i].call1();
      fstests[i].cleanup();

      fstests[i].setup();
      int rb1 = fstests[i].call1();
      int rb0 = fstests[i].call0();
      fstests[i].cleanup();

      if (ra0 == rb0 && ra1 == rb1) {
        if (verbose)
          printf("test %d: commutes: %s->%d %s->%d\n",
                 i, fstests[i].call0name, ra0, fstests[i].call1name, ra1);
      } else {
        printf("test %d: diverges: %s->%d %s->%d vs %s->%d %s->%d\n",
               i, fstests[i].call0name, ra0, fstests[i].call1name, ra1,
                  fstests[i].call0name, rb0, fstests[i].call1name, rb1);
      }
    }

    if (!run_threads)
      continue;

    fstests[i].setup();

    waiters = 0;
    ready = 0;
    pthread_t tid0, tid1;
    setaffinity(0);
    pthread_create(&tid0, 0, callthread, (void*) fstests[i].call0);
    setaffinity(1);
    pthread_create(&tid1, 0, callthread, (void*) fstests[i].call1);
    setaffinity(0);

    while (waiters.load() != 2)
      ;

    char mtname[64];
    snprintf(mtname, sizeof(mtname), "fstest-%d", i);
#ifdef XV6_USER
    mtenable_type(mtrace_record_ascope, mtname);
#else
    mtenable_type(mtrace_record_kernelscope, mtname);
#endif

    ready = 1;

    while (waiters.load() != 0)
      ;

    mtdisable(mtname);

    ready = 2;

    pthread_join(tid0, 0);
    pthread_join(tid1, 0);

    fstests[i].cleanup();

    printf("test %d completed threads\n", i);
  }
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "OGLSurface.h"

#include "../base/MathHelper.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/ObjectCounter.h"

#include "../graphics/GLContext.h"
#include "../graphics/GLTexture.h"

#include <iostream>
#include <sstream>

#include "../glm/gtc/matrix_transform.hpp"

using namespace std;

static glm::mat4 yuvCoeff(
        1.0f,   1.0f,    1.0f,  0.0f,
        0.0f, -0.34f,   1.77f,  0.0f,
       1.40f, -0.71f,    0.0f,  0.0f,
        0.0f,   0.0f,    0.0f,  1.0f);

namespace avg {

OGLSurface::OGLSurface()
    : m_Size(-1,-1),
      m_Gamma(1,1,1),
      m_Brightness(1,1,1),
      m_Contrast(1,1,1),
      m_AlphaGamma(1),
      m_bIsDirty(true)
{
    ObjectCounter::get()->incRef(&typeid(*this));
}

OGLSurface::~OGLSurface()
{
    ObjectCounter::get()->decRef(&typeid(*this));
}

void OGLSurface::create(PixelFormat pf, GLTexturePtr pTex0, GLTexturePtr pTex1,
        GLTexturePtr pTex2, GLTexturePtr pTex3)
{
    m_pf = pf;
    m_Size = pTex0->getSize();
    m_pTextures[0] = pTex0;
    m_pTextures[1] = pTex1;
    m_pTextures[2] = pTex2;
    m_pTextures[3] = pTex3;
    m_bIsDirty = true;

    // Make sure pixel format and number of textures line up.
    if (pixelFormatIsPlanar(pf)) {
        AVG_ASSERT(m_pTextures[2]);
        if (pixelFormatHasAlpha(m_pf)) {
            AVG_ASSERT(m_pTextures[3]);
        } else {
            AVG_ASSERT(!m_pTextures[3]);
        }
    } else {
        AVG_ASSERT(!m_pTextures[1]);
    }
}

void OGLSurface::setMask(GLTexturePtr pTex)
{
    m_pMaskTexture = pTex;
    m_bIsDirty = true;
}

void OGLSurface::destroy()
{
    m_pTextures[0] = GLTexturePtr();
    m_pTextures[1] = GLTexturePtr();
    m_pTextures[2] = GLTexturePtr();
    m_pTextures[3] = GLTexturePtr();
}

void OGLSurface::activate(const IntPoint& logicalSize, bool bPremultipliedAlpha) const
{
    StandardShaderPtr pShader = StandardShader::get();

    GLContext::checkError("OGLSurface::activate()");
    switch (m_pf) {
        case YCbCr420p:
        case YCbCrJ420p:
            pShader->setColorModel(1);
            break;
        case YCbCrA420p:
            pShader->setColorModel(3);
            break;
        case A8:
            pShader->setColorModel(2);
            break;
        default:
            pShader->setColorModel(0);
    }

    m_pTextures[0]->activate(GL_TEXTURE0);

    if (pixelFormatIsPlanar(m_pf)) {
        m_pTextures[1]->activate(GL_TEXTURE1);
        m_pTextures[2]->activate(GL_TEXTURE2);
        if (m_pf == YCbCrA420p) {
            m_pTextures[3]->activate(GL_TEXTURE3);
        }
    }
    if (pixelFormatIsPlanar(m_pf) || colorIsModified()) {
        glm::mat4 mat = calcColorspaceMatrix();
        pShader->setColorspaceMatrix(mat);
    } else {
        pShader->disableColorspaceMatrix();
    }
    pShader->setGamma(glm::vec4(1/m_Gamma.x, 1/m_Gamma.y, 1/m_Gamma.z,
                1./m_AlphaGamma));

    pShader->setPremultipliedAlpha(bPremultipliedAlpha);
    if (m_pMaskTexture) {
        m_pMaskTexture->activate(GL_TEXTURE4);
        // maskScale is (1,1) for everything excepting words nodes.
        glm::vec2 maskScale(1,1);
        if (logicalSize != IntPoint(0,0)) {
            maskScale = glm::vec2((float)logicalSize.x/m_Size.x,
                    (float)logicalSize.y/m_Size.y);
        }
        pShader->setMask(true, m_MaskPos, m_MaskSize*maskScale);
    } else {
        pShader->setMask(false);
    }
    pShader->activate();
    GLContext::checkError("OGLSurface::activate");
}

GLTexturePtr OGLSurface::getTex(int i) const
{
    return m_pTextures[i];
}

void OGLSurface::setMaskCoords(glm::vec2 maskPos, glm::vec2 maskSize)
{
    m_MaskPos = maskPos;
    m_MaskSize = maskSize;
    m_bIsDirty = true;
}

PixelFormat OGLSurface::getPixelFormat()
{
    return m_pf;
}

IntPoint OGLSurface::getSize()
{
    return m_Size;
}

IntPoint OGLSurface::getTextureSize()
{
    return m_pTextures[0]->getGLSize();
}

bool OGLSurface::isCreated() const
{
    return m_pTextures[0];
}

void OGLSurface::setColorParams(const glm::vec3& gamma, const glm::vec3& brightness,
            const glm::vec3& contrast)
{
    m_Gamma = gamma;
    m_Brightness = brightness;
    m_Contrast = contrast;
    m_bIsDirty = true;
}

void OGLSurface::setAlphaGamma(float gamma)
{
    m_AlphaGamma = gamma;
    m_bIsDirty = true;
}

bool OGLSurface::isDirty() const
{
    bool bIsDirty = m_bIsDirty;
    for (unsigned i=0; i<getNumPixelFormatPlanes(m_pf); ++i) {
        if (m_pTextures[i]->isDirty()) {
            bIsDirty = true;
        }
    }
    return bIsDirty;
}

void OGLSurface::resetDirty()
{
    m_bIsDirty = false;
    for (unsigned i=0; i<getNumPixelFormatPlanes(m_pf); ++i) {
        m_pTextures[i]->resetDirty();
    }
}

glm::mat4 OGLSurface::calcColorspaceMatrix() const
{
    glm::mat4 mat;
    if (colorIsModified()) {
        mat = glm::scale(mat, m_Brightness);
        glm::vec3 contrast = glm::vec3(0.5f, 0.5f, 0.5f) - m_Contrast/2.f;
        mat = glm::translate(mat, contrast);
        mat = glm::scale(mat, m_Contrast);
    }
    if (m_pf == YCbCr420p || m_pf == YCbCrJ420p || m_pf == YCbCrA420p) {
        mat *= yuvCoeff;
        mat = glm::translate(mat, glm::vec3(0.0, -0.5, -0.5));
        if (m_pf == YCbCr420p || m_pf == YCbCrA420p) {
            mat = glm::scale(mat,
                    glm::vec3(255.0f/(235-16), 255.0f/(235-16), 255.0f/(235-16)));
            mat = glm::translate(mat, glm::vec3(-16.0f/255, -16.0f/255, -16.0f/255));
        }
    }
    return mat;
}

bool OGLSurface::colorIsModified() const
{
    return (fabs(m_Brightness.x-1.0) > 0.00001 || fabs(m_Brightness.y-1.0) > 0.00001 ||
           fabs(m_Brightness.z-1.0) > 0.00001 || fabs(m_Contrast.x-1.0) > 0.00001 ||
           fabs(m_Contrast.y-1.0) > 0.00001 || fabs(m_Contrast.z-1.0) > 0.00001);
}

}
<commit_msg>Fixed masks for pot textures.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "OGLSurface.h"

#include "../base/MathHelper.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/ObjectCounter.h"

#include "../graphics/GLContext.h"
#include "../graphics/GLTexture.h"

#include <iostream>
#include <sstream>

#include "../glm/gtc/matrix_transform.hpp"

using namespace std;

static glm::mat4 yuvCoeff(
        1.0f,   1.0f,    1.0f,  0.0f,
        0.0f, -0.34f,   1.77f,  0.0f,
       1.40f, -0.71f,    0.0f,  0.0f,
        0.0f,   0.0f,    0.0f,  1.0f);

namespace avg {

OGLSurface::OGLSurface()
    : m_Size(-1,-1),
      m_Gamma(1,1,1),
      m_Brightness(1,1,1),
      m_Contrast(1,1,1),
      m_AlphaGamma(1),
      m_bIsDirty(true)
{
    ObjectCounter::get()->incRef(&typeid(*this));
}

OGLSurface::~OGLSurface()
{
    ObjectCounter::get()->decRef(&typeid(*this));
}

void OGLSurface::create(PixelFormat pf, GLTexturePtr pTex0, GLTexturePtr pTex1,
        GLTexturePtr pTex2, GLTexturePtr pTex3)
{
    m_pf = pf;
    m_Size = pTex0->getSize();
    m_pTextures[0] = pTex0;
    m_pTextures[1] = pTex1;
    m_pTextures[2] = pTex2;
    m_pTextures[3] = pTex3;
    m_bIsDirty = true;

    // Make sure pixel format and number of textures line up.
    if (pixelFormatIsPlanar(pf)) {
        AVG_ASSERT(m_pTextures[2]);
        if (pixelFormatHasAlpha(m_pf)) {
            AVG_ASSERT(m_pTextures[3]);
        } else {
            AVG_ASSERT(!m_pTextures[3]);
        }
    } else {
        AVG_ASSERT(!m_pTextures[1]);
    }
}

void OGLSurface::setMask(GLTexturePtr pTex)
{
    m_pMaskTexture = pTex;
    m_bIsDirty = true;
}

void OGLSurface::destroy()
{
    m_pTextures[0] = GLTexturePtr();
    m_pTextures[1] = GLTexturePtr();
    m_pTextures[2] = GLTexturePtr();
    m_pTextures[3] = GLTexturePtr();
}

void OGLSurface::activate(const IntPoint& logicalSize, bool bPremultipliedAlpha) const
{
    StandardShaderPtr pShader = StandardShader::get();

    GLContext::checkError("OGLSurface::activate()");
    switch (m_pf) {
        case YCbCr420p:
        case YCbCrJ420p:
            pShader->setColorModel(1);
            break;
        case YCbCrA420p:
            pShader->setColorModel(3);
            break;
        case A8:
            pShader->setColorModel(2);
            break;
        default:
            pShader->setColorModel(0);
    }

    m_pTextures[0]->activate(GL_TEXTURE0);

    if (pixelFormatIsPlanar(m_pf)) {
        m_pTextures[1]->activate(GL_TEXTURE1);
        m_pTextures[2]->activate(GL_TEXTURE2);
        if (m_pf == YCbCrA420p) {
            m_pTextures[3]->activate(GL_TEXTURE3);
        }
    }
    if (pixelFormatIsPlanar(m_pf) || colorIsModified()) {
        glm::mat4 mat = calcColorspaceMatrix();
        pShader->setColorspaceMatrix(mat);
    } else {
        pShader->disableColorspaceMatrix();
    }
    pShader->setGamma(glm::vec4(1/m_Gamma.x, 1/m_Gamma.y, 1/m_Gamma.z,
                1./m_AlphaGamma));

    pShader->setPremultipliedAlpha(bPremultipliedAlpha);
    if (m_pMaskTexture) {
        m_pMaskTexture->activate(GL_TEXTURE4);
        // Special case for pot textures:
        //   The tex coords in the vertex array are scaled to fit the image texture. We
        //   need to undo this and fit to the mask texture. In the npot case, everything
        //   evaluates to (1,1);
        glm::vec2 texSize = glm::vec2(m_pTextures[0]->getGLSize());
        glm::vec2 imgSize = glm::vec2(m_pTextures[0]->getSize());
        glm::vec2 maskTexSize = glm::vec2(m_pMaskTexture->getGLSize());
        glm::vec2 maskImgSize = glm::vec2(m_pMaskTexture->getSize());
        glm::vec2 maskScale = glm::vec2(maskTexSize.x/maskImgSize.x,
                maskTexSize.y/maskImgSize.y);
        glm::vec2 imgScale = glm::vec2(texSize.x/imgSize.x, texSize.y/imgSize.y);

        // Special case for words nodes.
        if (logicalSize != IntPoint(0,0)) {
            maskScale *= glm::vec2((float)logicalSize.x/m_Size.x,
                    (float)logicalSize.y/m_Size.y);
        }
        pShader->setMask(true, m_MaskPos/maskScale, m_MaskSize*maskScale/imgScale);
    } else {
        pShader->setMask(false);
    }
    pShader->activate();
    GLContext::checkError("OGLSurface::activate");
}

GLTexturePtr OGLSurface::getTex(int i) const
{
    return m_pTextures[i];
}

void OGLSurface::setMaskCoords(glm::vec2 maskPos, glm::vec2 maskSize)
{
    m_MaskPos = maskPos;
    m_MaskSize = maskSize;
    m_bIsDirty = true;
}

PixelFormat OGLSurface::getPixelFormat()
{
    return m_pf;
}

IntPoint OGLSurface::getSize()
{
    return m_Size;
}

IntPoint OGLSurface::getTextureSize()
{
    return m_pTextures[0]->getGLSize();
}

bool OGLSurface::isCreated() const
{
    return m_pTextures[0];
}

void OGLSurface::setColorParams(const glm::vec3& gamma, const glm::vec3& brightness,
            const glm::vec3& contrast)
{
    m_Gamma = gamma;
    m_Brightness = brightness;
    m_Contrast = contrast;
    m_bIsDirty = true;
}

void OGLSurface::setAlphaGamma(float gamma)
{
    m_AlphaGamma = gamma;
    m_bIsDirty = true;
}

bool OGLSurface::isDirty() const
{
    bool bIsDirty = m_bIsDirty;
    for (unsigned i=0; i<getNumPixelFormatPlanes(m_pf); ++i) {
        if (m_pTextures[i]->isDirty()) {
            bIsDirty = true;
        }
    }
    return bIsDirty;
}

void OGLSurface::resetDirty()
{
    m_bIsDirty = false;
    for (unsigned i=0; i<getNumPixelFormatPlanes(m_pf); ++i) {
        m_pTextures[i]->resetDirty();
    }
}

glm::mat4 OGLSurface::calcColorspaceMatrix() const
{
    glm::mat4 mat;
    if (colorIsModified()) {
        mat = glm::scale(mat, m_Brightness);
        glm::vec3 contrast = glm::vec3(0.5f, 0.5f, 0.5f) - m_Contrast/2.f;
        mat = glm::translate(mat, contrast);
        mat = glm::scale(mat, m_Contrast);
    }
    if (m_pf == YCbCr420p || m_pf == YCbCrJ420p || m_pf == YCbCrA420p) {
        mat *= yuvCoeff;
        mat = glm::translate(mat, glm::vec3(0.0, -0.5, -0.5));
        if (m_pf == YCbCr420p || m_pf == YCbCrA420p) {
            mat = glm::scale(mat,
                    glm::vec3(255.0f/(235-16), 255.0f/(235-16), 255.0f/(235-16)));
            mat = glm::translate(mat, glm::vec3(-16.0f/255, -16.0f/255, -16.0f/255));
        }
    }
    return mat;
}

bool OGLSurface::colorIsModified() const
{
    return (fabs(m_Brightness.x-1.0) > 0.00001 || fabs(m_Brightness.y-1.0) > 0.00001 ||
           fabs(m_Brightness.z-1.0) > 0.00001 || fabs(m_Contrast.x-1.0) > 0.00001 ||
           fabs(m_Contrast.y-1.0) > 0.00001 || fabs(m_Contrast.z-1.0) > 0.00001);
}

}
<|endoftext|>


<commit_before>#include "selectors.hh"

#include "string.hh"

#include <algorithm>

namespace Kakoune
{

namespace
{

bool is_eol(char c)
{
    return c == '\n';
}

bool is_blank(char c)
{
    return c == ' ' or c == '\t';
}

template<bool punctuation_is_word = false>
bool is_word(char c);

template<>
bool is_word<false>(char c)
{
    if (c >= '0' and c <= '9')
        return true;
    if (c >= 'a' and c <= 'z')
        return true;
    if (c >= 'A' and c <= 'Z')
        return true;
    if (c == '_')
        return true;
    return false;
}

template<>
bool is_word<true>(char c)
{
    return !is_blank(c) and !is_eol(c);
}

static bool is_punctuation(char c)
{
    return not (is_word(c) or is_blank(c) or is_eol(c));
}

enum class CharCategories
{
    Blank,
    EndOfLine,
    Word,
    Punctuation,
};

template<bool punctuation_is_word = false>
CharCategories categorize(char c)
{
    if (is_word(c))
        return CharCategories::Word;
    if (is_eol(c))
        return CharCategories::EndOfLine;
    if (is_blank(c))
        return CharCategories::Blank;
    return punctuation_is_word ? CharCategories::Word
                               : CharCategories::Punctuation;
}

template<typename T>
bool skip_while(BufferIterator& it, T condition)
{
    while (not it.is_end() and condition(*it))
        ++it;
    return not it.is_end() and condition(*it);
}

template<typename T>
bool skip_while_reverse(BufferIterator& it, T condition)
{
    while (not it.is_begin() and condition(*it))
        --it;
    return not it.is_end() and condition(*it);
}

}

typedef boost::regex_iterator<BufferIterator> RegexIterator;

template<bool punctuation_is_word>
SelectionAndCaptures select_to_next_word(const Selection& selection)
{
    BufferIterator begin = selection.last();
    if (categorize<punctuation_is_word>(*begin) !=
        categorize<punctuation_is_word>(*(begin+1)))
        ++begin;

    skip_while(begin, is_eol);
    BufferIterator end = begin+1;

    if (not punctuation_is_word and is_punctuation(*begin))
        skip_while(end, is_punctuation);
    else if (is_word<punctuation_is_word>(*begin))
        skip_while(end, is_word<punctuation_is_word>);

    bool with_end = skip_while(end, is_blank);

    return Selection(begin, with_end ? end : end-1);
}
template SelectionAndCaptures select_to_next_word<false>(const Selection&);
template SelectionAndCaptures select_to_next_word<true>(const Selection&);

template<bool punctuation_is_word>
SelectionAndCaptures select_to_next_word_end(const Selection& selection)
{
    BufferIterator begin = selection.last();
    if (categorize<punctuation_is_word>(*begin) !=
        categorize<punctuation_is_word>(*(begin+1)))
        ++begin;

    skip_while(begin, is_eol);
    BufferIterator end = begin;
    skip_while(end, is_blank);

    bool with_end = false;
    if (not punctuation_is_word and is_punctuation(*end))
        with_end = skip_while(end, is_punctuation);
    else if (is_word<punctuation_is_word>(*end))
        with_end = skip_while(end, is_word<punctuation_is_word>);

    return Selection(begin, with_end ? end : end-1);
}
template SelectionAndCaptures select_to_next_word_end<false>(const Selection&);
template SelectionAndCaptures select_to_next_word_end<true>(const Selection&);

template<bool punctuation_is_word>
SelectionAndCaptures select_to_previous_word(const Selection& selection)
{
    BufferIterator begin = selection.last();

    if (categorize<punctuation_is_word>(*begin) !=
        categorize<punctuation_is_word>(*(begin-1)))
        --begin;

    skip_while_reverse(begin, is_eol);
    BufferIterator end = begin;
    skip_while_reverse(end, is_blank);

    bool with_end = false;
    if (not punctuation_is_word and is_punctuation(*end))
        with_end = skip_while_reverse(end, is_punctuation);
    else if (is_word<punctuation_is_word>(*end))
        with_end = skip_while_reverse(end, is_word<punctuation_is_word>);

    return Selection(begin, with_end ? end : end+1);
}
template SelectionAndCaptures select_to_previous_word<false>(const Selection&);
template SelectionAndCaptures select_to_previous_word<true>(const Selection&);

SelectionAndCaptures select_line(const Selection& selection)
{
    BufferIterator first = selection.last();
    if (*first == '\n' and not (first + 1).is_end())
        ++first;

    while (not first.is_begin() and *(first - 1) != '\n')
        --first;

    BufferIterator last = first;
    while (not (last + 1).is_end() and *last != '\n')
        ++last;
    return Selection(first, last);
}

SelectionAndCaptures select_matching(const Selection& selection)
{
    std::vector<char> matching_pairs = { '(', ')', '{', '}', '[', ']', '<', '>' };
    BufferIterator it = selection.last();
    std::vector<char>::iterator match = matching_pairs.end();
    while (not is_eol(*it))
    {
        match = std::find(matching_pairs.begin(), matching_pairs.end(), *it);
        if (match != matching_pairs.end())
            break;
        ++it;
    }
    if (match == matching_pairs.end())
        return selection;

    BufferIterator begin = it;

    if (((match - matching_pairs.begin()) % 2) == 0)
    {
        int level = 0;
        const char opening = *match;
        const char closing = *(match+1);
        while (not it.is_end())
        {
            if (*it == opening)
                ++level;
            else if (*it == closing and --level == 0)
                return Selection(begin, it);

            ++it;
        }
    }
    else
    {
        int level = 0;
        const char opening = *(match-1);
        const char closing = *match;
        while (not it.is_begin())
        {
            if (*it == closing)
                ++level;
            else if (*it == opening and --level == 0)
                return Selection(begin, it);
            --it;
        }
    }
    return selection;
}

SelectionAndCaptures select_surrounding(const Selection& selection,
                             const std::pair<char, char>& matching,
                             bool inside)
{
    int level = 0;
    BufferIterator first = selection.last();
    while (not first.is_begin())
    {
        if (first != selection.last() and *first == matching.second)
            ++level;
        else if (*first == matching.first)
        {
            if (level == 0)
                break;
            else
                --level;
        }
        --first;
    }
    if (level != 0 or *first != matching.first)
        return selection;

    level = 0;
    BufferIterator last = first + 1;
    while (not last.is_end())
    {
        if (*last == matching.first)
            ++level;
        else if (*last == matching.second)
        {
            if (level == 0)
                break;
            else
                --level;
        }
        ++last;
    }
    if (level != 0 or *last != matching.second)
        return selection;

    if (inside)
    {
        ++first;
        if (first != last)
            --last;
    }
    return Selection(first, last);
}

SelectionAndCaptures select_to(const Selection& selection,
                               char c, int count, bool inclusive)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin;
    do
    {
        ++end;
        skip_while(end, [c](char cur) { return not is_eol(cur) and cur != c; });
        if (end.is_end() or is_eol(*end))
            return selection;
    }
    while (--count > 0);

    return Selection(begin, inclusive ? end : end-1);
}

SelectionAndCaptures select_to_reverse(const Selection& selection,
                                       char c, int count, bool inclusive)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin;
    do
    {
        --end;
        skip_while_reverse(end, [c](char cur) { return not is_eol(cur) and cur != c; });
        if (end.is_begin() or is_eol(*end))
            return selection;
    }
    while (--count > 0);

    return Selection(begin, inclusive ? end : end+1);
}

SelectionAndCaptures select_to_eol(const Selection& selection)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin + 1;
    skip_while(end, [](char cur) { return not is_eol(cur); });
    return Selection(begin, end-1);
}

SelectionAndCaptures select_to_eol_reverse(const Selection& selection)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin - 1;
    skip_while_reverse(end, [](char cur) { return not is_eol(cur); });
    return Selection(begin, end.is_begin() ? end : end+1);
}

template<bool punctuation_is_word>
SelectionAndCaptures select_whole_word(const Selection& selection, bool inner)
{
    BufferIterator first = selection.last();
    BufferIterator last = first;
    if (is_word(*first))
    {
        if (not skip_while_reverse(first, is_word<punctuation_is_word>))
            ++first;
        skip_while(last, is_word<punctuation_is_word>);
        if (not inner)
            skip_while(last, is_blank);
    }
    else if (not inner)
    {
        if (not skip_while_reverse(first, is_blank))
            ++first;
        skip_while(last, is_blank);
        if (not is_word<punctuation_is_word>(*last))
            return selection;
        skip_while(last, is_word<punctuation_is_word>);
    }
    --last;
    return Selection(first, last);
}
template SelectionAndCaptures select_whole_word<false>(const Selection&, bool);
template SelectionAndCaptures select_whole_word<true>(const Selection&, bool);

SelectionAndCaptures select_whole_lines(const Selection& selection)
{
     BufferIterator first = selection.first();
     BufferIterator last =  selection.last();
     BufferIterator& to_line_start = first <= last ? first : last;
     BufferIterator& to_line_end = first <= last ? last : first;

     --to_line_start;
     skip_while_reverse(to_line_start, [](char cur) { return not is_eol(cur); });
     ++to_line_start;

     skip_while(to_line_end, [](char cur) { return not is_eol(cur); });

     return Selection(first, last);
}

SelectionAndCaptures select_whole_buffer(const Selection& selection)
{
    const Buffer& buffer = selection.first().buffer();
    return Selection(buffer.begin(), buffer.end()-1);
}

SelectionAndCaptures select_next_match(const Selection& selection,
                                       const String& regex)
{
    try
    {
        BufferIterator begin = selection.last();
        BufferIterator end = begin;
        CaptureList captures;

        Regex ex(regex.begin(), regex.end());
        boost::match_results<BufferIterator> matches;

        if (boost::regex_search(begin+1, begin.buffer().end(),
                                matches, ex))
        {
            begin = matches[0].first;
            end   = matches[0].second;
            for (auto& match : matches)
                captures.push_back(String(match.first, match.second));
        }
        else if (boost::regex_search(begin.buffer().begin(), begin+1,
                                     matches, ex))
        {
            begin = matches[0].first;
            end   = matches[0].second;
            for (auto& match : matches)
                captures.push_back(String(match.first, match.second));
        }
        if (begin == end)
            ++end;

        return SelectionAndCaptures(begin, end - 1, std::move(captures));
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error(String("regex error: ") + err.what());
    }
}

SelectionAndCapturesList select_all_matches(const Selection& selection,
                                            const String& regex)
{
    try
    {
        Regex ex(regex.begin(), regex.end());
        RegexIterator re_it(selection.begin(), selection.end(), ex);
        RegexIterator re_end;

        SelectionAndCapturesList result;
        for (; re_it != re_end; ++re_it)
        {
            BufferIterator begin = (*re_it)[0].first;
            BufferIterator end   = (*re_it)[0].second;

            CaptureList captures;
            for (auto& match : *re_it)
                captures.push_back(String(match.first, match.second));

            result.push_back(SelectionAndCaptures(begin,
                                                  begin == end ? end : end-1,
                                                  std::move(captures)));
        }
        return result;
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error(String("regex error: ") + err.what());
    }
}

SelectionAndCapturesList split_selection(const Selection& selection,
                                         const String& separator_regex)
{
    try
    {
        Regex ex(separator_regex.begin(), separator_regex.end());
        RegexIterator re_it(selection.begin(), selection.end(), ex,
                            boost::regex_constants::match_nosubs);
        RegexIterator re_end;

        SelectionAndCapturesList result;
        BufferIterator begin = selection.begin();
        for (; re_it != re_end; ++re_it)
        {
            BufferIterator end = (*re_it)[0].first;

            result.push_back(Selection(begin, (begin == end) ? end : end-1));
            begin = (*re_it)[0].second;
        }
        result.push_back(Selection(begin, selection.last()));
        return result;
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error(String("regex error: ") + err.what());
    }
}

}
<commit_msg>whine when a search selected nothing so that the user knows<commit_after>#include "selectors.hh"

#include "string.hh"

#include <algorithm>

namespace Kakoune
{

namespace
{

bool is_eol(char c)
{
    return c == '\n';
}

bool is_blank(char c)
{
    return c == ' ' or c == '\t';
}

template<bool punctuation_is_word = false>
bool is_word(char c);

template<>
bool is_word<false>(char c)
{
    if (c >= '0' and c <= '9')
        return true;
    if (c >= 'a' and c <= 'z')
        return true;
    if (c >= 'A' and c <= 'Z')
        return true;
    if (c == '_')
        return true;
    return false;
}

template<>
bool is_word<true>(char c)
{
    return !is_blank(c) and !is_eol(c);
}

static bool is_punctuation(char c)
{
    return not (is_word(c) or is_blank(c) or is_eol(c));
}

enum class CharCategories
{
    Blank,
    EndOfLine,
    Word,
    Punctuation,
};

template<bool punctuation_is_word = false>
CharCategories categorize(char c)
{
    if (is_word(c))
        return CharCategories::Word;
    if (is_eol(c))
        return CharCategories::EndOfLine;
    if (is_blank(c))
        return CharCategories::Blank;
    return punctuation_is_word ? CharCategories::Word
                               : CharCategories::Punctuation;
}

template<typename T>
bool skip_while(BufferIterator& it, T condition)
{
    while (not it.is_end() and condition(*it))
        ++it;
    return not it.is_end() and condition(*it);
}

template<typename T>
bool skip_while_reverse(BufferIterator& it, T condition)
{
    while (not it.is_begin() and condition(*it))
        --it;
    return not it.is_end() and condition(*it);
}

}

typedef boost::regex_iterator<BufferIterator> RegexIterator;

template<bool punctuation_is_word>
SelectionAndCaptures select_to_next_word(const Selection& selection)
{
    BufferIterator begin = selection.last();
    if (categorize<punctuation_is_word>(*begin) !=
        categorize<punctuation_is_word>(*(begin+1)))
        ++begin;

    skip_while(begin, is_eol);
    BufferIterator end = begin+1;

    if (not punctuation_is_word and is_punctuation(*begin))
        skip_while(end, is_punctuation);
    else if (is_word<punctuation_is_word>(*begin))
        skip_while(end, is_word<punctuation_is_word>);

    bool with_end = skip_while(end, is_blank);

    return Selection(begin, with_end ? end : end-1);
}
template SelectionAndCaptures select_to_next_word<false>(const Selection&);
template SelectionAndCaptures select_to_next_word<true>(const Selection&);

template<bool punctuation_is_word>
SelectionAndCaptures select_to_next_word_end(const Selection& selection)
{
    BufferIterator begin = selection.last();
    if (categorize<punctuation_is_word>(*begin) !=
        categorize<punctuation_is_word>(*(begin+1)))
        ++begin;

    skip_while(begin, is_eol);
    BufferIterator end = begin;
    skip_while(end, is_blank);

    bool with_end = false;
    if (not punctuation_is_word and is_punctuation(*end))
        with_end = skip_while(end, is_punctuation);
    else if (is_word<punctuation_is_word>(*end))
        with_end = skip_while(end, is_word<punctuation_is_word>);

    return Selection(begin, with_end ? end : end-1);
}
template SelectionAndCaptures select_to_next_word_end<false>(const Selection&);
template SelectionAndCaptures select_to_next_word_end<true>(const Selection&);

template<bool punctuation_is_word>
SelectionAndCaptures select_to_previous_word(const Selection& selection)
{
    BufferIterator begin = selection.last();

    if (categorize<punctuation_is_word>(*begin) !=
        categorize<punctuation_is_word>(*(begin-1)))
        --begin;

    skip_while_reverse(begin, is_eol);
    BufferIterator end = begin;
    skip_while_reverse(end, is_blank);

    bool with_end = false;
    if (not punctuation_is_word and is_punctuation(*end))
        with_end = skip_while_reverse(end, is_punctuation);
    else if (is_word<punctuation_is_word>(*end))
        with_end = skip_while_reverse(end, is_word<punctuation_is_word>);

    return Selection(begin, with_end ? end : end+1);
}
template SelectionAndCaptures select_to_previous_word<false>(const Selection&);
template SelectionAndCaptures select_to_previous_word<true>(const Selection&);

SelectionAndCaptures select_line(const Selection& selection)
{
    BufferIterator first = selection.last();
    if (*first == '\n' and not (first + 1).is_end())
        ++first;

    while (not first.is_begin() and *(first - 1) != '\n')
        --first;

    BufferIterator last = first;
    while (not (last + 1).is_end() and *last != '\n')
        ++last;
    return Selection(first, last);
}

SelectionAndCaptures select_matching(const Selection& selection)
{
    std::vector<char> matching_pairs = { '(', ')', '{', '}', '[', ']', '<', '>' };
    BufferIterator it = selection.last();
    std::vector<char>::iterator match = matching_pairs.end();
    while (not is_eol(*it))
    {
        match = std::find(matching_pairs.begin(), matching_pairs.end(), *it);
        if (match != matching_pairs.end())
            break;
        ++it;
    }
    if (match == matching_pairs.end())
        return selection;

    BufferIterator begin = it;

    if (((match - matching_pairs.begin()) % 2) == 0)
    {
        int level = 0;
        const char opening = *match;
        const char closing = *(match+1);
        while (not it.is_end())
        {
            if (*it == opening)
                ++level;
            else if (*it == closing and --level == 0)
                return Selection(begin, it);

            ++it;
        }
    }
    else
    {
        int level = 0;
        const char opening = *(match-1);
        const char closing = *match;
        while (not it.is_begin())
        {
            if (*it == closing)
                ++level;
            else if (*it == opening and --level == 0)
                return Selection(begin, it);
            --it;
        }
    }
    return selection;
}

SelectionAndCaptures select_surrounding(const Selection& selection,
                             const std::pair<char, char>& matching,
                             bool inside)
{
    int level = 0;
    BufferIterator first = selection.last();
    while (not first.is_begin())
    {
        if (first != selection.last() and *first == matching.second)
            ++level;
        else if (*first == matching.first)
        {
            if (level == 0)
                break;
            else
                --level;
        }
        --first;
    }
    if (level != 0 or *first != matching.first)
        return selection;

    level = 0;
    BufferIterator last = first + 1;
    while (not last.is_end())
    {
        if (*last == matching.first)
            ++level;
        else if (*last == matching.second)
        {
            if (level == 0)
                break;
            else
                --level;
        }
        ++last;
    }
    if (level != 0 or *last != matching.second)
        return selection;

    if (inside)
    {
        ++first;
        if (first != last)
            --last;
    }
    return Selection(first, last);
}

SelectionAndCaptures select_to(const Selection& selection,
                               char c, int count, bool inclusive)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin;
    do
    {
        ++end;
        skip_while(end, [c](char cur) { return not is_eol(cur) and cur != c; });
        if (end.is_end() or is_eol(*end))
            return selection;
    }
    while (--count > 0);

    return Selection(begin, inclusive ? end : end-1);
}

SelectionAndCaptures select_to_reverse(const Selection& selection,
                                       char c, int count, bool inclusive)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin;
    do
    {
        --end;
        skip_while_reverse(end, [c](char cur) { return not is_eol(cur) and cur != c; });
        if (end.is_begin() or is_eol(*end))
            return selection;
    }
    while (--count > 0);

    return Selection(begin, inclusive ? end : end+1);
}

SelectionAndCaptures select_to_eol(const Selection& selection)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin + 1;
    skip_while(end, [](char cur) { return not is_eol(cur); });
    return Selection(begin, end-1);
}

SelectionAndCaptures select_to_eol_reverse(const Selection& selection)
{
    BufferIterator begin = selection.last();
    BufferIterator end = begin - 1;
    skip_while_reverse(end, [](char cur) { return not is_eol(cur); });
    return Selection(begin, end.is_begin() ? end : end+1);
}

template<bool punctuation_is_word>
SelectionAndCaptures select_whole_word(const Selection& selection, bool inner)
{
    BufferIterator first = selection.last();
    BufferIterator last = first;
    if (is_word(*first))
    {
        if (not skip_while_reverse(first, is_word<punctuation_is_word>))
            ++first;
        skip_while(last, is_word<punctuation_is_word>);
        if (not inner)
            skip_while(last, is_blank);
    }
    else if (not inner)
    {
        if (not skip_while_reverse(first, is_blank))
            ++first;
        skip_while(last, is_blank);
        if (not is_word<punctuation_is_word>(*last))
            return selection;
        skip_while(last, is_word<punctuation_is_word>);
    }
    --last;
    return Selection(first, last);
}
template SelectionAndCaptures select_whole_word<false>(const Selection&, bool);
template SelectionAndCaptures select_whole_word<true>(const Selection&, bool);

SelectionAndCaptures select_whole_lines(const Selection& selection)
{
     BufferIterator first = selection.first();
     BufferIterator last =  selection.last();
     BufferIterator& to_line_start = first <= last ? first : last;
     BufferIterator& to_line_end = first <= last ? last : first;

     --to_line_start;
     skip_while_reverse(to_line_start, [](char cur) { return not is_eol(cur); });
     ++to_line_start;

     skip_while(to_line_end, [](char cur) { return not is_eol(cur); });

     return Selection(first, last);
}

SelectionAndCaptures select_whole_buffer(const Selection& selection)
{
    const Buffer& buffer = selection.first().buffer();
    return Selection(buffer.begin(), buffer.end()-1);
}

SelectionAndCaptures select_next_match(const Selection& selection,
                                       const String& regex)
{
    try
    {
        BufferIterator begin = selection.last();
        BufferIterator end = begin;
        CaptureList captures;

        Regex ex(regex.begin(), regex.end());
        boost::match_results<BufferIterator> matches;

        if (boost::regex_search(begin+1, begin.buffer().end(),
                                matches, ex))
        {
            begin = matches[0].first;
            end   = matches[0].second;
            for (auto& match : matches)
                captures.push_back(String(match.first, match.second));
        }
        else if (boost::regex_search(begin.buffer().begin(), begin+1,
                                     matches, ex))
        {
            begin = matches[0].first;
            end   = matches[0].second;
            for (auto& match : matches)
                captures.push_back(String(match.first, match.second));
        }
        else
            throw runtime_error("'" + regex + "': no matches found");

        if (begin == end)
            ++end;

        return SelectionAndCaptures(begin, end - 1, std::move(captures));
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error(String("regex error: ") + err.what());
    }
}

SelectionAndCapturesList select_all_matches(const Selection& selection,
                                            const String& regex)
{
    try
    {
        Regex ex(regex.begin(), regex.end());
        RegexIterator re_it(selection.begin(), selection.end(), ex);
        RegexIterator re_end;

        SelectionAndCapturesList result;
        for (; re_it != re_end; ++re_it)
        {
            BufferIterator begin = (*re_it)[0].first;
            BufferIterator end   = (*re_it)[0].second;

            CaptureList captures;
            for (auto& match : *re_it)
                captures.push_back(String(match.first, match.second));

            result.push_back(SelectionAndCaptures(begin,
                                                  begin == end ? end : end-1,
                                                  std::move(captures)));
        }
        return result;
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error(String("regex error: ") + err.what());
    }
}

SelectionAndCapturesList split_selection(const Selection& selection,
                                         const String& separator_regex)
{
    try
    {
        Regex ex(separator_regex.begin(), separator_regex.end());
        RegexIterator re_it(selection.begin(), selection.end(), ex,
                            boost::regex_constants::match_nosubs);
        RegexIterator re_end;

        SelectionAndCapturesList result;
        BufferIterator begin = selection.begin();
        for (; re_it != re_end; ++re_it)
        {
            BufferIterator end = (*re_it)[0].first;

            result.push_back(Selection(begin, (begin == end) ? end : end-1));
            begin = (*re_it)[0].second;
        }
        result.push_back(Selection(begin, selection.last()));
        return result;
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error(String("regex error: ") + err.what());
    }
}

}
<|endoftext|>


<commit_before>#include "paddle.h"

paddle::paddle(sf::Vector2i windowResolution, string positionDeterminant, char paddleSize)
{
    //setting paddle size
    size.x=windowResolution.x/64;
    if(paddleSize == 'B' || paddleSize == 'b')
        size.y=windowResolution.y/4;
    else
        size.y=windowResolution.y/8;
    shape.setSize(size);

    //setting paddle position
    if(positionDeterminant=="left")
        shape.setPosition(size.x, windowResolution.y/2-shape.getGlobalBounds().height/2);
    else if(positionDeterminant=="right")
        shape.setPosition(windowResolution.x-size.x*2, windowResolution.y/2-shape.getGlobalBounds().height/2);
}

void paddle::moveUp(sf::Time time, double speed)
{
    //cout << "Function moveUp was called" << endl;
    if(shape.getPosition().y>8)
        //sth is wrong over here
        shape.move(sf::Vector2f(0,-4*speed*time.asMilliseconds()/4));
    //cout << time.asMilliseconds() << endl;
}

void paddle::moveDown(sf::Time time, sf::Vector2i windowResolution, double speed)
{
    if(shape.getPosition().y+size.y<windowResolution.y-8)
        shape.move(sf::Vector2f(0,4*speed*time.asMilliseconds()/4));
}
<commit_msg>Delete paddle.cpp<commit_after><|endoftext|>


<commit_before>#include "qtcamdevice.h"
#include "qtcamviewfinder.h"
#include "qtcamconfig.h"
#include "qtcamdevice_p.h"
#include <QDebug>
#include <gst/gst.h>
#include "qtcamgstreamermessagelistener.h"
#include "qtcammode.h"
#include "qtcamimagemode.h"
#include "qtcamvideomode.h"

QtCamDevice::QtCamDevice(QtCamConfig *config, const QString& name,
			 const QVariant& id, QObject *parent) :
  QObject(parent), d_ptr(new QtCamDevicePrivate) {

  d_ptr->q_ptr = this;
  d_ptr->name = name;
  d_ptr->id = id;
  d_ptr->conf = config;

  d_ptr->cameraBin = gst_element_factory_make("camerabin2", "QtCameraCameraBin");
  if (!d_ptr->cameraBin) {
    qCritical() << "Failed to create camerabin";
    return;
  }

  d_ptr->createAndAddElement(d_ptr->conf->audioSource(), "audio-source", "QtCameraAudioSrc");
  d_ptr->createAndAddVideoSource();

  int flags =
    0x00000001 /* no-audio-conversion - Do not use audio conversion elements */
    | 0x00000002 /* no-video-conversion - Do not use video conversion elements */
    | 0x00000004 /* no-viewfinder-conversion - Do not use viewfinder conversion elements */
    | 0x00000008; /* no-image-conversion - Do not use image conversion elements */

  g_object_set(d_ptr->cameraBin, "flags", flags, NULL);

  d_ptr->setAudioCaptureCaps();

  // TODO: audio bitrate
  // TODO: video bitrate
  // TODO: filters
  // TODO: capabilities
  // TODO: custom properties for jifmux, mp4mux, audio encoder, video encoder, sink & video source
  // color tune, scene modes
  d_ptr->listener = new QtCamGStreamerMessageListener(gst_element_get_bus(d_ptr->cameraBin),
						      d_ptr, this);

  QObject::connect(d_ptr->listener, SIGNAL(error(const QString&, int, const QString&)),
		   this, SLOT(_d_error(const QString&, int, const QString&)));
  QObject::connect(d_ptr->listener, SIGNAL(started()), this, SLOT(_d_started()));
  QObject::connect(d_ptr->listener, SIGNAL(stopped()), this, SLOT(_d_stopped()));
  QObject::connect(d_ptr->listener, SIGNAL(stopping()), this, SLOT(_d_stopping()));

  g_signal_connect(d_ptr->cameraBin, "notify::idle",
		   G_CALLBACK(QtCamDevicePrivate::on_idle_changed), d_ptr);

  g_signal_connect(d_ptr->wrapperVideoSource, "notify::ready-for-capture",
		   G_CALLBACK(QtCamDevicePrivate::on_ready_for_capture_changed), d_ptr);

  d_ptr->image = new QtCamImageMode(d_ptr, this);
  d_ptr->video = new QtCamVideoMode(d_ptr, this);
}

QtCamDevice::~QtCamDevice() {
  stop();

  d_ptr->image->deactivate();
  d_ptr->video->deactivate();

  delete d_ptr->image; d_ptr->image = 0;
  delete d_ptr->video; d_ptr->video = 0;
  delete d_ptr; d_ptr = 0;
}

bool QtCamDevice::setViewfinder(QtCamViewfinder *viewfinder) {
  if (isRunning()) {
    qWarning() << "QtCamDevice: pipeline must be stopped before setting a viewfinder";
    return false;
  }

  if (d_ptr->viewfinder == viewfinder) {
    return true;
  }

  if (!viewfinder) {
    qWarning() << "QtCamDevice: viewfinder cannot be unset.";
    return false;
  }

  if (d_ptr->viewfinder) {
    qWarning() << "QtCamDevice: viewfinder cannot be replaced.";
    return false;
  }

  if (!viewfinder->setDevice(this)) {
    return false;
  }

  d_ptr->viewfinder = viewfinder;

  return true;
}

bool QtCamDevice::start() {
  if (d_ptr->error) {
    qWarning() << "Pipeline must be stopped first because of an error.";
    return false;
  }

  if (!d_ptr->cameraBin) {
    qWarning() << "Missing camerabin";
    return false;
  }

  if (!d_ptr->viewfinder) {
    qWarning() << "Viewfinder not set";
    return false;
  }

  if (isRunning()) {
    return true;
  }

  if (!d_ptr->active) {
    d_ptr->image->activate();
  }
  else {
    d_ptr->active->applySettings();
  }

  // Set sink.
  if (!d_ptr->setViewfinderSink()) {
    return false;
  }

  GstStateChangeReturn err = gst_element_set_state(d_ptr->cameraBin, GST_STATE_PLAYING);
  if (err == GST_STATE_CHANGE_FAILURE) {
    qWarning() << "Failed to start camera pipeline";
    return false;
  }

  return true;
}

bool QtCamDevice::stop() {
  if (!d_ptr->cameraBin) {
    return true;
  }

  if (d_ptr->error) {
    gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL);
    d_ptr->error = false;
    return true;
  }

  GstState state;
  gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE);

  if (state == GST_STATE_NULL) {
    // Nothing to do.
    return true;
  }

  if (!isIdle()) {
    return false;
  }

  // First we go to ready:
  GstStateChangeReturn st = gst_element_set_state(d_ptr->cameraBin, GST_STATE_READY);
  if (st != GST_STATE_CHANGE_FAILURE) {
    // Flush the bus:
    d_ptr->listener->flushMessages();
  }

  // Now to NULL
  gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL);

  return true;
}

bool QtCamDevice::isRunning() {
  if (!d_ptr->cameraBin) {
    return false;
  }

  GstState state;
  GstStateChangeReturn err = gst_element_get_state(d_ptr->cameraBin,
						   &state, 0, GST_CLOCK_TIME_NONE);

  if (err == GST_STATE_CHANGE_FAILURE || state != GST_STATE_PLAYING) {
    return false;
  }

  return true;
}

bool QtCamDevice::isIdle() {
  if (!d_ptr->cameraBin) {
    return true;
  }

  gboolean idle = FALSE;
  g_object_get(d_ptr->cameraBin, "idle", &idle, NULL);

  return idle == TRUE;
}

QtCamImageMode *QtCamDevice::imageMode() const {
  return d_ptr->image;
}

QtCamVideoMode *QtCamDevice::videoMode() const {
  return d_ptr->video;
}

QtCamMode *QtCamDevice::activeMode() const {
  return d_ptr->active;
}

QString QtCamDevice::name() const {
  return d_ptr->name;
}

QVariant QtCamDevice::id() const {
  return d_ptr->id;
}

QtCamConfig *QtCamDevice::config() const {
  return d_ptr->conf;
}

QtCamGStreamerMessageListener *QtCamDevice::listener() const {
  return d_ptr->listener;
}

#include "moc_qtcamdevice.cpp"
<commit_msg>Wait for the state change to playing to complete before returning.<commit_after>#include "qtcamdevice.h"
#include "qtcamviewfinder.h"
#include "qtcamconfig.h"
#include "qtcamdevice_p.h"
#include <QDebug>
#include <gst/gst.h>
#include "qtcamgstreamermessagelistener.h"
#include "qtcammode.h"
#include "qtcamimagemode.h"
#include "qtcamvideomode.h"

QtCamDevice::QtCamDevice(QtCamConfig *config, const QString& name,
			 const QVariant& id, QObject *parent) :
  QObject(parent), d_ptr(new QtCamDevicePrivate) {

  d_ptr->q_ptr = this;
  d_ptr->name = name;
  d_ptr->id = id;
  d_ptr->conf = config;

  d_ptr->cameraBin = gst_element_factory_make("camerabin2", "QtCameraCameraBin");
  if (!d_ptr->cameraBin) {
    qCritical() << "Failed to create camerabin";
    return;
  }

  d_ptr->createAndAddElement(d_ptr->conf->audioSource(), "audio-source", "QtCameraAudioSrc");
  d_ptr->createAndAddVideoSource();

  int flags =
    0x00000001 /* no-audio-conversion - Do not use audio conversion elements */
    | 0x00000002 /* no-video-conversion - Do not use video conversion elements */
    | 0x00000004 /* no-viewfinder-conversion - Do not use viewfinder conversion elements */
    | 0x00000008; /* no-image-conversion - Do not use image conversion elements */

  g_object_set(d_ptr->cameraBin, "flags", flags, NULL);

  d_ptr->setAudioCaptureCaps();

  // TODO: audio bitrate
  // TODO: video bitrate
  // TODO: filters
  // TODO: capabilities
  // TODO: custom properties for jifmux, mp4mux, audio encoder, video encoder, sink & video source
  // color tune, scene modes
  d_ptr->listener = new QtCamGStreamerMessageListener(gst_element_get_bus(d_ptr->cameraBin),
						      d_ptr, this);

  QObject::connect(d_ptr->listener, SIGNAL(error(const QString&, int, const QString&)),
		   this, SLOT(_d_error(const QString&, int, const QString&)));
  QObject::connect(d_ptr->listener, SIGNAL(started()), this, SLOT(_d_started()));
  QObject::connect(d_ptr->listener, SIGNAL(stopped()), this, SLOT(_d_stopped()));
  QObject::connect(d_ptr->listener, SIGNAL(stopping()), this, SLOT(_d_stopping()));

  g_signal_connect(d_ptr->cameraBin, "notify::idle",
		   G_CALLBACK(QtCamDevicePrivate::on_idle_changed), d_ptr);

  g_signal_connect(d_ptr->wrapperVideoSource, "notify::ready-for-capture",
		   G_CALLBACK(QtCamDevicePrivate::on_ready_for_capture_changed), d_ptr);

  d_ptr->image = new QtCamImageMode(d_ptr, this);
  d_ptr->video = new QtCamVideoMode(d_ptr, this);
}

QtCamDevice::~QtCamDevice() {
  stop();

  d_ptr->image->deactivate();
  d_ptr->video->deactivate();

  delete d_ptr->image; d_ptr->image = 0;
  delete d_ptr->video; d_ptr->video = 0;
  delete d_ptr; d_ptr = 0;
}

bool QtCamDevice::setViewfinder(QtCamViewfinder *viewfinder) {
  if (isRunning()) {
    qWarning() << "QtCamDevice: pipeline must be stopped before setting a viewfinder";
    return false;
  }

  if (d_ptr->viewfinder == viewfinder) {
    return true;
  }

  if (!viewfinder) {
    qWarning() << "QtCamDevice: viewfinder cannot be unset.";
    return false;
  }

  if (d_ptr->viewfinder) {
    qWarning() << "QtCamDevice: viewfinder cannot be replaced.";
    return false;
  }

  if (!viewfinder->setDevice(this)) {
    return false;
  }

  d_ptr->viewfinder = viewfinder;

  return true;
}

bool QtCamDevice::start() {
  if (d_ptr->error) {
    qWarning() << "Pipeline must be stopped first because of an error.";
    return false;
  }

  if (!d_ptr->cameraBin) {
    qWarning() << "Missing camerabin";
    return false;
  }

  if (!d_ptr->viewfinder) {
    qWarning() << "Viewfinder not set";
    return false;
  }

  if (isRunning()) {
    return true;
  }

  if (!d_ptr->active) {
    d_ptr->image->activate();
  }
  else {
    d_ptr->active->applySettings();
  }

  // Set sink.
  if (!d_ptr->setViewfinderSink()) {
    return false;
  }

  GstStateChangeReturn err = gst_element_set_state(d_ptr->cameraBin, GST_STATE_PLAYING);
  if (err == GST_STATE_CHANGE_FAILURE) {
    qWarning() << "Failed to start camera pipeline";
    return false;
  }

  // We need to wait for startup to complet. There's a race condition somewhere in the pipeline.
  // If we set the scene mode to night and update the resolution while starting up
  // then subdevsrc2 barfs:
  // streaming task paused, reason not-negotiated (-4)
  GstState state;
  if (err != GST_STATE_CHANGE_ASYNC) {
    return true;
  }

  if (gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE)
      != GST_STATE_CHANGE_SUCCESS) {
    // We are seriously screwed up :(
    return false;
  }

  if (state != GST_STATE_PLAYING) {
    // Huh ? Is this even possible ??
    return false;
  }

  return true;
}

bool QtCamDevice::stop() {
  if (!d_ptr->cameraBin) {
    return true;
  }

  if (d_ptr->error) {
    gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL);
    d_ptr->error = false;
    return true;
  }

  GstState state;
  gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE);

  if (state == GST_STATE_NULL) {
    // Nothing to do.
    return true;
  }

  if (!isIdle()) {
    return false;
  }

  // First we go to ready:
  GstStateChangeReturn st = gst_element_set_state(d_ptr->cameraBin, GST_STATE_READY);
  if (st != GST_STATE_CHANGE_FAILURE) {
    // Flush the bus:
    d_ptr->listener->flushMessages();
  }

  // Now to NULL
  gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL);

  return true;
}

bool QtCamDevice::isRunning() {
  if (!d_ptr->cameraBin) {
    return false;
  }

  GstState state;
  GstStateChangeReturn err = gst_element_get_state(d_ptr->cameraBin,
						   &state, 0, GST_CLOCK_TIME_NONE);

  if (err == GST_STATE_CHANGE_FAILURE || state != GST_STATE_PLAYING) {
    return false;
  }

  return true;
}

bool QtCamDevice::isIdle() {
  if (!d_ptr->cameraBin) {
    return true;
  }

  gboolean idle = FALSE;
  g_object_get(d_ptr->cameraBin, "idle", &idle, NULL);

  return idle == TRUE;
}

QtCamImageMode *QtCamDevice::imageMode() const {
  return d_ptr->image;
}

QtCamVideoMode *QtCamDevice::videoMode() const {
  return d_ptr->video;
}

QtCamMode *QtCamDevice::activeMode() const {
  return d_ptr->active;
}

QString QtCamDevice::name() const {
  return d_ptr->name;
}

QVariant QtCamDevice::id() const {
  return d_ptr->id;
}

QtCamConfig *QtCamDevice::config() const {
  return d_ptr->conf;
}

QtCamGStreamerMessageListener *QtCamDevice::listener() const {
  return d_ptr->listener;
}

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