<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <fstream>
#include "Usuario.h"
#include "Cliente.h"
#include "Personal.h"
#include "Administrador.h"
#include "Chef.h"
#include "Lavaplatos.h"
#include "Mesero.h"

using namespace std;
void guardarArchivo(vector<Usuario*>);

int main(){
	vector<Usuario*> u;
	Cliente c("jalvarez","Jorge","asdf",23,"0801","98202419","Honduras",7);
	u.push_back(&c);
	Mesero m("jalvarez","Jorge","asdf",23,"0801","98654",5,15.5);
	u.push_back(&m);
	guardarArchivo(u);
}

vector<Usuario*> eliminarUsuario(vector<Usuario*> usuarios){
	int i;
	cout<<"Ingrese la posición del usuario que desea eliminar: "<<endl;
	cin>>i;
	usuarios.erase(usuarios.begin()+i);
	return usuarios;
}

void guardarArchivo(vector<Usuario*> Usuarios){
	//Clientes
	string Clientes="";
	string Administradores="";
	string Chefs="";
	string Lavaplatoss="";
	string Meseros="";
	for (int i = 0; i < Usuarios.size(); ++i)
	{
		if(dynamic_cast<Cliente*>(Usuarios[i]))
		{
			Cliente* temp=dynamic_cast<Cliente*>(Usuarios[i]);
			Clientes+=temp->getUsername()+" ";
			Clientes+=temp->getNombre()+" ";
			Clientes+=temp->getPassword()+" ";
			Clientes+=to_string(temp->getEdad())+" ";
			Clientes+=temp->getId()+" ";
			Clientes+=temp->getTelefono()+" ";
			Clientes+=temp->getDireccion()+" ";
			Clientes+=to_string(temp->getEstrellas())+" ";
			Clientes+="\n";
		}
		if(dynamic_cast<Administrador*>(Usuarios[i]))
		{
			Administrador* temp=dynamic_cast<Administrador*>(Usuarios[i]);
			Administradores+=temp->getUsername()+" ";
			Administradores+=temp->getNombre()+" ";
			Administradores+=temp->getPassword()+" ";
			Administradores+=to_string(temp->getEdad())+" ";
			Administradores+=temp->getId()+" ";
			Administradores+=temp->getTelefono()+" ";
			Administradores+=to_string(temp->getAnioContratado())+" ";
			Administradores+=to_string(temp->getSueldo())+" ";
			Administradores+=to_string(temp->getContratados())+" ";
			Administradores+=to_string(temp->getDespedidos())+" ";
			Administradores+="\n";
		}
		if(dynamic_cast<Chef*>(Usuarios[i]))
		{
			Chef* temp=dynamic_cast<Chef*>(Usuarios[i]);
			Chefs+=temp->getUsername()+" ";
			Chefs+=temp->getNombre()+" ";
			Chefs+=temp->getPassword()+" ";
			Chefs+=to_string(temp->getEdad())+" ";
			Chefs+=temp->getId()+" ";
			Chefs+=temp->getTelefono()+" ";
			Chefs+=to_string(temp->getAnioContratado())+" ";
			Chefs+=to_string(temp->getSueldo())+" ";
			Chefs+=temp->getPlatilloFavorito()+" ";
			Chefs+=to_string(temp->getRating())+" ";
			Chefs+="\n";
		}
		if(dynamic_cast<Lavaplatos*>(Usuarios[i]))
		{
			Lavaplatos* temp=dynamic_cast<Lavaplatos*>(Usuarios[i]);
			Lavaplatoss+=temp->getUsername()+" ";
			Lavaplatoss+=temp->getNombre()+" ";
			Lavaplatoss+=temp->getPassword()+" ";
			Lavaplatoss+=to_string(temp->getEdad())+" ";
			Lavaplatoss+=temp->getId()+" ";
			Lavaplatoss+=temp->getTelefono()+" ";
			Lavaplatoss+=to_string(temp->getAnioContratado())+" ";
			Lavaplatoss+=to_string(temp->getSueldo())+" ";
			Lavaplatoss+=to_string(temp->getMotivacion())+" ";
			Lavaplatoss+="\n";
		}
		if(dynamic_cast<Mesero*>(Usuarios[i]))
		{
			Mesero* temp=dynamic_cast<Mesero*>(Usuarios[i]);
			Meseros+=temp->getUsername()+" ";
			Meseros+=temp->getNombre()+" ";
			Meseros+=temp->getPassword()+" ";
			Meseros+=to_string(temp->getEdad())+" ";
			Meseros+=temp->getId()+" ";
			Meseros+=temp->getTelefono()+" ";
			Meseros+=to_string(temp->getAnioContratado())+" ";
			Meseros+=to_string(temp->getSueldo())+" ";
			Meseros+="\n";
		}
	}
	cout<<Clientes;
	ofstream archivo;
	string nombreArchivo;
	archivo.open("Clientes.txt",ios::out);
	archivo<<Clientes;
	archivo.close();
	archivo.open("Administradores.txt",ios::out);
	archivo<<Administradores;
	archivo.close();
	archivo.open("Chefs.txt",ios::out);
	archivo<<Chefs;
	archivo.close();
	archivo.open("Administradores.txt",ios::out);
	archivo<<Administradores;
	archivo.close();
	archivo.open("Lavaplatos.txt",ios::out);
	archivo<<Lavaplatoss;
	archivo.close();
	archivo.open("Meseros.txt",ios::out);
	archivo<<Meseros;
	archivo.close();
}<commit_msg>Se completo la función promedio<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <fstream>
#include "Usuario.h"
#include "Cliente.h"
#include "Personal.h"
#include "Administrador.h"
#include "Chef.h"
#include "Lavaplatos.h"
#include "Mesero.h"

using namespace std;
void guardarArchivo(vector<Usuario*>);

int main(){
	vector<Usuario*> u;
	Cliente c("jalvarez","Jorge","asdf",23,"0801","98202419","Honduras",7);
	u.push_back(&c);
	Mesero m("jalvarez","Jorge","asdf",23,"0801","98654",5,15.5);
	u.push_back(&m);
	guardarArchivo(u);
	cout<<cantPersonal(u);
}

vector<Usuario*> eliminarUsuario(vector<Usuario*> usuarios){
	int i;
	cout<<"Ingrese la posición del usuario que desea eliminar: "<<endl;
	cin>>i;
	usuarios.erase(usuarios.begin()+i);
	return usuarios;
}

double promedio(vector<Usuarios> Usuarios){
	int cantPersonal=0;
	double suma=0;
	double promedio;
	for (int i = 0; i < Usuarios.size(); ++i)
	{
		if (dynamic_cast<Personal>(Usuarios[i]))
		{
			Personal temp=dynamic_cast<Personal>(Usuarios[i]);
			suma+=temp.getSueldo();
			cantPersonal++;
		}
	}
	promedio=suma/cantPersonal;
	return cantPersonal;
}

void guardarArchivo(vector<Usuario*> Usuarios){
	//Clientes
	string Clientes="";
	string Administradores="";
	string Chefs="";
	string Lavaplatoss="";
	string Meseros="";
	for (int i = 0; i < Usuarios.size(); ++i)
	{
		if(dynamic_cast<Cliente*>(Usuarios[i]))
		{
			Cliente* temp=dynamic_cast<Cliente*>(Usuarios[i]);
			Clientes+=temp->getUsername()+" ";
			Clientes+=temp->getNombre()+" ";
			Clientes+=temp->getPassword()+" ";
			Clientes+=to_string(temp->getEdad())+" ";
			Clientes+=temp->getId()+" ";
			Clientes+=temp->getTelefono()+" ";
			Clientes+=temp->getDireccion()+" ";
			Clientes+=to_string(temp->getEstrellas())+" ";
			Clientes+="\n";
		}
		if(dynamic_cast<Administrador*>(Usuarios[i]))
		{
			Administrador* temp=dynamic_cast<Administrador*>(Usuarios[i]);
			Administradores+=temp->getUsername()+" ";
			Administradores+=temp->getNombre()+" ";
			Administradores+=temp->getPassword()+" ";
			Administradores+=to_string(temp->getEdad())+" ";
			Administradores+=temp->getId()+" ";
			Administradores+=temp->getTelefono()+" ";
			Administradores+=to_string(temp->getAnioContratado())+" ";
			Administradores+=to_string(temp->getSueldo())+" ";
			Administradores+=to_string(temp->getContratados())+" ";
			Administradores+=to_string(temp->getDespedidos())+" ";
			Administradores+="\n";
		}
		if(dynamic_cast<Chef*>(Usuarios[i]))
		{
			Chef* temp=dynamic_cast<Chef*>(Usuarios[i]);
			Chefs+=temp->getUsername()+" ";
			Chefs+=temp->getNombre()+" ";
			Chefs+=temp->getPassword()+" ";
			Chefs+=to_string(temp->getEdad())+" ";
			Chefs+=temp->getId()+" ";
			Chefs+=temp->getTelefono()+" ";
			Chefs+=to_string(temp->getAnioContratado())+" ";
			Chefs+=to_string(temp->getSueldo())+" ";
			Chefs+=temp->getPlatilloFavorito()+" ";
			Chefs+=to_string(temp->getRating())+" ";
			Chefs+="\n";
		}
		if(dynamic_cast<Lavaplatos*>(Usuarios[i]))
		{
			Lavaplatos* temp=dynamic_cast<Lavaplatos*>(Usuarios[i]);
			Lavaplatoss+=temp->getUsername()+" ";
			Lavaplatoss+=temp->getNombre()+" ";
			Lavaplatoss+=temp->getPassword()+" ";
			Lavaplatoss+=to_string(temp->getEdad())+" ";
			Lavaplatoss+=temp->getId()+" ";
			Lavaplatoss+=temp->getTelefono()+" ";
			Lavaplatoss+=to_string(temp->getAnioContratado())+" ";
			Lavaplatoss+=to_string(temp->getSueldo())+" ";
			Lavaplatoss+=to_string(temp->getMotivacion())+" ";
			Lavaplatoss+="\n";
		}
		if(dynamic_cast<Mesero*>(Usuarios[i]))
		{
			Mesero* temp=dynamic_cast<Mesero*>(Usuarios[i]);
			Meseros+=temp->getUsername()+" ";
			Meseros+=temp->getNombre()+" ";
			Meseros+=temp->getPassword()+" ";
			Meseros+=to_string(temp->getEdad())+" ";
			Meseros+=temp->getId()+" ";
			Meseros+=temp->getTelefono()+" ";
			Meseros+=to_string(temp->getAnioContratado())+" ";
			Meseros+=to_string(temp->getSueldo())+" ";
			Meseros+="\n";
		}
	}
	cout<<Clientes;
	ofstream archivo;
	string nombreArchivo;
	archivo.open("Clientes.txt",ios::out);
	archivo<<Clientes;
	archivo.close();
	archivo.open("Administradores.txt",ios::out);
	archivo<<Administradores;
	archivo.close();
	archivo.open("Chefs.txt",ios::out);
	archivo<<Chefs;
	archivo.close();
	archivo.open("Administradores.txt",ios::out);
	archivo<<Administradores;
	archivo.close();
	archivo.open("Lavaplatos.txt",ios::out);
	archivo<<Lavaplatoss;
	archivo.close();
	archivo.open("Meseros.txt",ios::out);
	archivo<<Meseros;
	archivo.close();
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <quvi/quvi.h>
#include <cstdlib>

struct MediaInfo
{
    bool IsValid;

    std::string Url;
    std::string Title;
    std::string Id;
    int ContentLength;
    std::string ContentType;
    std::string Extension;
    int Duration;

    MediaInfo() : IsValid(false) {}
};

MediaInfo ExtractMediaFromUrl(const std::string& url)
{
    MediaInfo info;

    quvi_t q;
    quvi_init(&q);

    //char *avail_formats;
    //quvi_query_formats(q, (char*)url.c_str(), &avail_formats);
    //std::cout << avail_formats << std::endl;

    // Get the best possible quality
    quvi_setopt(q, QUVIOPT_FORMAT, "best"); // Could be any of the avail_formats list

    quvi_media_t m;
    if(quvi_parse(q, (char*)url.c_str(), &m) != QUVI_OK)
        return info;

    char* prop;
    quvi_getprop(m, QUVIPROP_MEDIAURL, &prop);
    info.Url = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_PAGETITLE, &prop);
    info.Title = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_MEDIAID, &prop);
    info.Id = (prop ? prop : "");

    //quvi_getprop(m, QUVIPROP_MEDIACONTENTLENGTH, &prop);
    //info.ContentLength = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_MEDIACONTENTTYPE, &prop);
    info.ContentType = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_FILESUFFIX, &prop);
    info.Extension = (prop ? prop : "");

    //quvi_getprop(m, QUVIPROP_MEDIADURATION, &prop);
    //info.Duration = (prop ? prop : "");

    //std::cout << "video url: " << mediaUrl << std::endl;
    quvi_parse_close(&m);
    quvi_close(&q);

    info.IsValid = true;
    return info;
}

void ShowUsage()
{
    std::cout << "Usage: vidfetch [-format] <url>" << std::endl;
    std::cout << "\treplace 'format' by the destination file format (the file extension)" << std::endl;
    std::cout << "\tIf no format is specified, no conversion occurs" << std::endl;
}

int main(int argc, char **argv)
{
    if(argc == 2 && std::string(argv[1]) == "--help")
    {
        ShowUsage();
        return 0;
    }

    if(argc < 2)
    {
        ShowUsage();
        return 1;
    }

    std::string format;
    std::string url;

    for(int i = 1; i < argc; ++i)
    {
        std::string arg = argv[i];
        if(arg[0] == '-')
            format = arg.substr(1);
        else
            url = arg;
    }

    MediaInfo info = ExtractMediaFromUrl(url);
    if(info.IsValid)
    {
        std::cout << info.Url << std::endl;
        std::cout << info.Title << std::endl;
        std::cout << info.Extension << std::endl;
    }

    std::string origFilename = info.Title + "." + info.Extension;
    system(("curl -C - \"" + info.Url + "\" -o \"" + origFilename + "\"").c_str());

    // If conversion needed (if a conversion format has been specified):
    if(format != "")
    {
        std::string finalFilename = info.Title + "." + format;

        system(("ffmpeg -i \"" + origFilename + "\" -sameq \"" + finalFilename + "\"").c_str());

        // Remove original
        system(("rm \"" + origFilename + "\"").c_str());
    }
}
<commit_msg>-sameq parameter doesn't exist anymore in ffmpeg, replaced with qscale<commit_after>#include <iostream>
#include <string>
#include <quvi/quvi.h>
#include <cstdlib>

struct MediaInfo
{
    bool IsValid;

    std::string Url;
    std::string Title;
    std::string Id;
    int ContentLength;
    std::string ContentType;
    std::string Extension;
    int Duration;

    MediaInfo() : IsValid(false) {}
};

MediaInfo ExtractMediaFromUrl(const std::string& url)
{
    MediaInfo info;

    quvi_t q;
    quvi_init(&q);

    //char *avail_formats;
    //quvi_query_formats(q, (char*)url.c_str(), &avail_formats);
    //std::cout << avail_formats << std::endl;

    // Get the best possible quality
    quvi_setopt(q, QUVIOPT_FORMAT, "best"); // Could be any of the avail_formats list

    quvi_media_t m;
    if(quvi_parse(q, (char*)url.c_str(), &m) != QUVI_OK)
        return info;

    char* prop;
    quvi_getprop(m, QUVIPROP_MEDIAURL, &prop);
    info.Url = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_PAGETITLE, &prop);
    info.Title = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_MEDIAID, &prop);
    info.Id = (prop ? prop : "");

    //quvi_getprop(m, QUVIPROP_MEDIACONTENTLENGTH, &prop);
    //info.ContentLength = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_MEDIACONTENTTYPE, &prop);
    info.ContentType = (prop ? prop : "");

    quvi_getprop(m, QUVIPROP_FILESUFFIX, &prop);
    info.Extension = (prop ? prop : "");

    //quvi_getprop(m, QUVIPROP_MEDIADURATION, &prop);
    //info.Duration = (prop ? prop : "");

    //std::cout << "video url: " << mediaUrl << std::endl;
    quvi_parse_close(&m);
    quvi_close(&q);

    info.IsValid = true;
    return info;
}

void ShowUsage()
{
    std::cout << "Usage: vidfetch [-format] <url>" << std::endl;
    std::cout << "\treplace 'format' by the destination file format (the file extension)" << std::endl;
    std::cout << "\tIf no format is specified, no conversion occurs" << std::endl;
}

int main(int argc, char **argv)
{
    if(argc == 2 && std::string(argv[1]) == "--help")
    {
        ShowUsage();
        return 0;
    }

    if(argc < 2)
    {
        ShowUsage();
        return 1;
    }

    std::string format;
    std::string url;

    for(int i = 1; i < argc; ++i)
    {
        std::string arg = argv[i];
        if(arg[0] == '-')
            format = arg.substr(1);
        else
            url = arg;
    }

    MediaInfo info = ExtractMediaFromUrl(url);
    if(info.IsValid)
    {
        std::cout << info.Url << std::endl;
        std::cout << info.Title << std::endl;
        std::cout << info.Extension << std::endl;
    }

    std::string origFilename = info.Title + "." + info.Extension;
    system(("curl -C - \"" + info.Url + "\" -o \"" + origFilename + "\"").c_str());

    // If conversion needed (if a conversion format has been specified):
    if(format != "")
    {
        std::string finalFilename = info.Title + "." + format;

        system(("ffmpeg -i \"" + origFilename + "\" -qscale 0 \"" + finalFilename + "\"").c_str());

        // Remove original
        system(("rm \"" + origFilename + "\"").c_str());
    }
}
<|endoftext|>


<commit_before>#include <iostream>
using namespace std;
//Author: Caiden Sacks

void allTest();
void additionTest();
void subtractionTest();
void multiplicationTest();
void divisionTest();
bool Again();

double num1, num2, num3, num4, num5;
double rule;
bool addRule;
bool subRule;
bool multRule;
bool divRule;
char contVar;

int main()
{
	allTest();
}

void additionTest()
{
	double addTest1, addTest2, addTest3, addTest4;

	addTest1 = num2 - num1;
	addTest2 = num3 - num2;
	addTest3 = num4 - num3;
	addTest4 = num5 - num4;

	if (addTest1 == addTest2 && addTest2 == addTest3 && addTest3 == addTest4)
	{
		rule = addTest1;
		addRule = true;
		cout << "The rule for the numbers you entered is y = x + " << rule << endl;
	}
	else
		addRule = false;
}

void subtractionTest()
{
	double subTest1, subTest2, subTest3, subTest4;

		subTest1 = num1 - num2;
		subTest2 = num2 - num3;
		subTest3 = num3 - num4;
		subTest4 = num4 - num5;

		if (subTest1 == subTest2 && subTest2 == subTest3 && subTest3 == subTest4)
		{
			rule = subTest1;
			subRule = true;
			cout << "The rule for the numbers you entered is y = x - " << rule << endl;
		}
		else
			subRule = false;
}

void multiplicationTest()
{
	double multTest1, multTest2, multTest3, multTest4;

	multTest1 = num2 / num1;
	multTest2 = num3 / num2;
	multTest3 = num4 / num3;
	multTest4 = num5 / num4;

	if (multTest1 == multTest2 && multTest2 == multTest3 && multTest3 == multTest4)
	{
		rule = multTest1;
		multRule = true;
		cout << "The rule for the numbers you entered is y = " << rule << "x" << endl;
	}
	else
		multRule = false;
}

void divisionTest()
{
	double divTest1, divTest2, divTest3, divTest4;

	divTest1 = num1 / num2;
	divTest2 = num2 / num3;
	divTest3 = num3 / num4;
	divTest4 = num4 / num5;

	if (divTest1 == divTest2 && divTest2 == divTest3 && divTest3 == divTest4)
	{
		rule = divTest1;
		divRule = true;
		cout << "The rule for the numbers you entered is y = x / " << rule << endl;
	}
	else
		divRule = false;
}

void allTest()
{
	do
	{
		cout << "Please enter five numbers: ";
		cin >> num1 >> num2 >> num3 >> num4 >> num5;

		additionTest();

		subtractionTest();

		multiplicationTest();

		divisionTest();

		if (addRule != true && subRule != true && multRule != true && divRule != true)
		{
			cout << "No discernible pattern was found." << endl;
		}
	} while (Again() != false);
}

bool Again()
{
	cout << "If you would like to quit the program, enter 'Q'. If you would like to enter another set, enter anything except 'Q': ";
	cin >> contVar;
	if (contVar == 'Q' || contVar == 'q')
	{
		return false;
	}
	else
	{
		return true;
	}
}
<commit_msg>Added exponential rule recognition<commit_after>#include <iostream>
#include <cmath>
using namespace std;
//Author: Caiden Sacks

void allTest();
void additionTest();
void subtractionTest();
void multiplicationTest();
void divisionTest();
void powerTest();
bool Again();

double num1, num2, num3, num4, num5;
double rule;
bool addRule, subRule, multRule, divRule, powRule;

char contVar;

int main()
{
	allTest();
}

void additionTest()
{
	double addTest1, addTest2, addTest3, addTest4;

	addTest1 = num2 - num1;
	addTest2 = num3 - num2;
	addTest3 = num4 - num3;
	addTest4 = num5 - num4;
	double* addend = &addTest1;

	if (addTest1 == addTest2 && addTest2 == addTest3 && addTest3 == addTest4)
	{
		addRule = true;
		cout << "The rule for the numbers you entered is y = x + " << *addend << endl;
	}
	else
		addRule = false;
}

void subtractionTest()
{
	double subTest1, subTest2, subTest3, subTest4;

		subTest1 = num1 - num2;
		subTest2 = num2 - num3;
		subTest3 = num3 - num4;
		subTest4 = num4 - num5;
		double* subtrahend = &subTest1;

		if (subTest1 == subTest2 && subTest2 == subTest3 && subTest3 == subTest4)
		{
			subRule = true;
			cout << "The rule for the numbers you entered is y = x - " << *subtrahend << endl;
		}
		else
			subRule = false;
}

void multiplicationTest()
{
	double multTest1, multTest2, multTest3, multTest4;

	multTest1 = num2 / num1;
	multTest2 = num3 / num2;
	multTest3 = num4 / num3;
	multTest4 = num5 / num4;
	double* factor = &multTest1;

	if (multTest1 == multTest2 && multTest2 == multTest3 && multTest3 == multTest4)
	{
		multRule = true;
		cout << "The rule for the numbers you entered is y = " << *factor << "x" << endl;
	}
	else
		multRule = false;
}

void divisionTest()
{
	double divTest1, divTest2, divTest3, divTest4;

	divTest1 = num1 / num2;
	divTest2 = num2 / num3;
	divTest3 = num3 / num4;
	divTest4 = num4 / num5;
	double* divisor = &divTest1;

	if (divTest1 == divTest2 && divTest2 == divTest3 && divTest3 == divTest4)
	{
		divRule = true;
		cout << "The rule for the numbers you entered is y = x / " << *divisor << endl;
	}
	else
		divRule = false;
}

void powerTest()
{
	double powTest1, powTest2, powTest3, powTest4;

	powTest1 = log(num2) / log(num1);
	powTest2 = log(num3) / log(num2);
	powTest3 = log(num4) / log(num3);
	powTest4 = log(num5) / log(num4);
	double* power = &powTest1;

	if (powTest1 == powTest2 && powTest2 == powTest3 && powTest3 == powTest4)
	{
		powRule = true;
		cout << "The rule for the numbers you entered is y = x ^ " << *power << endl;
	}
	else
		powRule = false;
}

void allTest()
{
	do
	{
		cout << "Please enter five numbers: ";
		cin >> num1 >> num2 >> num3 >> num4 >> num5;

		additionTest();

		subtractionTest();

		multiplicationTest();

		divisionTest();

		powerTest();

		if (addRule != true && subRule != true && multRule != true && divRule != true && powRule != true)
		{
			cout << "No discernible pattern was found." << endl;
		}
	} while (Again() != false);
}

bool Again()
{
	cout << "If you would like to quit the program, enter 'Q'. If you would like to enter another set, enter anything except 'Q': ";
	cin >> contVar;
	if (contVar == 'Q' || contVar == 'q')
	{
		return false;
	}
	else
	{
		return true;
	}
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <cmath>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <stdio.h>
#include "moon.h"
#include "star.h"

bool isWhite(sf::Image& image, float px, float py){
	return image.getPixel(px, py) == sf::Color::White;
}

float getAngle(sf::Vector2f &orig, sf::Vector2i &des) {
    return std::atan2(des.y - orig.y, des.x - orig.x)*180/(M_PI);
}

namespace State{
enum state {
  Idle, Speaking, Searching, GroupChat, fadeOut
};
}

float distance(const sf::Vector2f &orig, const sf::Vector2f &des) {
    return std::sqrt(std::pow(std::abs(des.x-orig.x), 2) + std::pow(std::abs(des.y-orig.y), 2));
}

float getAngle(const sf::Vector2f &orig,const sf::Vector2f &des) {
    return std::atan2(des.y - orig.y, des.x - orig.x)*180/(M_PI);
}

int main(){

    /* initialize random seed: */
    srand (time(NULL));

	//SFML OBJECTS
	sf::View view;
	sf::Event event;
	sf::Clock deltaClock;

    sf::CircleShape guia;
    guia.setRadius(10);
    guia.setFillColor(sf::Color(200,200,200,50));
    guia.setOrigin(guia.getLocalBounds().width/2, guia.getLocalBounds().height/2);

    float deltatime = 0.0;

    sf::Font font;
    font.loadFromFile("res/font.otf");

    int moonSentenceIndex = 0;
    std::vector <std::string> moonSentences;

    int groupIndex = 0;
    std::vector< std::vector <std::pair <float, std::string > > > groups =
    {
        {
            std::pair <float, std::string >(0, "Hi, been a long time!"),
            std::pair <float, std::string >(5, "I've missed you so much!")
        }
        ,
        {
            std::pair <float, std::string >(0, "Glad you are here!"),
            std::pair <float, std::string >(6, "Oh, I love you! ^^ ")
        }
        ,
        {
        }
        ,
        {
            std::pair <float, std::string >(0, "Hey boys!"),
            std::pair <float, std::string >(6, "You are awesome!"),
            std::pair <float, std::string >(10, "So good to see you all!!!")
        }
        ,
        {
            std::pair <float, std::string >(0, "Loneliness fades away with you"),
            std::pair <float, std::string >(6, "We are all good together!")
        }
        ,
        {}
        ,
        {}
    };

    moonSentences.push_back("I'm so alone in this universe... \n Is hard to live this way...");
    moonSentences.push_back("I wish someone missed me too...");
    moonSentences.push_back("Has to be so nice to be loved...");
    moonSentences.push_back("Wish someone would care about me... \n I'm sure is a warm feeling...");
    moonSentences.push_back("Friendship... It hurts so much not having it...");
    moonSentences.push_back("Are we? I'm invisible to them...");
    moonSentences.push_back("But wait...");
    moonSentences.push_back("What if everyone was talking about me this whole time?");
    moonSentences.push_back("Game made with love  \n by Genís Bayona at Oxfordhacks 2016");
    moonSentences.push_back("Music: Sad Day from \n Royalty Free Music Bensound. "

    Moon moon("The life of the moon is so lonely", font);
    moon.setOrigin(moon.getLocalBounds().width/2, moon.getLocalBounds().height/2);

    std::vector < Star > stars;

    State::state currentState = State::Idle;

    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), L"The Moon", sf::Style::Resize|sf::Style::Close);

    view.reset(sf::FloatRect(0,0,
                             window.getSize().x, window.getSize().y));

    window.setFramerateLimit(30);

    std::vector < sf::CircleShape > ministars;

    float fadeOutValue = 0;

    sf::Music m;
    m.openFromFile("res/music.ogg");
    m.setLoop(true);
    m.play();

	//GAME LOOP
	while(window.isOpen()){

        //Deltatime
        deltatime = deltaClock.restart().asSeconds();

		//Loop for handling events
		while(window.pollEvent(event)){
			switch (event.type){
				//Close event
				case sf::Event::Closed:
					window.close();
					break;
				//KeyPressed event
				case  sf::Event::KeyPressed:
					//Close key
					if (event.key.code == sf::Keyboard::Escape) {
						window.close();
					}
                //Default
				default:
					//Do nothing
					break;
			}
		}

sf::Vector2f groupPosition;
        switch(currentState){
        case State::Idle:
            //std::cout << "idle" << std::endl;
            if(moon.textBox.finished()){
                //std::cout << "boobs" << std::endl;
                if(moonSentenceIndex >= moonSentences.size()) moon.setSentence("Thank you : )");
                else moon.setSentence(moonSentences[moonSentenceIndex]);
                ++moonSentenceIndex;
                currentState = State::Speaking;
            }
            break;
        case State::Speaking:
            //std::cout << "speaking" << std::endl;
            if(moon.textBox.finished()){
                currentState = State::Searching;

                if(groupIndex < groups.size()){
                    auto group = groups[groupIndex];
                    ++groupIndex;

                    int sign1 = -1;
                    if( rand()%2 == 0) sign1 = 1;
                    int sign2 = -1;
                    if( rand()%2 == 0) sign2 = 1;
                    int sign3 = -1;
                    if( rand()%2 == 0) sign3 = 1;
                    int sign4 = -1;
                    if( rand()%2 == 0) sign4 = 1;

                    int w_size = static_cast<int>(window.getSize().y);
                    groupPosition = moon.getPosition() + sf::Vector2f((w_size/5 + rand()%w_size) * sign1,
                                                                    (w_size/5 + rand()%w_size) * sign2);

                    for(auto &pair: group){
                        stars.emplace_back(Star(font, pair.first));
                        stars[stars.size()-1].setPosition(groupPosition+sf::Vector2f((20 + rand()%150) * sign3,
                                                                                (20 + rand()%150) * sign4));
                        stars[stars.size()-1].setSentence(pair.second);
                    }
                }
                else {
                    int size = 20;
                    stars.emplace_back(Star(font, 2));
                    stars[stars.size()-1].setPosition(sf::Vector2f(0.0,0.0));
                    stars[stars.size()-1].setSentence(": )");

                    stars.emplace_back(Star(font, 3));
                    stars[stars.size()-1].setPosition(sf::Vector2f(1*size,-1.42*size));
                    stars[stars.size()-1].setSentence("<3");

                    stars.emplace_back(Star(font, 3));
                    stars[stars.size()-1].setPosition(sf::Vector2f(-1*size,-1.42*size));
                    stars[stars.size()-1].setSentence("<3");

                    stars.emplace_back(Star(font, 4));
                    stars[stars.size()-1].setPosition(sf::Vector2f(2*size,-2.84*size));
                    stars[stars.size()-1].setSentence(": )");

                    stars.emplace_back(Star(font, 4));
                    stars[stars.size()-1].setPosition(sf::Vector2f(-2*size,-2.84*size));
                    stars[stars.size()-1].setSentence("<3");

                    stars.emplace_back(Star(font, 5));
                    stars[stars.size()-1].setPosition(sf::Vector2f(1.6*size,-3.9*size));
                    stars[stars.size()-1].setSentence(": )");

                    stars.emplace_back(Star(font, 3));
                    stars[stars.size()-1].setPosition(sf::Vector2f(-1.4*size,-3.9*size));
                    stars[stars.size()-1].setSentence("( :");

                    stars.emplace_back(Star(font, 6));
                    stars[stars.size()-1].setPosition(sf::Vector2f(0*size,-3.1*size));
                    stars[stars.size()-1].setSentence("<3");
                }
            }
            break;
        case State::Searching:
        {
            ////std::cout << "seraching the meaning of life" << moon.getPosition().x << "," <<moon.getPosition().y << std::endl;
            bool goToNextState = true;
            for(Star &s : stars){
               //// std::cout << "star -> " << s.getPosition().x << ";" << s.getPosition().y << std::endl;
                if(distance(moon.getPosition(), s.getPosition()) > window.getSize().y/2) goToNextState = false;
            }
            for(Star &s : stars){
                s.update(deltatime);
            }
            if(goToNextState){
                for(Star &s : stars){
                    s.setCanSpeak(true);
                }
                currentState = State::GroupChat;
            }

            break;
        }
        case State::GroupChat:
        {
            //std::cout << "groupchating (. Y .)" << std::endl;
            for(Star &s : stars){
                s.update(deltatime);
            }

            bool finished = true;
            for(Star &s : stars){
                if(!s.textBox.finished()) finished = false;
            }

            if(finished) {
                fadeOutValue = 0.0;
                currentState = State::fadeOut;
            }
            break;
        }
        case State::fadeOut:
            if(fadeOutValue <= 1){
                fadeOutValue += deltatime* 0.5;
                for(Star &s : stars){
                    s.setColor(sf::Color(255,255,255, 255-255*fadeOutValue));
                    s.sglow.setColor(sf::Color(255,255,255, 255-255*fadeOutValue));
                }
            }
            else {
                stars.clear();
                currentState = State::Idle;
            }
            break;
        default:
            break;
        }

        moon.update(deltatime, window);
		//Set view values
        sf::Vector2f viewPosition = view.getCenter();

        view.reset(sf::FloatRect(viewPosition.x, viewPosition.y,
                                 window.getSize().x, window.getSize().y));

        sf::Vector2f step;
        step.x = (viewPosition.x - moon.getPosition().x+10) *-0.1* deltatime;
        step.y = (viewPosition.y - moon.getPosition().y+10) *-0.1* deltatime;

        float maxDist = 20;
        float dist = distance(viewPosition, moon.getPosition());
        sf::Vector2f extra(0.f,0.f);
        if( dist > maxDist){
            extra.x = (viewPosition.x - moon.getPosition().x+10) *-1* deltatime;
            extra.y = (viewPosition.y - moon.getPosition().y+10) *-1* deltatime;
        }

        view.setCenter(viewPosition + step + extra);
        view.setViewport(sf::FloatRect(0,0,1.0f,1.0f));

/*
        view.reset(sf::FloatRect(moon.getPosition().x, moon.getPosition().y,
                                 window.getSize().x, window.getSize().y));

        viewPosition.y = moon.getPosition().y+10;
        viewPosition.x = moon.getPosition().x+10;
        view.setCenter(viewPosition);
        view.setViewport(sf::FloatRect(0,0,1.0f,1.0f));
*/

		//Set window view, draw and display
        window.setView(view);

        sf::Color c = sf::Color(0,0,0,0.1);
        window.clear(c);

        for(auto it = ministars.begin(); it != ministars.end();){
            if(std::abs(it->getPosition().x - moon.getPosition().x) > window.getSize().x
                    || std::abs(it->getPosition().y - moon.getPosition().y) > window.getSize().y
                    ) it = ministars.erase(it);
            else ++it;
        }

        const int maxStars = 50;
        if(ministars.size() < maxStars){
            for(int i = ministars.size(); i < maxStars; ++i){
                sf::Vector2f pos;
                pos.x = rand()%window.getSize().x;
                pos.x -= window.getSize().x/2;
                pos.y = rand()%window.getSize().y;
                pos.y -= window.getSize().y/2;
                sf::CircleShape c(1,4);
                c.setPosition(moon.getPosition() + pos);
                c.setFillColor(sf::Color(250,250,250,100));
                ministars.push_back(c);
            }
        }

        for(int i = 0; i < maxStars; ++i){
            window.draw(ministars[i]);
        }

        if(stars.size() > 0){
            float angle = getAngle(moon.getPosition(), stars[0].getPosition());
            //std::cout << "the angle is "<< angle << std::endl;
            sf::Vector2f guiaPos;
            guia.setFillColor(sf::Color(200,200,200,50));
            guiaPos.x = moon.getPosition().x + std::cos(angle*M_PI/180) * (moon.getRadius()*3 + guia.getRadius());
            guiaPos.y = moon.getPosition().y + std::sin(angle*M_PI/180) * (moon.getRadius()*3 + guia.getRadius());
            guia.setPosition(guiaPos);
            window.draw(guia);

            guia.setFillColor(sf::Color(0,0,0,255));
            guiaPos.x = moon.getPosition().x + std::cos(angle*M_PI/180) * (moon.getRadius()*3 );//+ guia.getRadius());
            guiaPos.y = moon.getPosition().y + std::sin(angle*M_PI/180) * (moon.getRadius()*3 );//+ guia.getRadius());
            guia.setPosition(guiaPos);
            window.draw(guia);

        }

        for(Star &s : stars){
            /*
            float dist = std::abs(distance(moon.getPosition(), s.getPosition()));
            if(dist < 2*moon.getGlobalBounds().width){
                float factor = dist/2.f*moon.getGlobalBounds().width;
                s.setColor(sf::Color(255,255,255,int(255*factor)));
            }else s.setColor(sf::Color(255,255,255,255));
            */
            s.render(window);
            //window.draw(s);
        }
        moon.render(window);
        window.display();

	}
}
<commit_msg>credits and final and stuff<commit_after>#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <cmath>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <stdio.h>
#include "moon.h"
#include "star.h"

bool isWhite(sf::Image& image, float px, float py){
	return image.getPixel(px, py) == sf::Color::White;
}

float getAngle(sf::Vector2f &orig, sf::Vector2i &des) {
    return std::atan2(des.y - orig.y, des.x - orig.x)*180/(M_PI);
}

namespace State{
enum state {
  Idle, Speaking, Searching, GroupChat, fadeOut
};
}

float distance(const sf::Vector2f &orig, const sf::Vector2f &des) {
    return std::sqrt(std::pow(std::abs(des.x-orig.x), 2) + std::pow(std::abs(des.y-orig.y), 2));
}

float getAngle(const sf::Vector2f &orig,const sf::Vector2f &des) {
    return std::atan2(des.y - orig.y, des.x - orig.x)*180/(M_PI);
}

int main(){

    /* initialize random seed: */
    srand (time(NULL));

	//SFML OBJECTS
	sf::View view;
	sf::Event event;
	sf::Clock deltaClock;

    sf::CircleShape guia;
    guia.setRadius(10);
    guia.setFillColor(sf::Color(200,200,200,50));
    guia.setOrigin(guia.getLocalBounds().width/2, guia.getLocalBounds().height/2);

    float deltatime = 0.0;

    sf::Font font;
    font.loadFromFile("res/font.otf");

    int moonSentenceIndex = 0;
    std::vector <std::string> moonSentences;

    int groupIndex = 0;
    std::vector< std::vector <std::pair <float, std::string > > > groups =
    {
        {
            std::pair <float, std::string >(0, "Hi, been a long time!"),
            std::pair <float, std::string >(5, "I've missed you so much!")
        }
        ,
        {
            std::pair <float, std::string >(0, "Glad you are here!"),
            std::pair <float, std::string >(6, "Oh, I love you! ^^ ")
        }
        ,
        {
        }
        ,
        {
            std::pair <float, std::string >(0, "Hey boys!"),
            std::pair <float, std::string >(6, "You are awesome!"),
            std::pair <float, std::string >(10, "So good to see you all!!!")
        }
        ,
        {
            std::pair <float, std::string >(0, "Loneliness fades away with you"),
            std::pair <float, std::string >(6, "We are all good together!")
        }
        ,
        {}
        ,
        {}
    };

    moonSentences.push_back("I'm so alone in this universe... \n Is hard to live this way...");
    moonSentences.push_back("I wish someone missed me too...");
    moonSentences.push_back("Has to be so nice to be loved...");
    moonSentences.push_back("Wish someone would care about me... \n I'm sure is a warm feeling...");
    moonSentences.push_back("Friendship... It hurts so much not having it...");
    moonSentences.push_back("Are we? I'm invisible to them...");
    moonSentences.push_back("But wait...");
    moonSentences.push_back("What if everyone was talking about me this whole time?");
    moonSentences.push_back("Game made with love  \n by Genis Bayona \n at Oxfordhacks 2016");
    moonSentences.push_back("Music: Sad Day from \n Royalty Free Music \n Bensound. ");

    Moon moon("The life of the moon is so lonely", font);
    moon.setOrigin(moon.getLocalBounds().width/2, moon.getLocalBounds().height/2);

    std::vector < Star > stars;

    State::state currentState = State::Idle;

    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), L"The Moon", sf::Style::Resize|sf::Style::Close);

    view.reset(sf::FloatRect(0,0,
                             window.getSize().x, window.getSize().y));

    window.setFramerateLimit(30);

    std::vector < sf::CircleShape > ministars;

    float fadeOutValue = 0;

    sf::Music m;
    m.openFromFile("res/music.ogg");
    m.setLoop(true);
    m.play();

	//GAME LOOP
	while(window.isOpen()){

        //Deltatime
        deltatime = deltaClock.restart().asSeconds();

		//Loop for handling events
		while(window.pollEvent(event)){
			switch (event.type){
				//Close event
				case sf::Event::Closed:
					window.close();
					break;
				//KeyPressed event
				case  sf::Event::KeyPressed:
					//Close key
					if (event.key.code == sf::Keyboard::Escape) {
						window.close();
					}
                //Default
				default:
					//Do nothing
					break;
			}
		}

sf::Vector2f groupPosition;
        switch(currentState){
        case State::Idle:
            //std::cout << "idle" << std::endl;
            if(moon.textBox.finished()){
                //std::cout << "boobs" << std::endl;
                if(moonSentenceIndex >= moonSentences.size()) moon.setSentence("Thank you : )");
                else moon.setSentence(moonSentences[moonSentenceIndex]);
                ++moonSentenceIndex;
                currentState = State::Speaking;
            }
            break;
        case State::Speaking:
            //std::cout << "speaking" << std::endl;
            if(moon.textBox.finished()){
                currentState = State::Searching;

                if(groupIndex < groups.size()){
                    auto group = groups[groupIndex];
                    ++groupIndex;

                    int sign1 = -1;
                    if( rand()%2 == 0) sign1 = 1;
                    int sign2 = -1;
                    if( rand()%2 == 0) sign2 = 1;
                    int sign3 = -1;
                    if( rand()%2 == 0) sign3 = 1;
                    int sign4 = -1;
                    if( rand()%2 == 0) sign4 = 1;

                    int w_size = static_cast<int>(window.getSize().y);
                    groupPosition = moon.getPosition() + sf::Vector2f((w_size/5 + rand()%w_size) * sign1,
                                                                    (w_size/5 + rand()%w_size) * sign2);

                    for(auto &pair: group){
                        stars.emplace_back(Star(font, pair.first));
                        stars[stars.size()-1].setPosition(groupPosition+sf::Vector2f((20 + rand()%150) * sign3,
                                                                                (20 + rand()%150) * sign4));
                        stars[stars.size()-1].setSentence(pair.second);
                    }
                }
                else {
                    int size = 20;
                    stars.emplace_back(Star(font, 2));
                    stars[stars.size()-1].setPosition(sf::Vector2f(0.0,0.0));
                    stars[stars.size()-1].setSentence(": )");

                    stars.emplace_back(Star(font, 3));
                    stars[stars.size()-1].setPosition(sf::Vector2f(1*size,-1.42*size));
                    stars[stars.size()-1].setSentence("<3");

                    stars.emplace_back(Star(font, 3));
                    stars[stars.size()-1].setPosition(sf::Vector2f(-1*size,-1.42*size));
                    stars[stars.size()-1].setSentence("<3");

                    stars.emplace_back(Star(font, 4));
                    stars[stars.size()-1].setPosition(sf::Vector2f(2*size,-2.84*size));
                    stars[stars.size()-1].setSentence(": )");

                    stars.emplace_back(Star(font, 4));
                    stars[stars.size()-1].setPosition(sf::Vector2f(-2*size,-2.84*size));
                    stars[stars.size()-1].setSentence("<3");

                    stars.emplace_back(Star(font, 5));
                    stars[stars.size()-1].setPosition(sf::Vector2f(1.6*size,-3.9*size));
                    stars[stars.size()-1].setSentence(": )");

                    stars.emplace_back(Star(font, 3));
                    stars[stars.size()-1].setPosition(sf::Vector2f(-1.4*size,-3.9*size));
                    stars[stars.size()-1].setSentence("( :");

                    stars.emplace_back(Star(font, 6));
                    stars[stars.size()-1].setPosition(sf::Vector2f(0*size,-3.1*size));
                    stars[stars.size()-1].setSentence("<3");
                }
            }
            break;
        case State::Searching:
        {
            ////std::cout << "seraching the meaning of life" << moon.getPosition().x << "," <<moon.getPosition().y << std::endl;
            bool goToNextState = true;
            for(Star &s : stars){
               //// std::cout << "star -> " << s.getPosition().x << ";" << s.getPosition().y << std::endl;
                if(distance(moon.getPosition(), s.getPosition()) > window.getSize().y/2) goToNextState = false;
            }
            for(Star &s : stars){
                s.update(deltatime);
            }
            if(goToNextState){
                for(Star &s : stars){
                    s.setCanSpeak(true);
                }
                currentState = State::GroupChat;
            }

            break;
        }
        case State::GroupChat:
        {
            //std::cout << "groupchating (. Y .)" << std::endl;
            for(Star &s : stars){
                s.update(deltatime);
            }

            bool finished = true;
            for(Star &s : stars){
                if(!s.textBox.finished()) finished = false;
            }

            if(finished) {
                fadeOutValue = 0.0;
                currentState = State::fadeOut;
            }
            break;
        }
        case State::fadeOut:
            if(fadeOutValue <= 1){
                fadeOutValue += deltatime* 0.5;
                for(Star &s : stars){
                    s.setColor(sf::Color(255,255,255, 255-255*fadeOutValue));
                    s.sglow.setColor(sf::Color(255,255,255, 255-255*fadeOutValue));
                }
            }
            else {
                stars.clear();
                currentState = State::Idle;
            }
            break;
        default:
            break;
        }

        moon.update(deltatime, window);
		//Set view values
        sf::Vector2f viewPosition = view.getCenter();

        view.reset(sf::FloatRect(viewPosition.x, viewPosition.y,
                                 window.getSize().x, window.getSize().y));

        sf::Vector2f step;
        step.x = (viewPosition.x - moon.getPosition().x+10) *-0.1* deltatime;
        step.y = (viewPosition.y - moon.getPosition().y+10) *-0.1* deltatime;

        float maxDist = 20;
        float dist = distance(viewPosition, moon.getPosition());
        sf::Vector2f extra(0.f,0.f);
        if( dist > maxDist){
            extra.x = (viewPosition.x - moon.getPosition().x+10) *-1* deltatime;
            extra.y = (viewPosition.y - moon.getPosition().y+10) *-1* deltatime;
        }

        view.setCenter(viewPosition + step + extra);
        view.setViewport(sf::FloatRect(0,0,1.0f,1.0f));

/*
        view.reset(sf::FloatRect(moon.getPosition().x, moon.getPosition().y,
                                 window.getSize().x, window.getSize().y));

        viewPosition.y = moon.getPosition().y+10;
        viewPosition.x = moon.getPosition().x+10;
        view.setCenter(viewPosition);
        view.setViewport(sf::FloatRect(0,0,1.0f,1.0f));
*/

		//Set window view, draw and display
        window.setView(view);

        sf::Color c = sf::Color(0,0,0,0.1);
        window.clear(c);

        for(auto it = ministars.begin(); it != ministars.end();){
            if(std::abs(it->getPosition().x - moon.getPosition().x) > window.getSize().x
                    || std::abs(it->getPosition().y - moon.getPosition().y) > window.getSize().y
                    ) it = ministars.erase(it);
            else ++it;
        }

        const int maxStars = 50;
        if(ministars.size() < maxStars){
            for(int i = ministars.size(); i < maxStars; ++i){
                sf::Vector2f pos;
                pos.x = rand()%window.getSize().x;
                pos.x -= window.getSize().x/2;
                pos.y = rand()%window.getSize().y;
                pos.y -= window.getSize().y/2;
                sf::CircleShape c(1,4);
                c.setPosition(moon.getPosition() + pos);
                c.setFillColor(sf::Color(250,250,250,100));
                ministars.push_back(c);
            }
        }

        for(int i = 0; i < maxStars; ++i){
            window.draw(ministars[i]);
        }

        if(stars.size() > 0){
            float angle = getAngle(moon.getPosition(), stars[0].getPosition());
            //std::cout << "the angle is "<< angle << std::endl;
            sf::Vector2f guiaPos;
            guia.setFillColor(sf::Color(200,200,200,50));
            guiaPos.x = moon.getPosition().x + std::cos(angle*M_PI/180) * (moon.getRadius()*3 + guia.getRadius());
            guiaPos.y = moon.getPosition().y + std::sin(angle*M_PI/180) * (moon.getRadius()*3 + guia.getRadius());
            guia.setPosition(guiaPos);
            window.draw(guia);

            guia.setFillColor(sf::Color(0,0,0,255));
            guiaPos.x = moon.getPosition().x + std::cos(angle*M_PI/180) * (moon.getRadius()*3 );//+ guia.getRadius());
            guiaPos.y = moon.getPosition().y + std::sin(angle*M_PI/180) * (moon.getRadius()*3 );//+ guia.getRadius());
            guia.setPosition(guiaPos);
            window.draw(guia);

        }

        for(Star &s : stars){
            /*
            float dist = std::abs(distance(moon.getPosition(), s.getPosition()));
            if(dist < 2*moon.getGlobalBounds().width){
                float factor = dist/2.f*moon.getGlobalBounds().width;
                s.setColor(sf::Color(255,255,255,int(255*factor)));
            }else s.setColor(sf::Color(255,255,255,255));
            */
            s.render(window);
            //window.draw(s);
        }
        moon.render(window);
        window.display();

	}
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Sep 21, 2013
 *      Author: tomas
 */

#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <iostream> // TODO unused?
#include <math.h>       /* fabs */
#include <sys/time.h>
#include <unistd.h>
using namespace std;

#define GRID_SIZE 32 // TODO fix grid when odd number of cells
#define KEY_SPACE 32
#define RAND_SEED 1

const float HALF_GRID_SIZE = GRID_SIZE / 2;
const float CORNER_LENGTH = 1.0 / (float)HALF_GRID_SIZE;

int windowSizeH = 600;
int windowSizeV = 600;

bool shouldDrawUserLine = false;
bool shouldDrawBresenhamLine = false;
bool snapToGrid = true;
bool showHelp = false;

float mouseBeginX = 0;
float mouseBeginY = 0;
float mouseEndX = 0;
float mouseEndY = 0;

// TODO better titles
int gridBeginX = 0;
int gridBeginY = 0;
int gridEndX = 0;
int gridEndY = 0;

float userLineBeginX = 0;
float userLineBeginY = 0;
float userLineEndX = 0;
float userLineEndY = 0;

void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) {

	worldX = ((float)screenX / (float)windowSizeH) * 2 - 1;
	worldY = ((float)screenY / (float)windowSizeV) * -2 + 1;
}

void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){
	gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE );
	gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE );
}

void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY, bool cellCenter){

	worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1;
	worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1;

	if (cellCenter){
		worldX += (CORNER_LENGTH / 2);
		worldY -= (CORNER_LENGTH / 2);
	}

}

void colorGridCell(int x, int y) {

	float topLeftX;
	float topLeftY;

	transformGridToWorldCoordinates(x, y, topLeftX, topLeftY, false);

	glColor3f(0, 0.5, 0.5);

	glBegin(GL_QUADS);
		glVertex2f(topLeftX, topLeftY);
		glVertex2f(topLeftX + CORNER_LENGTH, topLeftY);

		glVertex2f(topLeftX + CORNER_LENGTH, topLeftY - CORNER_LENGTH);
		glVertex2f(topLeftX, topLeftY - CORNER_LENGTH);
	glEnd();

}

void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX,
		int gridEndY, bool useInts, bool draw) {

	bool isSteep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX);
	if (isSteep) {
		swap(gridBeginX, gridBeginY);
		swap(gridEndX, gridEndY);
	}

	if (gridBeginX > gridEndX) {
		swap(gridBeginX, gridEndX);
		swap(gridBeginY, gridEndY);
	}

	int deltaX = gridEndX - gridBeginX;
	int deltay = abs(gridEndY - gridBeginY);
	int currentY = gridBeginY;

	if (useInts) {
		int error = deltaX / 2;

		int yStep = 1;
		if (gridBeginY >= gridEndY) {
			yStep = -1;
		}

		for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) {

			if (draw) {
				if (isSteep) {
					colorGridCell(currentY, currentX);
				} else {
					colorGridCell(currentX, currentY);
				}
			}

			error = error - deltay;
			if (error < 0) {
				currentY = currentY + yStep;
				error = error + deltaX;
			}
		}
	} else {
		float error = 0;
		float deltaError = fabs((float) deltay / (float) deltaX);

		int yStep = 1;
		if (gridBeginY >= gridEndY) {
			yStep = -1;
		}

		for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) {
			if (draw) {
				if (isSteep) {
					colorGridCell(currentY, currentX);
				} else {
					colorGridCell(currentX, currentY);
				}
			}

			error = error + deltaError;
			if (error >= 0.5) {
				currentY = currentY + yStep;
				error = error - 1.0;
			}
		}

	}
}

void mouseClickCallback (int button, int state, int x, int y){

	if (button == GLUT_LEFT_BUTTON){

		if ((state == GLUT_DOWN)){
			transformScreenToWorldCoordinates(x, y, mouseBeginX, mouseBeginY);
			mouseEndX = mouseBeginX;
			mouseEndY = mouseBeginY;
			shouldDrawUserLine = true;

			transformWorldToGridCoordinates(mouseBeginX, mouseBeginY, gridBeginX, gridBeginY);
			gridEndX = gridBeginX;
			gridEndY = gridBeginY;
			shouldDrawBresenhamLine = true;
		}
//		else if (state == GLUT_UP) {
//			transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY);
//			transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY);
//
//		}
		glutPostRedisplay();
	}
}

void mouseDragCallback(int x, int y){

	transformScreenToWorldCoordinates(x, y, mouseEndX, mouseEndY);
	transformWorldToGridCoordinates(mouseEndX, mouseEndY, gridEndX, gridEndY);

	glutPostRedisplay();
}

void keyboardCallback(unsigned char key, int x, int y){

	switch (key) {

	case KEY_SPACE:

		showHelp = !showHelp;
		glutPostRedisplay();
		break;
	}

}

void drawUserLine(){

	if (snapToGrid) {
		transformGridToWorldCoordinates(gridBeginX, gridBeginY, userLineBeginX, userLineBeginY, true);
		transformGridToWorldCoordinates(gridEndX, gridEndY, userLineEndX, userLineEndY, true);
	} else {
		userLineBeginX = mouseBeginX;
		userLineBeginY = mouseBeginY;
		userLineEndX = mouseEndX;
		userLineEndY = mouseEndY;
	}

	glColor3f(1.0, 0.0, 0.0);

	glBegin(GL_LINES);
		glVertex2f(userLineBeginX, userLineBeginY);
		glVertex2f(userLineEndX, userLineEndY);
	glEnd();
}

void drawGrid(){

	glColor3f(0.5, 0.5, 0.5);

	glBegin(GL_LINES);
	for (int i = -HALF_GRID_SIZE; i <= HALF_GRID_SIZE; i++) {
		float xAndY = i / (float)(HALF_GRID_SIZE);
		glVertex2f(xAndY, -1.0);
		glVertex2f(xAndY, 1.0);

		glVertex2f(-1.0, xAndY);
		glVertex2f(1.0, xAndY);
	}
	glEnd();
}

//TODO do not forget to reset colors

void drawHelpOverlay(){

	glColor3f(0.1, 0.1, 0.1);

	glBegin(GL_QUADS);
		glVertex2f(-1.0, 1.0);
		glVertex2f(1.0, 1.0);

		glVertex2f(1.0, 0);
		glVertex2f(-1.0, 0);
	glEnd();

	glColor3f(1.0, 1.0, 1.0);
	glRasterPos2f(-0.9, 0.9);
}

void display(void) {

	glClear(GL_COLOR_BUFFER_BIT);

	if (shouldDrawBresenhamLine){
		drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY, false, true);
	}

	drawGrid();

	if (shouldDrawUserLine) {
		drawUserLine();
	}

	if (showHelp) {
		drawHelpOverlay();
	}

	glFlush();
}

int getRandomIntInRange(int min, int max) {
	return min + (rand() % (int)(max - min + 1)); // TODO review algorithm
	// TODO make random seed always the same
}

long getLineDrawingExecutionSpeedMicroseconds(bool useInts, long lineDraws){

	int min = 0;
	int max = GRID_SIZE - 1;

	int randBeginX;
	int randBeginY;
	int randEndX;
	int randEndY;

	srand(RAND_SEED);

	struct timeval start, end;

	gettimeofday(&start, NULL);

	for (long i = 0; i < lineDraws; i++) {
		randBeginX = getRandomIntInRange(min, max);
		randBeginY = getRandomIntInRange(min, max);
		randEndX = getRandomIntInRange(min, max);
		randEndY = getRandomIntInRange(min, max);

		drawBresenhamLine(randBeginX, randBeginY, randEndX, randEndY, useInts, false);

		//		cout << randBeginX << " " << randBeginX << " to " << randEndX << " " << randEndY << endl;
	}

	gettimeofday(&end, NULL);

	return end.tv_usec - start.tv_usec;
}

void testBresenhamLineAlgorithmExecutionSpeed(long numberOfCalls){

	long execTimeUsingInt   = getLineDrawingExecutionSpeedMicroseconds(true, numberOfCalls);
	long execTimeUsingFloat = getLineDrawingExecutionSpeedMicroseconds(false, numberOfCalls);

	cout << execTimeUsingInt << " " << execTimeUsingFloat << endl;
}

void init(void) {
}

int main(int argc, char *argv[]) {

//	testBresenhamLineAlgorithmExecutionSpeed(10000);
//	return 0;

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
	glutInitWindowSize(windowSizeH, windowSizeV);
	glutInitWindowPosition(100, 50);
	glutCreateWindow("Bresenham's line algorithm demo - press \"ENTER\" for help");
	init();
	glutDisplayFunc(display);

	glutMouseFunc(mouseClickCallback);
	glutMotionFunc(mouseDragCallback);
	glutKeyboardFunc(keyboardCallback);

	glutMainLoop();
	return 0;
}
<commit_msg>Refactoring. combined into structs.<commit_after>/*
 * main.cpp
 *
 *  Created on: Sep 21, 2013
 *      Author: tomas
 */

#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <iostream> // TODO unused?
#include <math.h>       /* fabs */
#include <sys/time.h>
#include <unistd.h>
using namespace std;

#define GRID_SIZE 32 // TODO fix grid when odd number of cells
#define USE_OPTIMIZED_LINE_ALG true
#define KEY_SPACE 32
#define RAND_SEED 1

const float HALF_GRID_SIZE = GRID_SIZE / 2;
const float CORNER_LENGTH = 1.0 / (float)HALF_GRID_SIZE;

struct pointF2 {
  float x;
  float y;
};

struct pointInt2 {
  int x;
  int y;
};

struct lineF2 {
	pointF2 begin, end;
};

struct lineInt2 {
	pointInt2 begin, end;
};

int windowSizeH = 600;
int windowSizeV = 600;

bool shouldDrawUserLine = false;
bool shouldDrawBresenhamLine = false;
bool snapToGrid = true;
bool showHelp = false;

lineF2 mouseLine;
lineF2 userLine;
lineInt2 approxLine;

void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) {

	worldX = ((float)screenX / (float)windowSizeH) * 2 - 1;
	worldY = ((float)screenY / (float)windowSizeV) * -2 + 1;
}

void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){
	gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE );
	gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE );
}

void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY, bool cellCenter){

	worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1;
	worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1;

	if (cellCenter){
		worldX += (CORNER_LENGTH / 2);
		worldY -= (CORNER_LENGTH / 2);
	}

}

void colorGridCell(int x, int y) {

	float topLeftX;
	float topLeftY;

	transformGridToWorldCoordinates(x, y, topLeftX, topLeftY, false);

	glColor3f(0, 0.5, 0.5);

	glBegin(GL_QUADS);
		glVertex2f(topLeftX, topLeftY);
		glVertex2f(topLeftX + CORNER_LENGTH, topLeftY);

		glVertex2f(topLeftX + CORNER_LENGTH, topLeftY - CORNER_LENGTH);
		glVertex2f(topLeftX, topLeftY - CORNER_LENGTH);
	glEnd();

}

void drawBresenhamLine(int lineBeginX, int lineBeginY, int lineEndX,
		int lineEndY, bool useInts, bool draw) {

	bool isSteep = abs(lineEndY - lineBeginY) > abs(lineEndX - lineBeginX);
	if (isSteep) {
		swap(lineBeginX, lineBeginY);
		swap(lineEndX, lineEndY);
	}

	if (lineBeginX > lineEndX) {
		swap(lineBeginX, lineEndX);
		swap(lineBeginY, lineEndY);
	}

	int deltaX = lineEndX - lineBeginX;
	int deltay = abs(lineEndY - lineBeginY);
	int currentY = lineBeginY;

	if (useInts) {
		int error = deltaX / 2;

		int yStep = 1;
		if (lineBeginY >= lineEndY) {
			yStep = -1;
		}

		for (int currentX = lineBeginX; currentX <= lineEndX; currentX++) {

			if (draw) {
				if (isSteep) {
					colorGridCell(currentY, currentX);
				} else {
					colorGridCell(currentX, currentY);
				}
			}

			error = error - deltay;
			if (error < 0) {
				currentY = currentY + yStep;
				error = error + deltaX;
			}
		}
	} else {
		float error = 0;
		float deltaError = fabs((float) deltay / (float) deltaX);

		int yStep = 1;
		if (lineBeginY >= lineEndY) {
			yStep = -1;
		}

		for (int currentX = lineBeginX; currentX <= lineEndX; currentX++) {
			if (draw) {
				if (isSteep) {
					colorGridCell(currentY, currentX);
				} else {
					colorGridCell(currentX, currentY);
				}
			}

			error = error + deltaError;
			if (error >= 0.5) {
				currentY = currentY + yStep;
				error = error - 1.0;
			}
		}

	}
}

void mouseClickCallback (int button, int state, int x, int y){

	if (button == GLUT_LEFT_BUTTON){

		if ((state == GLUT_DOWN)){
			transformScreenToWorldCoordinates(x, y, mouseLine.begin.x, mouseLine.begin.y);
			mouseLine.end.x = mouseLine.begin.x;
			mouseLine.end.y = mouseLine.begin.y;
			shouldDrawUserLine = true;

			transformWorldToGridCoordinates(mouseLine.begin.x, mouseLine.begin.y, approxLine.begin.x, approxLine.begin.y);
			approxLine.end.x = approxLine.begin.x;
			approxLine.end.y = approxLine.begin.y;
			shouldDrawBresenhamLine = true;
		}
//		else if (state == GLUT_UP) {
//			transformWorldToGridCoordinates(beginX, beginY, approxLine.begin.x, approxLine.begin.y);
//			transformWorldToGridCoordinates(endX, endY, approxLine.end.x, approxLine.end.y);
//
//		}
		glutPostRedisplay();
	}
}

void mouseDragCallback(int x, int y){

	transformScreenToWorldCoordinates(x, y, mouseLine.end.x, mouseLine.end.y);
	transformWorldToGridCoordinates(mouseLine.end.x, mouseLine.end.y, approxLine.end.x, approxLine.end.y);

	glutPostRedisplay();
}

void keyboardCallback(unsigned char key, int x, int y){

	switch (key) {

	case KEY_SPACE:

		showHelp = !showHelp;
		glutPostRedisplay();
		break;
	}

}

void drawUserLine(){

	if (snapToGrid) {
		transformGridToWorldCoordinates(approxLine.begin.x, approxLine.begin.y, userLine.begin.x, userLine.begin.y, true);
		transformGridToWorldCoordinates(approxLine.end.x, approxLine.end.y, userLine.end.x, userLine.end.y, true);
	} else {
		userLine.begin.x = mouseLine.begin.x;
		userLine.begin.y = mouseLine.begin.x;
		userLine.end.x = mouseLine.end.x;
		userLine.end.y = mouseLine.end.y;
	}

	glColor3f(1.0, 0.0, 0.0);

	glBegin(GL_LINES);
		glVertex2f(userLine.begin.x, userLine.begin.y);
		glVertex2f(userLine.end.x, userLine.end.y);
	glEnd();
}

void drawGrid(){

	glColor3f(0.5, 0.5, 0.5);

	glBegin(GL_LINES);
	for (int i = -HALF_GRID_SIZE; i <= HALF_GRID_SIZE; i++) {
		float xAndY = i / (float)(HALF_GRID_SIZE);
		glVertex2f(xAndY, -1.0);
		glVertex2f(xAndY, 1.0);

		glVertex2f(-1.0, xAndY);
		glVertex2f(1.0, xAndY);
	}
	glEnd();
}

//TODO do not forget to reset colors

void drawHelpOverlay(){

	glColor3f(0.1, 0.1, 0.1);

	glBegin(GL_QUADS);
		glVertex2f(-1.0, 1.0);
		glVertex2f(1.0, 1.0);

		glVertex2f(1.0, 0);
		glVertex2f(-1.0, 0);
	glEnd();

	glColor3f(1.0, 1.0, 1.0);
	glRasterPos2f(-0.9, 0.9);
}

void display(void) {

	glClear(GL_COLOR_BUFFER_BIT);

	if (shouldDrawBresenhamLine){
		drawBresenhamLine(approxLine.begin.x, approxLine.begin.y, approxLine.end.x, approxLine.end.y, USE_OPTIMIZED_LINE_ALG, true);
	}

	drawGrid();

	if (shouldDrawUserLine) {
		drawUserLine();
	}

	if (showHelp) {
		drawHelpOverlay();
	}

	glFlush();
}

int getRandomIntInRange(int min, int max) {
	return min + (rand() % (int)(max - min + 1)); // TODO review algorithm
	// TODO make random seed always the same
}

long getLineDrawingExecutionSpeedMicroseconds(bool useInts, long lineDraws){

	int min = 0;
	int max = GRID_SIZE - 1;

	int randBeginX;
	int randBeginY;
	int randEndX;
	int randEndY;

	srand(RAND_SEED);

	struct timeval start, end;

	gettimeofday(&start, NULL);

	for (long i = 0; i < lineDraws; i++) {
		randBeginX = getRandomIntInRange(min, max);
		randBeginY = getRandomIntInRange(min, max);
		randEndX = getRandomIntInRange(min, max);
		randEndY = getRandomIntInRange(min, max);

		drawBresenhamLine(randBeginX, randBeginY, randEndX, randEndY, useInts, false);

		//		cout << randBeginX << " " << randBeginX << " to " << randEndX << " " << randEndY << endl;
	}

	gettimeofday(&end, NULL);

	return end.tv_usec - start.tv_usec;
}

void testBresenhamLineAlgorithmExecutionSpeed(long numberOfCalls){

	long execTimeUsingInt   = getLineDrawingExecutionSpeedMicroseconds(true, numberOfCalls);
	long execTimeUsingFloat = getLineDrawingExecutionSpeedMicroseconds(false, numberOfCalls);

	cout << execTimeUsingInt << " " << execTimeUsingFloat << endl;
}

void init(void) {
}

int main(int argc, char *argv[]) {

//	testBresenhamLineAlgorithmExecutionSpeed(10000);
//	return 0;

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
	glutInitWindowSize(windowSizeH, windowSizeV);
	glutInitWindowPosition(100, 50);
	glutCreateWindow("Bresenham's line algorithm demo - press \"ENTER\" for help");
	init();
	glutDisplayFunc(display);

	glutMouseFunc(mouseClickCallback);
	glutMotionFunc(mouseDragCallback);
	glutKeyboardFunc(keyboardCallback);

	glutMainLoop();
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <boost/asio.hpp>

using namespace boost::asio::ip;
using namespace std;

int main(int argc, char** argv) {
  if(argc != 3) {
    cerr << "Usage: halfwit <server> <channel>\n";
    return 1;
  }
  try {
    boost::asio::io_service io_service;
    tcp::resolver resolver(io_service);
    tcp::resolver::query query (argv[1], "6667");

    cout << "resolving " << argv[1] << endl;
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;
    cout << "connecting...";
    tcp::socket socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    while(error && endpoint_iterator != end) {
      socket.close();
      socket.connect(*endpoint_iterator++, error);
    }
    if(error)
      throw boost::system::system_error(error);
    cout << "connected!\n";

    socket.write_some("USER halfwit . . :halfwitbot", error);
    socket.write_some("NICK halfwit", error);

    for(;;) {
      vector<char> buf(128);
      socket.read_some(boost::asio::buffer(buf), error);
      if(error == boost::asio::error::eof)
        break;
      else if(error)
        throw boost::system::system_error(error);
      for(auto i: buf)
        cout << i;
    }
  }
  catch(std::exception &e) {
    cerr << "error: " << e.what() << endl;
  }
}
<commit_msg>respond to PING, send nick info<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <boost/asio.hpp>

using namespace boost::asio::ip;
using namespace std;

int main(int argc, char** argv) {
  if(argc != 3) {
    cerr << "Usage: halfwit <server> <channel>\n";
    return 1;
  }
  try {
    boost::asio::io_service io_service;
    tcp::resolver resolver(io_service);
    tcp::resolver::query query (argv[1], "6667");

    cout << "resolving " << argv[1] << endl;
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;
    cout << "connecting...";
    tcp::socket socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    while(error && endpoint_iterator != end) {
      socket.close();
      socket.connect(*endpoint_iterator++, error);
    }
    if(error)
      throw boost::system::system_error(error);
    cout << "connected!\n";

    string user_msg = "USER halfwitbot myhost server :halfwitbot\n";
    string nick_msg = "NICK halfwitbot\n";
    string join_msg = "JOIN #" + string(argv[2]) + "\n";
    socket.write_some(boost::asio::buffer(user_msg), error);
    socket.write_some(boost::asio::buffer(nick_msg), error);
    socket.write_some(boost::asio::buffer(join_msg), error);

    if(error)
      throw boost::system::system_error(error);

    for(;;) {
      vector<char> buf(128);
      socket.read_some(boost::asio::buffer(buf), error);
      if(error == boost::asio::error::eof)
        break;
      else if(error)
        throw boost::system::system_error(error);

      string first_four(buf.begin(), buf.begin() + 4);
      if(first_four.compare("PING") == 0) {
        string pong_msg = string("PONG") + string(buf.begin() + 4, buf.end());
        socket.write_some(boost::asio::buffer(pong_msg), error);
        if(error)
          throw boost::system::system_error(error);
      }

      for(auto i: buf)
        cout << i;
    }
  }
  catch(std::exception &e) {
    cerr << "error: " << e.what() << endl;
  }
}
<|endoftext|>


<commit_before>/*
 * Fixture class runs benchmark by a given Functor and test data from FFTFixtureData.
 *
 */
#ifndef FIXTURE_BENCHMARK_HPP_
#define FIXTURE_BENCHMARK_HPP_

#include "fixture_data.hpp"

#include <stdlib.h>
#include <math.h>
#include <type_traits>
#include <boost/test/unit_test.hpp>

namespace gearshifft
{
  /*
fftkind, precision, dimkind, dim, nx, ny, nz, run, AllocBuffer (bytes), AllocPlan (bytes), {times}, time-unit
"Inplace Complex", float, 1, 3, 63,67,65, 0, ..., ..., ..., ms
   */

  template<typename T_Precision,
           typename T_Application >
  struct FixtureBenchmark
  {
    using ResultT = typename T_Application::ResultT;
    static constexpr int NR_RUNS = T_Application::NR_RUNS;
    static constexpr double ERROR_BOUND = T_Application::ERROR_BOUND;

    /**
     * Benchmark body with 1 warmup and NR_RUNS repetitions of iFFT(FFT()) implementation.
     * Implementation is given with TFunctor.
     * Depending on TFunctor::InputIsReal it uses RealType or ComplexType test data.
     * Statistics will be printed after the runs.
     * FFT output will be normalized and compared to original input, which is kept stored in FFTFixtureData.
     * Is called from auto test case function in fixture_test_suite.
     */
    template<typename T_Functor, bool NormalizeResult, size_t T_NDim=3>
    void benchmark(const std::array<unsigned, T_NDim>& extents) {
      using VectorT = std::conditional_t<T_Functor::IsComplex,
                                         typename FixtureData<T_Precision,T_NDim>::ComplexVector,
                                         typename FixtureData<T_Precision,T_NDim>::RealVector>;

      static_assert(T_NDim<=3,"T_NDim<=3");

      auto data_set = FixtureData<T_Precision,T_NDim>::getInstancePtr(extents);
      VectorT* data_buffer_p = new VectorT;
      VectorT& data_buffer = *data_buffer_p; // @todo check: workaround, stack ctor fails
      data_set->copyTo(data_buffer);
      assert(data_buffer.data());

      auto fft = T_Functor();
      ResultT result;
      result.template init<T_Functor::IsComplex,
                           T_Functor::IsInplace,
                           T_NDim>(extents);
      try {
        // warmup
        fft(result, data_buffer, extents);
        for(int r=0; r<NR_RUNS; ++r)
        {
          result.setRun(r);
          data_set->copyTo(data_buffer);
          fft(result, data_buffer, extents);
        }
      } catch(const std::runtime_error& e) {
        delete data_buffer_p;
        BOOST_FAIL( e.what() );
      }
      auto deviation = data_set->template check_deviation<NormalizeResult>(data_buffer);
      const double error_bound = ERROR_BOUND;
      BOOST_CHECK_LE( deviation, error_bound );

      T_Application::getInstance().addRecord(result);

      delete data_buffer_p;
    }
  };

} // gearshifft

#endif /* FIXTURE_BENCHMARK_HPP_ */
<commit_msg>degrading use of std::conditional_t to std::conditional to be C++11 compliant<commit_after>/*
 * Fixture class runs benchmark by a given Functor and test data from FFTFixtureData.
 *
 */
#ifndef FIXTURE_BENCHMARK_HPP_
#define FIXTURE_BENCHMARK_HPP_

#include "fixture_data.hpp"

#include <stdlib.h>
#include <math.h>
#include <type_traits>
#include <boost/test/unit_test.hpp>

namespace gearshifft
{
  /*
fftkind, precision, dimkind, dim, nx, ny, nz, run, AllocBuffer (bytes), AllocPlan (bytes), {times}, time-unit
"Inplace Complex", float, 1, 3, 63,67,65, 0, ..., ..., ..., ms
   */

  template<typename T_Precision,
           typename T_Application >
  struct FixtureBenchmark
  {
    using ResultT = typename T_Application::ResultT;
    static constexpr int NR_RUNS = T_Application::NR_RUNS;
    static constexpr double ERROR_BOUND = T_Application::ERROR_BOUND;

    /**
     * Benchmark body with 1 warmup and NR_RUNS repetitions of iFFT(FFT()) implementation.
     * Implementation is given with TFunctor.
     * Depending on TFunctor::InputIsReal it uses RealType or ComplexType test data.
     * Statistics will be printed after the runs.
     * FFT output will be normalized and compared to original input, which is kept stored in FFTFixtureData.
     * Is called from auto test case function in fixture_test_suite.
     */
    template<typename T_Functor, bool NormalizeResult, size_t T_NDim=3>
    void benchmark(const std::array<unsigned, T_NDim>& extents) {
      using VectorT = typename std::conditional<T_Functor::IsComplex,
						typename FixtureData<T_Precision,T_NDim>::ComplexVector,
						typename FixtureData<T_Precision,T_NDim>::RealVector>::type;

      static_assert(T_NDim<=3,"T_NDim<=3");

      auto data_set = FixtureData<T_Precision,T_NDim>::getInstancePtr(extents);
      VectorT* data_buffer_p = new VectorT;
      VectorT& data_buffer = *data_buffer_p; // @todo check: workaround, stack ctor fails
      data_set->copyTo(data_buffer);
      assert(data_buffer.data());

      auto fft = T_Functor();
      ResultT result;
      result.template init<T_Functor::IsComplex,
                           T_Functor::IsInplace,
                           T_NDim>(extents);
      try {
        // warmup
        fft(result, data_buffer, extents);
        for(int r=0; r<NR_RUNS; ++r)
        {
          result.setRun(r);
          data_set->copyTo(data_buffer);
          fft(result, data_buffer, extents);
        }
      } catch(const std::runtime_error& e) {
        delete data_buffer_p;
        BOOST_FAIL( e.what() );
      }
      auto deviation = data_set->template check_deviation<NormalizeResult>(data_buffer);
      const double error_bound = ERROR_BOUND;
      BOOST_CHECK_LE( deviation, error_bound );

      T_Application::getInstance().addRecord(result);

      delete data_buffer_p;
    }
  };

} // gearshifft

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


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "ut_mscenewindow.h"

#include <MDismissEvent>
#include <MScene>
#include <MSceneManager>
#include <MApplicationWindow>
#include <MWindow>
#include <MComponentData>

class MyMDismissEventFilter : public QObject
{
public:
    MyMDismissEventFilter() : QObject(0) {
        count = 0;
    }

    bool eventFilter(QObject *watched, QEvent *event) {
        Q_UNUSED(watched)
        if (event->type() == MDismissEvent::eventType()) {
            count++;
        }
        return false;
    }

    int count;
};

// Test class implementation

void Ut_MSceneWindow::init()
{
    m_subject = new MSceneWindow;
}

void Ut_MSceneWindow::cleanup()
{
    delete m_subject;
    m_subject = 0;
}

void Ut_MSceneWindow::initTestCase()
{
    if(MComponentData::instance() == 0) {
        static int argc = 1;
        static char *argv[ 1 ];
        argv[ 0 ] = (char*)"./ut_mwindow";
        m_componentData = MComponentData::createInstance(argc, argv);
    }
    window = new MWindow(new MSceneManager);

    qRegisterMetaType<MSceneWindow::SceneWindowState>("MSceneWindow::SceneWindowState");
}

void Ut_MSceneWindow::cleanupTestCase()
{
    delete window;
    window = 0;
}

void Ut_MSceneWindow::testAccessors()
{
    m_subject->setManagedManually(true);

    QCOMPARE(m_subject->windowType(), MSceneWindow::PlainSceneWindow);
    QCOMPARE(m_subject->isManagedManually(), true);
}

void Ut_MSceneWindow::testAppearOnWindow()
{
    m_subject->appear(window);

    QCOMPARE(m_subject->sceneManager(), window->sceneManager());
    QVERIFY(m_subject->scene() == static_cast<QGraphicsScene *>(window->scene()));
}

void Ut_MSceneWindow::testAppearOnScene()
{
    m_subject->appear(window->scene());

    QCOMPARE(m_subject->sceneManager(), window->sceneManager());
    QVERIFY(m_subject->scene() == static_cast<QGraphicsScene *>(window->scene()));
}

/*
 * Appearing on a MWindow without a scene manager should just work.
 * Scene manager should be created on the fly.
 */
void Ut_MSceneWindow::testAppearWithoutSceneManager()
{
    window->setSceneManager(0);

    m_subject->appear(window);

    QVERIFY(m_subject->sceneManager() == window->sceneManager());
    QVERIFY(m_subject->scene() == static_cast<QGraphicsScene *>(window->scene()));
}

void Ut_MSceneWindow::testDismiss()
{
    MyMDismissEventFilter dismissEventFilter;
    m_subject->installEventFilter(&dismissEventFilter);

    window->sceneManager()->appearSceneWindowNow(m_subject);

    QSignalSpy spyWindowAppeared(m_subject, SIGNAL(appeared()));
    QSignalSpy spyWindowDisappeared(m_subject, SIGNAL(disappeared()));

    window->sceneManager()->dismissSceneWindowNow(m_subject);

    QCOMPARE(spyWindowAppeared.count(), 0);
    QCOMPARE(spyWindowDisappeared.count(), 1);
    // QCOMPARE(dismissEventFilter.count, 1); FIXME: Dismiss events are disabled in 0.18 due to ABI freeze
}

void Ut_MSceneWindow::testDestroyWhenDoneCallingDisappear()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDone);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->disappearSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 1);

    m_subject = 0;
}

void Ut_MSceneWindow::testDestroyWhenDoneCallingDismiss()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDone);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->dismissSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 1);

    m_subject = 0;
}

void Ut_MSceneWindow::testDestroyWhenDismissedCallingDisappear()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDismissed);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->disappearSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 0);
}

void Ut_MSceneWindow::testDestroyWhenDismissedCallingDismiss()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDismissed);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->dismissSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 1);

    m_subject = 0;
}

void Ut_MSceneWindow::testDismissedStateReset()
{
    window->sceneManager()->appearSceneWindowNow(m_subject);
    window->sceneManager()->dismissSceneWindowNow(m_subject);

    // internal "dismissed" state should be reset to false on next reappearance
    // Therefore the disappearance below should not cause self-destruction

    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDismissed);
    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));
    window->sceneManager()->disappearSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 0);
}

void Ut_MSceneWindow::testSceneWindowStateChanges()
{
    QSignalSpy spyDisappeared(m_subject, SIGNAL(disappeared()));
    QSignalSpy spyAppearing(m_subject, SIGNAL(appearing()));
    QSignalSpy spyAppeared(m_subject, SIGNAL(appeared()));
    QSignalSpy spyDisappearing(m_subject, SIGNAL(disappearing()));
    QSignalSpy spySceneWindowStateChanged(m_subject,
            SIGNAL(sceneWindowStateChanged(MSceneWindow::SceneWindowState,
                    MSceneWindow::SceneWindowState)));
    TestBridge testBridge;

    testBridge.setObjectName("_m_testBridge");
    testBridge.setParent(m_subject);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);

    testBridge.setSceneWindowState(MSceneWindow::Appearing);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Appearing);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 1);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 0);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Appearing,
                                         MSceneWindow::Disappeared));
    spyAppearing.clear();

    testBridge.setSceneWindowState(MSceneWindow::Appeared);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Appeared);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 1);
    QCOMPARE(spyDisappearing.count(), 0);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Appeared,
                                         MSceneWindow::Appearing));
    spyAppeared.clear();

    testBridge.setSceneWindowState(MSceneWindow::Disappearing);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappearing);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 1);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Disappearing,
                                         MSceneWindow::Appeared));
    spyDisappearing.clear();

    testBridge.setSceneWindowState(MSceneWindow::Disappeared);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);
    QCOMPARE(spyDisappeared.count(), 1);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 0);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Disappeared,
                                         MSceneWindow::Disappearing));
    spyDisappeared.clear();
}

void Ut_MSceneWindow::testSettingSameSceneWindowState()
{
    QSignalSpy spyDisappeared(m_subject, SIGNAL(disappeared()));
    QSignalSpy spyAppearing(m_subject, SIGNAL(appearing()));
    QSignalSpy spyAppeared(m_subject, SIGNAL(appeared()));
    QSignalSpy spyDisappearing(m_subject, SIGNAL(disappearing()));
    QSignalSpy spySceneWindowStateChanged(m_subject,
            SIGNAL(sceneWindowStateChanged(MSceneWindow::SceneWindowState,
                    MSceneWindow::SceneWindowState)));
    TestBridge testBridge;

    testBridge.setObjectName("_m_testBridge");
    testBridge.setParent(m_subject);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);

    testBridge.setSceneWindowState(MSceneWindow::Disappeared);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 0);
    QCOMPARE(spySceneWindowStateChanged.count(), 0);

}

void Ut_MSceneWindow::testFocusHandlingOnWindowBlocking()
{
    window->show();
    QTest::qWaitForWindowShown(window);

    m_subject->appear(window->scene());
    QGraphicsWidget *widget = new QGraphicsWidget(m_subject);
    widget->setFlag(QGraphicsItem::ItemIsFocusable);
    widget->setFocus();

    QVERIFY(widget->hasFocus());

    qApp->sendEvent(m_subject, new QEvent(QEvent::WindowBlocked));

    QVERIFY(!widget->hasFocus());

    qApp->sendEvent(m_subject, new QEvent(QEvent::WindowUnblocked));

    QVERIFY(widget->hasFocus());

    window->hide();
    qApp->processEvents();
}

void Ut_MSceneWindow::processPendingEvents()
{
    // Send the posted QEvent::DeferredDelete from deleteLater().
    QCoreApplication::sendPostedEvents();

    // Quit when there are no more pending events (like DeferredDelete)
    QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit()));

    QCoreApplication::instance()->exec();
}

bool Ut_MSceneWindow::verifySceneWindowStateChange(QSignalSpy &spy,
        MSceneWindow::SceneWindowState expectedNewState,
        MSceneWindow::SceneWindowState expectedOldState)
{
    if (spy.count() != 1) {
        qWarning() << "sceneWindowStateChanged(). Signal emitted" << spy.count()
            << "times. Expected 1";
        return false;
    }

    QList<QVariant> arguments = spy.takeFirst();

    if (arguments.count() != 2) {
        qFatal("Did not connect to the proper signal");
        return false;
    }

    MSceneWindow::SceneWindowState actualNewState =
        arguments.at(0).value<MSceneWindow::SceneWindowState>();

    MSceneWindow::SceneWindowState actualOldState =
        arguments.at(1).value<MSceneWindow::SceneWindowState>();

    if (actualNewState != expectedNewState) {
        qWarning() << "sceneWindowStateChanged(). newState: Expected" << expectedNewState
            << "got" << actualNewState;
        return false;
    }

    if (actualOldState != expectedOldState) {
        qWarning() << "sceneWindowStateChanged(). oldState: Expected" << expectedOldState
            << "got" << actualNewState;
        return false;
    }

    return true;
}

TestBridge::TestBridge(QObject *parent)
    : QObject(parent)
{
}

void TestBridge::setSceneWindowState(MSceneWindow::SceneWindowState newState)
{
    QObject *testInterface = children()[0];

    QMetaObject::invokeMethod(testInterface, "setSceneWindowState",
            Qt::DirectConnection,
            Q_ARG(MSceneWindow::SceneWindowState, newState));
}

QTEST_MAIN(Ut_MSceneWindow)
<commit_msg>Fixes: Ut_MSceneWindow::testFocusHandlingOnWindowBlocking is not reliable.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "ut_mscenewindow.h"

#include <MDismissEvent>
#include <MScene>
#include <MSceneManager>
#include <MApplicationWindow>
#include <MWindow>
#include <MComponentData>

class MyMDismissEventFilter : public QObject
{
public:
    MyMDismissEventFilter() : QObject(0) {
        count = 0;
    }

    bool eventFilter(QObject *watched, QEvent *event) {
        Q_UNUSED(watched)
        if (event->type() == MDismissEvent::eventType()) {
            count++;
        }
        return false;
    }

    int count;
};

// Test class implementation

void Ut_MSceneWindow::init()
{
    m_subject = new MSceneWindow;
}

void Ut_MSceneWindow::cleanup()
{
    delete m_subject;
    m_subject = 0;
}

void Ut_MSceneWindow::initTestCase()
{
    if(MComponentData::instance() == 0) {
        static int argc = 1;
        static char *argv[ 1 ];
        argv[ 0 ] = (char*)"./ut_mwindow";
        m_componentData = MComponentData::createInstance(argc, argv);
    }
    window = new MWindow(new MSceneManager);

    qRegisterMetaType<MSceneWindow::SceneWindowState>("MSceneWindow::SceneWindowState");
}

void Ut_MSceneWindow::cleanupTestCase()
{
    delete window;
    window = 0;
}

void Ut_MSceneWindow::testAccessors()
{
    m_subject->setManagedManually(true);

    QCOMPARE(m_subject->windowType(), MSceneWindow::PlainSceneWindow);
    QCOMPARE(m_subject->isManagedManually(), true);
}

void Ut_MSceneWindow::testAppearOnWindow()
{
    m_subject->appear(window);

    QCOMPARE(m_subject->sceneManager(), window->sceneManager());
    QVERIFY(m_subject->scene() == static_cast<QGraphicsScene *>(window->scene()));
}

void Ut_MSceneWindow::testAppearOnScene()
{
    m_subject->appear(window->scene());

    QCOMPARE(m_subject->sceneManager(), window->sceneManager());
    QVERIFY(m_subject->scene() == static_cast<QGraphicsScene *>(window->scene()));
}

/*
 * Appearing on a MWindow without a scene manager should just work.
 * Scene manager should be created on the fly.
 */
void Ut_MSceneWindow::testAppearWithoutSceneManager()
{
    window->setSceneManager(0);

    m_subject->appear(window);

    QVERIFY(m_subject->sceneManager() == window->sceneManager());
    QVERIFY(m_subject->scene() == static_cast<QGraphicsScene *>(window->scene()));
}

void Ut_MSceneWindow::testDismiss()
{
    MyMDismissEventFilter dismissEventFilter;
    m_subject->installEventFilter(&dismissEventFilter);

    window->sceneManager()->appearSceneWindowNow(m_subject);

    QSignalSpy spyWindowAppeared(m_subject, SIGNAL(appeared()));
    QSignalSpy spyWindowDisappeared(m_subject, SIGNAL(disappeared()));

    window->sceneManager()->dismissSceneWindowNow(m_subject);

    QCOMPARE(spyWindowAppeared.count(), 0);
    QCOMPARE(spyWindowDisappeared.count(), 1);
    // QCOMPARE(dismissEventFilter.count, 1); FIXME: Dismiss events are disabled in 0.18 due to ABI freeze
}

void Ut_MSceneWindow::testDestroyWhenDoneCallingDisappear()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDone);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->disappearSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 1);

    m_subject = 0;
}

void Ut_MSceneWindow::testDestroyWhenDoneCallingDismiss()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDone);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->dismissSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 1);

    m_subject = 0;
}

void Ut_MSceneWindow::testDestroyWhenDismissedCallingDisappear()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDismissed);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->disappearSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 0);
}

void Ut_MSceneWindow::testDestroyWhenDismissedCallingDismiss()
{
    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDismissed);

    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));

    window->sceneManager()->dismissSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 1);

    m_subject = 0;
}

void Ut_MSceneWindow::testDismissedStateReset()
{
    window->sceneManager()->appearSceneWindowNow(m_subject);
    window->sceneManager()->dismissSceneWindowNow(m_subject);

    // internal "dismissed" state should be reset to false on next reappearance
    // Therefore the disappearance below should not cause self-destruction

    window->sceneManager()->appearSceneWindowNow(m_subject, MSceneWindow::DestroyWhenDismissed);
    QSignalSpy spyDestroyed(m_subject, SIGNAL(destroyed()));
    window->sceneManager()->disappearSceneWindowNow(m_subject);

    processPendingEvents();

    QCOMPARE(spyDestroyed.count(), 0);
}

void Ut_MSceneWindow::testSceneWindowStateChanges()
{
    QSignalSpy spyDisappeared(m_subject, SIGNAL(disappeared()));
    QSignalSpy spyAppearing(m_subject, SIGNAL(appearing()));
    QSignalSpy spyAppeared(m_subject, SIGNAL(appeared()));
    QSignalSpy spyDisappearing(m_subject, SIGNAL(disappearing()));
    QSignalSpy spySceneWindowStateChanged(m_subject,
            SIGNAL(sceneWindowStateChanged(MSceneWindow::SceneWindowState,
                    MSceneWindow::SceneWindowState)));
    TestBridge testBridge;

    testBridge.setObjectName("_m_testBridge");
    testBridge.setParent(m_subject);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);

    testBridge.setSceneWindowState(MSceneWindow::Appearing);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Appearing);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 1);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 0);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Appearing,
                                         MSceneWindow::Disappeared));
    spyAppearing.clear();

    testBridge.setSceneWindowState(MSceneWindow::Appeared);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Appeared);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 1);
    QCOMPARE(spyDisappearing.count(), 0);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Appeared,
                                         MSceneWindow::Appearing));
    spyAppeared.clear();

    testBridge.setSceneWindowState(MSceneWindow::Disappearing);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappearing);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 1);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Disappearing,
                                         MSceneWindow::Appeared));
    spyDisappearing.clear();

    testBridge.setSceneWindowState(MSceneWindow::Disappeared);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);
    QCOMPARE(spyDisappeared.count(), 1);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 0);
    QVERIFY(verifySceneWindowStateChange(spySceneWindowStateChanged,
                                         MSceneWindow::Disappeared,
                                         MSceneWindow::Disappearing));
    spyDisappeared.clear();
}

void Ut_MSceneWindow::testSettingSameSceneWindowState()
{
    QSignalSpy spyDisappeared(m_subject, SIGNAL(disappeared()));
    QSignalSpy spyAppearing(m_subject, SIGNAL(appearing()));
    QSignalSpy spyAppeared(m_subject, SIGNAL(appeared()));
    QSignalSpy spyDisappearing(m_subject, SIGNAL(disappearing()));
    QSignalSpy spySceneWindowStateChanged(m_subject,
            SIGNAL(sceneWindowStateChanged(MSceneWindow::SceneWindowState,
                    MSceneWindow::SceneWindowState)));
    TestBridge testBridge;

    testBridge.setObjectName("_m_testBridge");
    testBridge.setParent(m_subject);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);

    testBridge.setSceneWindowState(MSceneWindow::Disappeared);

    QCOMPARE(m_subject->sceneWindowState(), MSceneWindow::Disappeared);
    QCOMPARE(spyDisappeared.count(), 0);
    QCOMPARE(spyAppearing.count(), 0);
    QCOMPARE(spyAppeared.count(), 0);
    QCOMPARE(spyDisappearing.count(), 0);
    QCOMPARE(spySceneWindowStateChanged.count(), 0);

}

void Ut_MSceneWindow::testFocusHandlingOnWindowBlocking()
{
    window->show();
    QTest::qWaitForWindowShown(window);

    m_subject->appear(window->scene());
    QGraphicsWidget *widget = new QGraphicsWidget(m_subject);
    widget->setFlag(QGraphicsItem::ItemIsFocusable);
    widget->setFocus();

    if (!window->scene()->isActive())
        QSKIP("The scene is not active, focus will not be set...", SkipAll);

    QVERIFY(widget->hasFocus());

    qApp->sendEvent(m_subject, new QEvent(QEvent::WindowBlocked));

    QVERIFY(!widget->hasFocus());

    qApp->sendEvent(m_subject, new QEvent(QEvent::WindowUnblocked));

    QVERIFY(widget->hasFocus());

    window->hide();
    qApp->processEvents();
}

void Ut_MSceneWindow::processPendingEvents()
{
    // Send the posted QEvent::DeferredDelete from deleteLater().
    QCoreApplication::sendPostedEvents();

    // Quit when there are no more pending events (like DeferredDelete)
    QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit()));

    QCoreApplication::instance()->exec();
}

bool Ut_MSceneWindow::verifySceneWindowStateChange(QSignalSpy &spy,
        MSceneWindow::SceneWindowState expectedNewState,
        MSceneWindow::SceneWindowState expectedOldState)
{
    if (spy.count() != 1) {
        qWarning() << "sceneWindowStateChanged(). Signal emitted" << spy.count()
            << "times. Expected 1";
        return false;
    }

    QList<QVariant> arguments = spy.takeFirst();

    if (arguments.count() != 2) {
        qFatal("Did not connect to the proper signal");
        return false;
    }

    MSceneWindow::SceneWindowState actualNewState =
        arguments.at(0).value<MSceneWindow::SceneWindowState>();

    MSceneWindow::SceneWindowState actualOldState =
        arguments.at(1).value<MSceneWindow::SceneWindowState>();

    if (actualNewState != expectedNewState) {
        qWarning() << "sceneWindowStateChanged(). newState: Expected" << expectedNewState
            << "got" << actualNewState;
        return false;
    }

    if (actualOldState != expectedOldState) {
        qWarning() << "sceneWindowStateChanged(). oldState: Expected" << expectedOldState
            << "got" << actualNewState;
        return false;
    }

    return true;
}

TestBridge::TestBridge(QObject *parent)
    : QObject(parent)
{
}

void TestBridge::setSceneWindowState(MSceneWindow::SceneWindowState newState)
{
    QObject *testInterface = children()[0];

    QMetaObject::invokeMethod(testInterface, "setSceneWindowState",
            Qt::DirectConnection,
            Q_ARG(MSceneWindow::SceneWindowState, newState));
}

QTEST_MAIN(Ut_MSceneWindow)
<|endoftext|>