<commit_before>#include "gui.h"
/**
 * @brief MainWindow::MainWindow : ventana principal para logearse, registrarse y ver competencias
 *
 * @param guiP : objeto gui que hace de mediador y sirve para pasar el control
 * una vez que se quiera ir a otra ventana
 *
 * @param parent : objeto tipo ventana padre que sirve como retorno, asi lo
 * implementa Qt
 */
MainWindow::MainWindow(GUI* guiP, QWidget *parent):
    QMainWindow(parent), gui(guiP), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QPixmap pix(":/images/Heros128.png");
    ui->label_logo->setPixmap(pix);

    this->setWindowTitle("Sistema deportivo Pegaso");
    this->setWindowIcon(pix);

    // validador del email
    EmailValidator* emailValidator = new EmailValidator(this);
    ui->lineEdit->setValidator(emailValidator);

    // validador de la contraseña
    QRegExp password("[a-zA-Z0-9.-]*");
    QValidator* passwordValidator = new QRegExpValidator(password,this);
    ui->lineEdit_2->setValidator(passwordValidator);

    // contraseña seteada para que no se vea al escribir
    ui->lineEdit_2->setEchoMode(QLineEdit::Password);
//    ui->pushButton_3->hide();
//    ui->pushButton->hide();

//    this->setGeometry(0,0,350,100);

}
/**
 * @brief GUI::GUI : Mediador que controla interacion de interfaz grafica
 * y gestores de la capa logica.
 *
 * @param gestorDBP
 * @param gestorCompetenciasP
 * @param gestorLugaresP
 * @param gestorPartidosP
 * @param gestorUsuariosP
 * @param deportesP
 * @param paisesP
 * @param estadosP
 * @param modalidadesP
 *
 */
GUI::GUI(QApplication *appP, GestorBaseDatos *gestorDBP, GestorCompetencias *gestorCompetenciasP, GestorLugares *gestorLugaresP,
         GestorPartidos *gestorPartidosP, GestorUsuarios *gestorUsuariosP, QVector<Deporte *> deportesP,
         QVector<Pais *> paisesP, QVector<Estado *> estadosP, QVector<TipoModalidad *> modalidadesP):
    gestorDB(gestorDBP), gestorCompetencias(gestorCompetenciasP), gestorLugares(gestorLugaresP),
    gestorPartidos(gestorPartidosP), gestorUsuarios(gestorUsuariosP), deportes(deportesP),
    paises(paisesP), estados(estadosP), modalidades(modalidadesP), app(appP)
{}

MainWindow::~MainWindow()
{
    delete ui;
}
/**
 * @brief MainWindow::on_pushButton_2_clicked
 * @details boton de login extrae toda la informacion de la ui, la verifica
 * y la envia al gestor correspondiente para luego efectuar el cambio de ventana o no
 */
void MainWindow::on_pushButton_2_clicked()
{
    // La contraseña no puede ser menor a 6 caracteres
    // si no se cumple directamente no se verifica
    // no se avisa nada al respecto
    if(ui->lineEdit_2->text().size() > 0 && ui->lineEdit->text().size() > 0 && ui->lineEdit->hasAcceptableInput() ){
        // se encripta la contraseña a penas se pide por seguridad
        QByteArray passwordHash = QCryptographicHash::hash(QByteArray::fromStdString(ui->lineEdit_2->text().toStdString()),QCryptographicHash::Sha256);

        // obtenemos el mail de la ui
        QString email = ui->lineEdit->text();

        gui->handleMain(this,QString("pantallaUsuario"),email,passwordHash);
    }
    else{
        QMessageBox* msg = new QMessageBox(this);
        msg->setText("Complete correctamente los campos por favor");
        QPixmap icono(":/images/Heros-amarillo-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->exec();
    }
}

/**
 * @brief MainWindow::on_pushButton_4_clicked
 * @details boton de cierre de la ventana principal
 */
void MainWindow::on_pushButton_4_clicked()
{
    this->close();
    gui->close();
}

/**
 * @brief GUI::handleMain:
 *      Handle para manejar los posibles eventos de la ventana principal
 * @param a : ventana padre a la posible ventana a instaciar
 * @param b : opcion para el handle
 * @param email : email para pedir el usuario
 * @param pass : contraseña encriptada para loggear usuario
 */
void GUI::handleMain(QMainWindow* a, QString b, QString email, QByteArray pass)
{
    if (b == "pantallaUsuario")
    {
        if(gestorUsuarios->login(email,pass) != NULL){

            pantalla_usuario* p = new pantalla_usuario(this,a);
            a->close();
            p->show();
        }
        else{
            // mensaje de error
            QMessageBox* msg = new QMessageBox(a);
            msg->setText("Nombre o contraseña incorrecta");
            QPixmap icono(":/images/Heros-rojo-64.png");
            msg->setIconPixmap(icono);
            msg->setModal(true);
            msg->exec();
        }

    }
    else if (b == "registrarUsuario")
    {

        registrar_usuario * ru = new registrar_usuario(this,paises,a);
        ru->setModal(true);
        ru->show();
    }

}

void GUI::handlePantallaUsuario(QDialog *a, QString b)
{
    if (b == "listarCompetencias"){

        listar_competencias* l = new listar_competencias(this,deportes,estados,modalidades,a);
        a->close();
        l->show();
    }
    else if(b == "cerrar")
    {
           MainWindow * m = new MainWindow(this);
           m->show();
           a->close();
    }
}

void GUI::handleListarCompetencias(QDialog *a, QString b, Competencia *comp)
{
    if (b == "altaCompetencia")
    {
        Usuario* user = gestorUsuarios->getActual();

        QVector<Lugar*> lugares = gestorLugares->getLugares();

        QVector<TipoResultado*> resultados = gestorCompetencias->getTiposResultado();
        alta_competencia * al = new alta_competencia(this,deportes,lugares,modalidades, resultados, a);
        al->setModal(true);
        al->show();

    }
    else if (b == "verCompetencia")
    {
        Competencia * c = gestorCompetencias->getCompetenciaFull(comp->getId());
        ver_competencia * v = new ver_competencia(this,c,a);
        v->setModal(true);
        v->show();
    }
    else if(b == "cerrar")
    {
            pantalla_usuario* p = new pantalla_usuario(this);
            p->show();
            a->close();
    }
}

void GUI::handleAltaCompetencia(QDialog *a, QString b, QString nombreComp, Deporte* dep,
                                QVector<Lugar *> lugs, QVector<int> disps, Modalidad* mod,
                                QString reglamento)
{
    if (b == "crearCompetencia")
    {
        bool op;
        QString error;
        Usuario* user = gestorUsuarios->getActual();

        DtoCompetencia* dtoC = new DtoCompetencia(user,nombreComp,dep,lugs,disps,mod,reglamento);
        if(gestorCompetencias->crearCompetencia(dtoC,op,error) != NULL){

            QMessageBox* msg = new QMessageBox(a);
            msg->setText("Competencia creada correctamente");
            QPixmap icono(":/images/Heros-verde-64.png");
            msg->setIconPixmap(icono);
            msg->setModal(true);
            msg->exec();
        }
        else{
            // QMessageBox fracaso
            QMessageBox* msg = new QMessageBox(a);
            QString error1 = "Error al crear la competencia. \n" + error;
            msg->setText(error1);
            QPixmap icono(":/images/Heros-rojo-64.png");
            msg->setIconPixmap(icono);
            msg->setModal(true);
            msg->exec();
        }
        a->close();

    }
}

bool GUI::handleVerCompetencia(ver_competencia *a, QString b, QString &error, Competencia* comp)
{
    competenciaActual = comp;
    if (b == "modificarCompetencia")
    {
        /* code */
    }
    else if (b == "generarFixture")
    {
        bool retorno = gestorCompetencias->generarFixture(comp,error);
        competenciaActual = comp;
        return retorno;
    }
    else if (b == "bajaCompetencia")
    {
        /* code */
    }
    else if (b == "mostrarFixture")
    {
        //comp = gestorCompetencias->getCompetenciaFull(comp->getId());
        //competenciaActual = comp;
        mostrar_fixture* mf = new mostrar_fixture(this,comp,a,a);
        mf->setModal(true);
        mf->show();
    }
    else if (b == "mostrarTablasPosiciones")
    {
        GeneradorExcel* genExcel = new GeneradorExcel();
        generadorReporte* genRep = new generadorReporte();
        tabla_posiciones* t = new tabla_posiciones(this,comp,a,genExcel,genRep);
        t->setModal(true);
        t->show();
    }
    else if (b == "listarParticipantes"){

        participantes = comp->getParticipantes();
        listar_participante * lp = new listar_participante(this,comp, a);
        lp->setModal(true);
        lp->show();
    }
    return false;
}

bool GUI::handleMostrarFixture(mostrar_fixture *a, QString b,Partido* partido)
{
    if (b == "gestionarFixture")
    {
        gestionar_fixture* gf = new gestionar_fixture(competenciaActual,a,partido,this,a);
        gf->setModal(true);
        gf->show();
        return true;
    }
}

void GUI::handleGestionarFixture(QDialog *a, QString b, mostrar_fixture* mf, Partido *partP, Resultado *resP)
{
    gestorCompetencias->nuevoResultado(competenciaActual,partP,resP);

    //competenciaActual = gestorCompetencias->getCompetenciaFull(competenciaActual->getId());

    QMessageBox* msg = new QMessageBox(a);
    msg->setText("Partido cargado correctamente");
    QPixmap icono(":/images/Heros-verde-64.png");
    msg->setIconPixmap(icono);
    msg->setModal(true);
    msg->exec();
    a->close();

    mf->actualizarTabla();
}

QVector<Competencia*> GUI::handleFiltrarCompetencias(QStringList data)
{
    QString nombreComp, deporte, estado, tipoModalidad;

    Usuario*  usuario   =   gestorUsuarios->getActual();

    nombreComp          =   data[0];
    deporte             =   data[1];
    estado              =   data[2];
    tipoModalidad       =   data[3];

    Estado* e = this->buscarEstado(estado);

    Deporte* d = this->buscarDeporte(deporte);

    TipoModalidad* tm = this->buscarTipoModalidad(tipoModalidad);

    DtoGetCompetencia* datos = new DtoGetCompetencia(usuario,nombreComp,d,tm,e);
    return gestorCompetencias->getCompetenciasLazy(datos);

}

QString GUI::handleRegistrarUsuario(DtoUsuario *datos)
{
    QString error;
    gestorUsuarios->altaUsuario(datos,error);
    return error;
}

QVector<Deporte *> GUI::getDeportes() const
{
    return deportes;
}

void GUI::setDeportes(const QVector<Deporte *> &value)
{
    deportes = value;
}

QVector<Provincia *> GUI::getProvincias(Pais *paisP)
{
    return gestorUsuarios->getProvincias(paisP);
}

QVector<Localidad *> GUI::getLocalidades(Provincia *provinciaP)
{
    return gestorUsuarios->getLocalidades(provinciaP);
}

Competencia* GUI::handleAltaParticipante(QDialog *a, QString nombre, QString email, QString ImgUrl)
{
    DtoParticipante* datos = new DtoParticipante(nombre,email,ImgUrl);
    QString error;
    if(gestorCompetencias->altaParticipante(competenciaActual,datos,error)){
        QMessageBox* msg = new QMessageBox(a);
        msg->setText(error);
        QPixmap icono(":/images/Heros-verde-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->exec();
        return competenciaActual;
    }
    else{
        QMessageBox* msg = new QMessageBox(a);
        msg->setText(error);
        QPixmap icono(":/images/Heros-rojo-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->exec();
        Competencia* aux;
        return aux;
    }

}
Estado *GUI::buscarEstado(QString estado)
{
    for (int i = 0; i < estados.size(); ++i) {
        if(estado.toLower() == estados[i]->getNombre().toLower())
            return estados[i];
    }
    return NULL;
}

Deporte *GUI::buscarDeporte(QString deporte)
{
    for (int i = 0; i < deportes.size(); ++i) {
        if(deporte.toLower()==deportes[i]->getNombre().toLower())
            return deportes[i];
    }
    return NULL;
}

TipoModalidad *GUI::buscarTipoModalidad(QString tipoMod)
{
    for (int i = 0; i < modalidades.size(); ++i) {
        if(tipoMod.toLower() == modalidades[i]->getNombre().toLower())
            return modalidades[i];
    }
    return NULL;
}

void GUI::show()
{
    MainWindow * m = new MainWindow(this);
    m->show();
}

void GUI::close()
{
//    app->setQuitOnLastWindowClosed(true);
    app->quit();
}

void MainWindow::on_pushButton_clicked()
{
    gui->handleMain(this,QString("registrarUsuario"));
}

EmailValidator::EmailValidator(QObject *parent) :
    QValidator(parent),
      m_validMailRegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}"),
      m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[a-z]*"){}

QValidator::State EmailValidator::validate(QString &text, int &pos) const
{
    Q_UNUSED(pos)

    fixup(text);

    if (m_validMailRegExp.exactMatch(text))
        return Acceptable;

    if (m_intermediateMailRegExp.exactMatch(text))
        return Intermediate;

    return Invalid;
}

void EmailValidator::fixup(QString &text) const
{
    text = text.trimmed().toLower();
}
<commit_msg>Corregido bug al cargar un participante con el mismo nombre/correo<commit_after>#include "gui.h"
/**
 * @brief MainWindow::MainWindow : ventana principal para logearse, registrarse y ver competencias
 *
 * @param guiP : objeto gui que hace de mediador y sirve para pasar el control
 * una vez que se quiera ir a otra ventana
 *
 * @param parent : objeto tipo ventana padre que sirve como retorno, asi lo
 * implementa Qt
 */
MainWindow::MainWindow(GUI* guiP, QWidget *parent):
    QMainWindow(parent), gui(guiP), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QPixmap pix(":/images/Heros128.png");
    ui->label_logo->setPixmap(pix);

    this->setWindowTitle("Sistema deportivo Pegaso");
    this->setWindowIcon(pix);

    // validador del email
    EmailValidator* emailValidator = new EmailValidator(this);
    ui->lineEdit->setValidator(emailValidator);

    // validador de la contraseña
    QRegExp password("[a-zA-Z0-9.-]*");
    QValidator* passwordValidator = new QRegExpValidator(password,this);
    ui->lineEdit_2->setValidator(passwordValidator);

    // contraseña seteada para que no se vea al escribir
    ui->lineEdit_2->setEchoMode(QLineEdit::Password);
//    ui->pushButton_3->hide();
//    ui->pushButton->hide();

//    this->setGeometry(0,0,350,100);

}
/**
 * @brief GUI::GUI : Mediador que controla interacion de interfaz grafica
 * y gestores de la capa logica.
 *
 * @param gestorDBP
 * @param gestorCompetenciasP
 * @param gestorLugaresP
 * @param gestorPartidosP
 * @param gestorUsuariosP
 * @param deportesP
 * @param paisesP
 * @param estadosP
 * @param modalidadesP
 *
 */
GUI::GUI(QApplication *appP, GestorBaseDatos *gestorDBP, GestorCompetencias *gestorCompetenciasP, GestorLugares *gestorLugaresP,
         GestorPartidos *gestorPartidosP, GestorUsuarios *gestorUsuariosP, QVector<Deporte *> deportesP,
         QVector<Pais *> paisesP, QVector<Estado *> estadosP, QVector<TipoModalidad *> modalidadesP):
    gestorDB(gestorDBP), gestorCompetencias(gestorCompetenciasP), gestorLugares(gestorLugaresP),
    gestorPartidos(gestorPartidosP), gestorUsuarios(gestorUsuariosP), deportes(deportesP),
    paises(paisesP), estados(estadosP), modalidades(modalidadesP), app(appP)
{}

MainWindow::~MainWindow()
{
    delete ui;
}
/**
 * @brief MainWindow::on_pushButton_2_clicked
 * @details boton de login extrae toda la informacion de la ui, la verifica
 * y la envia al gestor correspondiente para luego efectuar el cambio de ventana o no
 */
void MainWindow::on_pushButton_2_clicked()
{
    // La contraseña no puede ser menor a 6 caracteres
    // si no se cumple directamente no se verifica
    // no se avisa nada al respecto
    if(ui->lineEdit_2->text().size() > 0 && ui->lineEdit->text().size() > 0 && ui->lineEdit->hasAcceptableInput() ){
        // se encripta la contraseña a penas se pide por seguridad
        QByteArray passwordHash = QCryptographicHash::hash(QByteArray::fromStdString(ui->lineEdit_2->text().toStdString()),QCryptographicHash::Sha256);

        // obtenemos el mail de la ui
        QString email = ui->lineEdit->text();

        gui->handleMain(this,QString("pantallaUsuario"),email,passwordHash);
    }
    else{
        QMessageBox* msg = new QMessageBox(this);
        msg->setText("Complete correctamente los campos por favor");
        QPixmap icono(":/images/Heros-amarillo-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->exec();
    }
}

/**
 * @brief MainWindow::on_pushButton_4_clicked
 * @details boton de cierre de la ventana principal
 */
void MainWindow::on_pushButton_4_clicked()
{
    this->close();
    gui->close();
}

/**
 * @brief GUI::handleMain:
 *      Handle para manejar los posibles eventos de la ventana principal
 * @param a : ventana padre a la posible ventana a instaciar
 * @param b : opcion para el handle
 * @param email : email para pedir el usuario
 * @param pass : contraseña encriptada para loggear usuario
 */
void GUI::handleMain(QMainWindow* a, QString b, QString email, QByteArray pass)
{
    if (b == "pantallaUsuario")
    {
        if(gestorUsuarios->login(email,pass) != NULL){

            pantalla_usuario* p = new pantalla_usuario(this,a);
            a->close();
            p->show();
        }
        else{
            // mensaje de error
            QMessageBox* msg = new QMessageBox(a);
            msg->setText("Nombre o contraseña incorrecta");
            QPixmap icono(":/images/Heros-rojo-64.png");
            msg->setIconPixmap(icono);
            msg->setModal(true);
            msg->exec();
        }

    }
    else if (b == "registrarUsuario")
    {

        registrar_usuario * ru = new registrar_usuario(this,paises,a);
        ru->setModal(true);
        ru->show();
    }

}

void GUI::handlePantallaUsuario(QDialog *a, QString b)
{
    if (b == "listarCompetencias"){

        listar_competencias* l = new listar_competencias(this,deportes,estados,modalidades,a);
        a->close();
        l->show();
    }
    else if(b == "cerrar")
    {
           MainWindow * m = new MainWindow(this);
           m->show();
           a->close();
    }
}

void GUI::handleListarCompetencias(QDialog *a, QString b, Competencia *comp)
{
    if (b == "altaCompetencia")
    {
        Usuario* user = gestorUsuarios->getActual();

        QVector<Lugar*> lugares = gestorLugares->getLugares();

        QVector<TipoResultado*> resultados = gestorCompetencias->getTiposResultado();
        alta_competencia * al = new alta_competencia(this,deportes,lugares,modalidades, resultados, a);
        al->setModal(true);
        al->show();

    }
    else if (b == "verCompetencia")
    {
        Competencia * c = gestorCompetencias->getCompetenciaFull(comp->getId());
        ver_competencia * v = new ver_competencia(this,c,a);
        v->setModal(true);
        v->show();
    }
    else if(b == "cerrar")
    {
            pantalla_usuario* p = new pantalla_usuario(this);
            p->show();
            a->close();
    }
}

void GUI::handleAltaCompetencia(QDialog *a, QString b, QString nombreComp, Deporte* dep,
                                QVector<Lugar *> lugs, QVector<int> disps, Modalidad* mod,
                                QString reglamento)
{
    if (b == "crearCompetencia")
    {
        bool op;
        QString error;
        Usuario* user = gestorUsuarios->getActual();

        DtoCompetencia* dtoC = new DtoCompetencia(user,nombreComp,dep,lugs,disps,mod,reglamento);
        if(gestorCompetencias->crearCompetencia(dtoC,op,error) != NULL){

            QMessageBox* msg = new QMessageBox(a);
            msg->setText("Competencia creada correctamente");
            QPixmap icono(":/images/Heros-verde-64.png");
            msg->setIconPixmap(icono);
            msg->setModal(true);
            msg->exec();
            a->close();
        }
        else{
            // QMessageBox fracaso
            QMessageBox* msg = new QMessageBox(a);
            QString error1 = "Error al crear la competencia. \n" + error;
            msg->setText(error1);
            QPixmap icono(":/images/Heros-rojo-64.png");
            msg->setIconPixmap(icono);
            msg->setModal(true);
            msg->exec();
        }

    }
}

bool GUI::handleVerCompetencia(ver_competencia *a, QString b, QString &error, Competencia* comp)
{
    competenciaActual = comp;
    if (b == "modificarCompetencia")
    {
        /* code */
    }
    else if (b == "generarFixture")
    {
        bool retorno = gestorCompetencias->generarFixture(comp,error);
        competenciaActual = comp;
        return retorno;
    }
    else if (b == "bajaCompetencia")
    {
        /* code */
    }
    else if (b == "mostrarFixture")
    {
        //comp = gestorCompetencias->getCompetenciaFull(comp->getId());
        //competenciaActual = comp;
        mostrar_fixture* mf = new mostrar_fixture(this,comp,a,a);
        mf->setModal(true);
        mf->show();
    }
    else if (b == "mostrarTablasPosiciones")
    {
        GeneradorExcel* genExcel = new GeneradorExcel();
        generadorReporte* genRep = new generadorReporte();
        tabla_posiciones* t = new tabla_posiciones(this,comp,a,genExcel,genRep);
        t->setModal(true);
        t->show();
    }
    else if (b == "listarParticipantes"){

        participantes = comp->getParticipantes();
        listar_participante * lp = new listar_participante(this,comp, a);
        lp->setModal(true);
        lp->show();
    }
    return false;
}

bool GUI::handleMostrarFixture(mostrar_fixture *a, QString b,Partido* partido)
{
    if (b == "gestionarFixture")
    {
        gestionar_fixture* gf = new gestionar_fixture(competenciaActual,a,partido,this,a);
        gf->setModal(true);
        gf->show();
        return true;
    }
}

void GUI::handleGestionarFixture(QDialog *a, QString b, mostrar_fixture* mf, Partido *partP, Resultado *resP)
{
    gestorCompetencias->nuevoResultado(competenciaActual,partP,resP);

    //competenciaActual = gestorCompetencias->getCompetenciaFull(competenciaActual->getId());

    QMessageBox* msg = new QMessageBox(a);
    msg->setText("Partido cargado correctamente");
    QPixmap icono(":/images/Heros-verde-64.png");
    msg->setIconPixmap(icono);
    msg->setModal(true);
    msg->exec();
    a->close();

    mf->actualizarTabla();
}

QVector<Competencia*> GUI::handleFiltrarCompetencias(QStringList data)
{
    QString nombreComp, deporte, estado, tipoModalidad;

    Usuario*  usuario   =   gestorUsuarios->getActual();

    nombreComp          =   data[0];
    deporte             =   data[1];
    estado              =   data[2];
    tipoModalidad       =   data[3];

    Estado* e = this->buscarEstado(estado);

    Deporte* d = this->buscarDeporte(deporte);

    TipoModalidad* tm = this->buscarTipoModalidad(tipoModalidad);

    DtoGetCompetencia* datos = new DtoGetCompetencia(usuario,nombreComp,d,tm,e);
    return gestorCompetencias->getCompetenciasLazy(datos);

}

QString GUI::handleRegistrarUsuario(DtoUsuario *datos)
{
    QString error;
    gestorUsuarios->altaUsuario(datos,error);
    return error;
}

QVector<Deporte *> GUI::getDeportes() const
{
    return deportes;
}

void GUI::setDeportes(const QVector<Deporte *> &value)
{
    deportes = value;
}

QVector<Provincia *> GUI::getProvincias(Pais *paisP)
{
    return gestorUsuarios->getProvincias(paisP);
}

QVector<Localidad *> GUI::getLocalidades(Provincia *provinciaP)
{
    return gestorUsuarios->getLocalidades(provinciaP);
}

Competencia* GUI::handleAltaParticipante(QDialog *a, QString nombre, QString email, QString ImgUrl)
{
    DtoParticipante* datos = new DtoParticipante(nombre,email,ImgUrl);
    QString error;
    if(gestorCompetencias->altaParticipante(competenciaActual,datos,error)){
        QMessageBox* msg = new QMessageBox(a);
        msg->setText(error);
        QPixmap icono(":/images/Heros-verde-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->exec();
        return competenciaActual;
    }
    else{
        QMessageBox* msg = new QMessageBox(a);
        msg->setText(error);
        QPixmap icono(":/images/Heros-rojo-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->exec();
        return competenciaActual;
    }

}
Estado *GUI::buscarEstado(QString estado)
{
    for (int i = 0; i < estados.size(); ++i) {
        if(estado.toLower() == estados[i]->getNombre().toLower())
            return estados[i];
    }
    return NULL;
}

Deporte *GUI::buscarDeporte(QString deporte)
{
    for (int i = 0; i < deportes.size(); ++i) {
        if(deporte.toLower()==deportes[i]->getNombre().toLower())
            return deportes[i];
    }
    return NULL;
}

TipoModalidad *GUI::buscarTipoModalidad(QString tipoMod)
{
    for (int i = 0; i < modalidades.size(); ++i) {
        if(tipoMod.toLower() == modalidades[i]->getNombre().toLower())
            return modalidades[i];
    }
    return NULL;
}

void GUI::show()
{
    MainWindow * m = new MainWindow(this);
    m->show();
}

void GUI::close()
{
//    app->setQuitOnLastWindowClosed(true);
    app->quit();
}

void MainWindow::on_pushButton_clicked()
{
    gui->handleMain(this,QString("registrarUsuario"));
}

EmailValidator::EmailValidator(QObject *parent) :
    QValidator(parent),
      m_validMailRegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}"),
      m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[a-z]*"){}

QValidator::State EmailValidator::validate(QString &text, int &pos) const
{
    Q_UNUSED(pos)

    fixup(text);

    if (m_validMailRegExp.exactMatch(text))
        return Acceptable;

    if (m_intermediateMailRegExp.exactMatch(text))
        return Intermediate;

    return Invalid;
}

void EmailValidator::fixup(QString &text) const
{
    text = text.trimmed().toLower();
}
<|endoftext|>


<commit_before>//
// LocalProjection.cpp
//
// This library has a concept "current projection" which is represented
// by the vtLocalProjection class.
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "vtdata/MathTypes.h"
#include "vtdata/Projections.h"
#include "LocalProjection.h"

//
// The global current projection is stored here.
//
vtLocalProjection g_Proj;

//
// Earth's diameter: 12756 km
// approximate circumference: 40074 km
// each degree of latitude: 111.3 km
//
#define earth_radius	6378000.0f		// in meters
#define meters_per_latitude	111300.0f

vtLocalProjection::vtLocalProjection() : vtProjection()
{
	m_fVerticalScale = WORLD_SCALE;
}

void vtLocalProjection::SetDegreeOrigin(const DPoint2 &degrees)
{
	m_EarthOrigin = degrees;

	// estimate meters per degree of longitude, using the terrain origin
	double r0, circ;

	r0 = earth_radius * cos(degrees.y / 180.0 * PI);
	circ = 2.0 * r0 * PI;
	m_fMetersPerLongitude = (float) (circ / 360.0);
}

void vtLocalProjection::SetMeterOrigin(const DPoint2 &meters)
{
	m_EarthOrigin = meters;
}

void vtLocalProjection::SetVerticalScale(float scale)
{
	m_fVerticalScale = scale;
}

void vtLocalProjection::convert_latlon_to_local_xz(float lat, float lon,
												   float &x, float &z)
{
	if (IsGeographic())
	{
		x = (float) ((lon - m_EarthOrigin.x) * m_fMetersPerLongitude * WORLD_SCALE);
		z = (float) -((lat - m_EarthOrigin.y) * meters_per_latitude * WORLD_SCALE);
	}
	// TODO: what if not geographic?
}

void vtLocalProjection::convert_latlon_to_local_xz(double lat, double lon,
												   float &x, float &z)
{
	convert_latlon_to_local_xz((float) lat, (float) lon, x, z);
}

void vtLocalProjection::convert_utm_to_xy(float utm_x, float utm_y,
										  float &x, float &y)
{
	x = (float) (utm_x - m_EarthOrigin.x);
	y = (float) (utm_y - m_EarthOrigin.y);
}

void vtLocalProjection::convert_utm_to_xy(double utm_x, double utm_y,
										  float &x, float &y)
{
	x = (float) (utm_x - m_EarthOrigin.x);
	y = (float) (utm_y - m_EarthOrigin.y);
}

void vtLocalProjection::convert_utm_to_local_xz(float utm_x, float utm_y,
												float &x, float &z)
{
	x = (float) (utm_x - m_EarthOrigin.x) * WORLD_SCALE;
	z = (float) -(utm_y - m_EarthOrigin.y) * WORLD_SCALE;
}

void vtLocalProjection::convert_utm_to_local_xz(double utm_x, double utm_y,
												float &x, float &z)
{
	x = (float) (utm_x - m_EarthOrigin.x) * WORLD_SCALE;
	z = (float) -(utm_y - m_EarthOrigin.y) * WORLD_SCALE;
}

void vtLocalProjection::convert_utm_vector_to_local_xz(float utm_x,
													   float utm_y, float &x, float &z)
{
	x = (float) (utm_x * WORLD_SCALE);
	z = (float) -(utm_y * WORLD_SCALE);
}

void vtLocalProjection::convert_local_xz_to_utm(float x, float z,
												float &utm_x, float &utm_y)
{
	utm_x = (float) (x / WORLD_SCALE + m_EarthOrigin.x);
	utm_y = (float) -(z / WORLD_SCALE + m_EarthOrigin.y);
}

void vtLocalProjection::convert_local_xz_to_utm(float x, float z,
												double &utm_x, double &utm_y)
{
	utm_x = (x / WORLD_SCALE + m_EarthOrigin.x);
	utm_y = (-z / WORLD_SCALE + m_EarthOrigin.y);
}

void vtLocalProjection::convert_local_xz_to_latlon(float x, float z,
												   double &lat, double &lon)
{
	lon = m_EarthOrigin.x + (x / m_fMetersPerLongitude / WORLD_SCALE);
	lat = m_EarthOrigin.y + (-z / meters_per_latitude / WORLD_SCALE);
}

//
// Convert from the coordinate system of the virtual world (x,y,z) to actual
// earth coodinates (map coordinates, altitude in meters)
//
void vtLocalProjection::ConvertToEarth(const FPoint3 &world, DPoint3 &earth)
{
	if (IsGeographic())
		convert_local_xz_to_latlon(world.x, world.z, earth.y, earth.x);
	else
		convert_local_xz_to_utm(world.x, world.z, earth.x, earth.y);
	earth.z = world.y / m_fVerticalScale;
}

void vtLocalProjection::ConvertFromEarth(const DPoint3 &earth, FPoint3 &world)
{
	if (IsGeographic())
		convert_latlon_to_local_xz(earth.y, earth.x, world.x, world.y);
	else
		convert_utm_to_local_xz(earth.x, earth.y, world.x, world.z);
	world.y = (float) (earth.z * m_fVerticalScale);
}

void vtLocalProjection::ConvertToEarth(float x, float z, DPoint2 &earth)
{
	if (IsGeographic())
		convert_local_xz_to_latlon(x, z, earth.y, earth.x);
	else
		convert_local_xz_to_utm(x, z, earth.x, earth.y);
}

void vtLocalProjection::ConvertFromEarth(const DPoint2 &earth, float &x, float &z)
{
	if (IsGeographic())
		convert_latlon_to_local_xz(earth.y, earth.x, x, z);
	else
		convert_utm_to_local_xz(earth.x, earth.y, x, z);
}

<commit_msg>use EstimateDegreesToMeters<commit_after>//
// LocalProjection.cpp
//
// This library has a concept "current projection" which is represented
// by the vtLocalProjection class.
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "vtdata/MathTypes.h"
#include "vtdata/Projections.h"
#include "LocalProjection.h"

//
// The global current projection for the current terrain is stored here.
//
vtLocalProjection g_Proj;

vtLocalProjection::vtLocalProjection() : vtProjection()
{
	m_fVerticalScale = WORLD_SCALE;
}

void vtLocalProjection::SetDegreeOrigin(const DPoint2 &degrees)
{
	m_EarthOrigin = degrees;

	// estimate meters per degree of longitude, using the terrain origin
	m_fMetersPerLongitude = EstimateDegreesToMeters(degrees.y);
}

void vtLocalProjection::SetMeterOrigin(const DPoint2 &meters)
{
	m_EarthOrigin = meters;
}

void vtLocalProjection::SetVerticalScale(float scale)
{
	m_fVerticalScale = scale;
}

void vtLocalProjection::convert_latlon_to_local_xz(float lat, float lon,
												   float &x, float &z)
{
	if (IsGeographic())
	{
		x = (float) ((lon - m_EarthOrigin.x) * m_fMetersPerLongitude * WORLD_SCALE);
		z = (float) -((lat - m_EarthOrigin.y) * METERS_PER_LATITUDE * WORLD_SCALE);
	}
	// TODO: what if not geographic?
}

void vtLocalProjection::convert_latlon_to_local_xz(double lat, double lon,
												   float &x, float &z)
{
	convert_latlon_to_local_xz((float) lat, (float) lon, x, z);
}

void vtLocalProjection::convert_utm_to_xy(float utm_x, float utm_y,
										  float &x, float &y)
{
	x = (float) (utm_x - m_EarthOrigin.x);
	y = (float) (utm_y - m_EarthOrigin.y);
}

void vtLocalProjection::convert_utm_to_xy(double utm_x, double utm_y,
										  float &x, float &y)
{
	x = (float) (utm_x - m_EarthOrigin.x);
	y = (float) (utm_y - m_EarthOrigin.y);
}

void vtLocalProjection::convert_utm_to_local_xz(float utm_x, float utm_y,
												float &x, float &z)
{
	x = (float) (utm_x - m_EarthOrigin.x) * WORLD_SCALE;
	z = (float) -(utm_y - m_EarthOrigin.y) * WORLD_SCALE;
}

void vtLocalProjection::convert_utm_to_local_xz(double utm_x, double utm_y,
												float &x, float &z)
{
	x = (float) (utm_x - m_EarthOrigin.x) * WORLD_SCALE;
	z = (float) -(utm_y - m_EarthOrigin.y) * WORLD_SCALE;
}

void vtLocalProjection::convert_utm_vector_to_local_xz(float utm_x,
													   float utm_y, float &x, float &z)
{
	x = (float) (utm_x * WORLD_SCALE);
	z = (float) -(utm_y * WORLD_SCALE);
}

void vtLocalProjection::convert_local_xz_to_utm(float x, float z,
												float &utm_x, float &utm_y)
{
	utm_x = (float) (x / WORLD_SCALE + m_EarthOrigin.x);
	utm_y = (float) -(z / WORLD_SCALE + m_EarthOrigin.y);
}

void vtLocalProjection::convert_local_xz_to_utm(float x, float z,
												double &utm_x, double &utm_y)
{
	utm_x = (x / WORLD_SCALE + m_EarthOrigin.x);
	utm_y = (-z / WORLD_SCALE + m_EarthOrigin.y);
}

void vtLocalProjection::convert_local_xz_to_latlon(float x, float z,
												   double &lat, double &lon)
{
	lon = m_EarthOrigin.x + (x / m_fMetersPerLongitude / WORLD_SCALE);
	lat = m_EarthOrigin.y + (-z / METERS_PER_LATITUDE / WORLD_SCALE);
}

//
// Convert from the coordinate system of the virtual world (x,y,z) to actual
// earth coodinates (map coordinates, altitude in meters)
//
void vtLocalProjection::ConvertToEarth(const FPoint3 &world, DPoint3 &earth)
{
	if (IsGeographic())
		convert_local_xz_to_latlon(world.x, world.z, earth.y, earth.x);
	else
		convert_local_xz_to_utm(world.x, world.z, earth.x, earth.y);
	earth.z = world.y / m_fVerticalScale;
}

void vtLocalProjection::ConvertFromEarth(const DPoint3 &earth, FPoint3 &world)
{
	if (IsGeographic())
		convert_latlon_to_local_xz(earth.y, earth.x, world.x, world.y);
	else
		convert_utm_to_local_xz(earth.x, earth.y, world.x, world.z);
	world.y = (float) (earth.z * m_fVerticalScale);
}

void vtLocalProjection::ConvertToEarth(float x, float z, DPoint2 &earth)
{
	if (IsGeographic())
		convert_local_xz_to_latlon(x, z, earth.y, earth.x);
	else
		convert_local_xz_to_utm(x, z, earth.x, earth.y);
}

void vtLocalProjection::ConvertFromEarth(const DPoint2 &earth, float &x, float &z)
{
	if (IsGeographic())
		convert_latlon_to_local_xz(earth.y, earth.x, x, z);
	else
		convert_utm_to_local_xz(earth.x, earth.y, x, z);
}

<|endoftext|>


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

Stock Buy Sell to Maximize Profit
=================================

Ref - http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/

--------------------------------------------------------------------------------

Problem
=======
Finding elements in BSTs.

--------------------------------------------------------------------------------

Time Complexity
===============
O(logn)

except for skew trees O(n)

--------------------------------------------------------------------------------

Output
======
Buy on day : 0   Sell on day: 3
Buy on day : 4   Sell on day: 6

*******************************************************************************/

#include <stdio.h>

struct Node {
    int data;
    Node *left;
    Node *right;
};

struct Node * getNode(int data)  {
    Node *newNode = new Node();
    newNode->data = data;
    newNode->left = newNode->right = NULL;

    return newNode;
}

int main()
{
    /* BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */

    Node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);

    return 0;
}
<commit_msg>BST Find and insertion<commit_after>/*******************************************************************************

Stock Buy Sell to Maximize Profit
=================================

Ref - http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/

--------------------------------------------------------------------------------

Problem
=======
Finding elements in BSTs.

--------------------------------------------------------------------------------

Time Complexity
===============
O(logn)

except for skew trees O(n)

--------------------------------------------------------------------------------

Output
======
Tree is:
50
30 70
20 40 60 80

Lowest element in tree: 20
Highest element in tree: 80

Data 60 exists in tree
Data 75 does NOT exist in tree

*******************************************************************************/

#include <stdio.h>
#include <queue>
using namespace std;

struct Node {
    int data;
    Node *left;
    Node *right;
};

struct Node * getNode(int data)  {
    Node *newNode = new Node();
    newNode->data = data;
    newNode->left = newNode->right = NULL;

    return newNode;
}

void printTree(Node *root) {
    queue<Node *> q;
    q.push(root);
    q.push(NULL);
    while(!q.empty()) {
        root = q.front();
        q.pop();
        if(root)    {
            printf("%d ", root->data);
            if(root->left)
                q.push(root->left);
            if(root->right)
                q.push(root->right);
        }
        else    {
            printf("\n");
            if(!q.empty())
                q.push(NULL);
        }
    }
}

struct Node * insert(Node *root, int data)  {
    if(root)    {
        if(data < root->data)
            root->left = insert(root->left, data);
        else if(data > root->data)
            root->right = insert(root->right, data);
    }
    else
        root = getNode(data);

    return root;
}

struct Node * lowest(Node *root)    {
    if(root->left)
        return lowest(root->left);

    return root;
}

struct Node * highest(Node *root)    {
    if(root->right)
        return highest(root->right);

    return root;
}

struct Node * find(Node *root, int data)    {
    if(root)    {
        if(root->data == data)
            return root;
        else if(data < root->data)
            return find(root->left, data);
        else
            return find(root->right, data);
    }

    return NULL;
}

int main()
{
    /* BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */

    Node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);

    printf("Tree is:\n");
    printTree(root);
    printf("\n");
    printf("Lowest element in tree: %d\n", lowest(root)->data);
    printf("Highest element in tree: %d\n", highest(root)->data);
    printf("\n");

    if(find(root, 60))
        printf("Data 60 exists in tree\n");
    else
        printf("Data 60 does NOT exist in tree\n");

    if(find(root, 75))
        printf("Data 75 exists in tree\n");
    else
        printf("Data 75 does NOT exist in tree\n");

    return 0;
}
<|endoftext|>


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

//
// NPAPI UnitTests.
//

// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>

// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <ostream>

#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;

std::ostream& operator<<(std::ostream& out, const CComBSTR &str)
{
  // I love strings.  I really do.  That's why I make sure
  // to need 4 different types of strings to stream one out.
  TCHAR szFinal[1024];
  _bstr_t bstrIntermediate(str);
  _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate);
  return out << szFinal;
}

// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
  std::wstring test_case = L"arguments.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
  std::wstring test_case = L"many_plugins.html";
  GURL url(GetTestUrl(L"npapi", test_case));
  NavigateToURL(url);

  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "2", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "3", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "4", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "5", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "6", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "7", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "8", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "9", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "10", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "11", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "12", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "13", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "14", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "15", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
  std::wstring test_case = L"geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("geturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
  std::wstring test_case = L"get_javascript_url.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
  std::wstring test_case = L"npobject_proxy.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
  std::wstring test_case = L"self_delete_plugin_geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_geturl", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
  std::wstring test_case = L"self_delete_plugin_invoke.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_invoke", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPITester, DISABLED_SelfDeletePluginInvokeAlert) {
  std::wstring test_case = L"self_delete_plugin_invoke_alert.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);

  // Wait for the alert dialog and then close it.
  automation()->WaitForAppModalDialog(5000);
  scoped_ptr<WindowProxy> window(automation()->GetActiveWindow());
  ASSERT_TRUE(window.get());
  ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0));

  WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"execute_script_delete_in_paint.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("execute_script_delete_in_paint", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"self_delete_plugin_stream.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("self_delete_plugin_stream", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
  show_window_ = true;
  std::wstring test_case = L"verify_plugin_window_rect.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"npobject_lifetime_test.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("npobject_lifetime_test", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
  GURL url = GetTestUrl(L"npapi", L"new_fails.html");
  NavigateToURL(url);
  WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
 if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    GURL url = GetTestUrl(L"npapi",
                          L"execute_script_delete_in_npn_evaluate.html");
    NavigateToURL(url);
    WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
 }
}

TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
  GURL url = GetTestUrl(L"npapi",
                        L"get_javascript_open_popup_with_plugin.html");
  NavigateToURL(url);
  WaitForFinish("plugin_popup_with_plugin_target", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                action_timeout_ms());
}
<commit_msg>Fix build break.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//
// NPAPI UnitTests.
//

// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>

// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <ostream>

#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;

std::ostream& operator<<(std::ostream& out, const CComBSTR &str)
{
  // I love strings.  I really do.  That's why I make sure
  // to need 4 different types of strings to stream one out.
  TCHAR szFinal[1024];
  _bstr_t bstrIntermediate(str);
  _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate);
  return out << szFinal;
}

// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
  std::wstring test_case = L"arguments.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
  std::wstring test_case = L"many_plugins.html";
  GURL url(GetTestUrl(L"npapi", test_case));
  NavigateToURL(url);

  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "2", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "3", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "4", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "5", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "6", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "7", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "8", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "9", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "10", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "11", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "12", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "13", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "14", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "15", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
  std::wstring test_case = L"geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("geturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
  std::wstring test_case = L"get_javascript_url.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
  std::wstring test_case = L"npobject_proxy.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
  std::wstring test_case = L"self_delete_plugin_geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_geturl", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
  std::wstring test_case = L"self_delete_plugin_invoke.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_invoke", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPITester, DISABLED_SelfDeletePluginInvokeAlert) {
  std::wstring test_case = L"self_delete_plugin_invoke_alert.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);

  // Wait for the alert dialog and then close it.
  automation()->WaitForAppModalDialog(5000);
  scoped_ptr<WindowProxy> window(automation()->GetActiveWindow());
  ASSERT_TRUE(window.get());
  ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0));

  WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
  if (!UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"execute_script_delete_in_paint.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("execute_script_delete_in_paint", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
  if (!UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"self_delete_plugin_stream.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("self_delete_plugin_stream", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
  show_window_ = true;
  std::wstring test_case = L"verify_plugin_window_rect.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
  if (!UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"npobject_lifetime_test.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("npobject_lifetime_test", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
  GURL url = GetTestUrl(L"npapi", L"new_fails.html");
  NavigateToURL(url);
  WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
 if (!UITest::in_process_renderer()) {
    GURL url = GetTestUrl(L"npapi",
                          L"execute_script_delete_in_npn_evaluate.html");
    NavigateToURL(url);
    WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
 }
}

TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
  GURL url = GetTestUrl(L"npapi",
                        L"get_javascript_open_popup_with_plugin.html");
  NavigateToURL(url);
  WaitForFinish("plugin_popup_with_plugin_target", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                action_timeout_ms());
}
<|endoftext|>


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

//
// NPAPI UnitTests.
//

// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>

// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <ostream>

#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;

std::ostream& operator<<(std::ostream& out, const CComBSTR &str)
{
  // I love strings.  I really do.  That's why I make sure
  // to need 4 different types of strings to stream one out.
  TCHAR szFinal[1024];
  _bstr_t bstrIntermediate(str);
  _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate);
  return out << szFinal;
}

// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
  std::wstring test_case = L"arguments.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
  std::wstring test_case = L"many_plugins.html";
  GURL url(GetTestUrl(L"npapi", test_case));
  NavigateToURL(url);

  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "2", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "3", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "4", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "5", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "6", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "7", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "8", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "9", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "10", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "11", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "12", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "13", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "14", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "15", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
  std::wstring test_case = L"geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("geturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
  std::wstring test_case = L"get_javascript_url.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
  std::wstring test_case = L"npobject_proxy.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
  std::wstring test_case = L"self_delete_plugin_geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_geturl", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
  std::wstring test_case = L"self_delete_plugin_invoke.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_invoke", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvokeAlert) {
  std::wstring test_case = L"self_delete_plugin_invoke_alert.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);

  // Wait for the alert dialog and then close it.
  automation()->WaitForAppModalDialog(5000);
  scoped_ptr<WindowProxy> window(automation()->GetActiveWindow());
  ASSERT_TRUE(window.get());
  ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0));

  WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"execute_script_delete_in_paint.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("execute_script_delete_in_paint", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"self_delete_plugin_stream.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("self_delete_plugin_stream", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
  show_window_ = true;
  std::wstring test_case = L"verify_plugin_window_rect.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"npobject_lifetime_test.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("npobject_lifetime_test", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
  GURL url = GetTestUrl(L"npapi", L"new_fails.html");
  NavigateToURL(url);
  WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
 if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    GURL url = GetTestUrl(L"npapi",
                          L"execute_script_delete_in_npn_evaluate.html");
    NavigateToURL(url);
    WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
 }
}

TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
  GURL url = GetTestUrl(L"npapi",
                        L"get_javascript_open_popup_with_plugin.html");
  NavigateToURL(url);
  WaitForFinish("plugin_popup_with_plugin_target", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}
<commit_msg>Disable NPAPITester.SelfDeletePluginInvokeAlert UI test.  It doesn't seem to work on the buildbots.  I need to find a better way to get the WindowProxy for the alert dialog.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//
// NPAPI UnitTests.
//

// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>

// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <ostream>

#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;

std::ostream& operator<<(std::ostream& out, const CComBSTR &str)
{
  // I love strings.  I really do.  That's why I make sure
  // to need 4 different types of strings to stream one out.
  TCHAR szFinal[1024];
  _bstr_t bstrIntermediate(str);
  _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate);
  return out << szFinal;
}

// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
  std::wstring test_case = L"arguments.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
  std::wstring test_case = L"many_plugins.html";
  GURL url(GetTestUrl(L"npapi", test_case));
  NavigateToURL(url);

  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "2", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "3", url, kTestCompleteCookie,
                kTestCompleteSuccess,  kShortWaitTimeout);
  WaitForFinish("arguments", "4", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "5", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "6", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "7", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "8", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "9", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "10", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "11", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "12", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "13", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "14", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
  WaitForFinish("arguments", "15", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
  std::wstring test_case = L"geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("geturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
  std::wstring test_case = L"get_javascript_url.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
  std::wstring test_case = L"npobject_proxy.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
  std::wstring test_case = L"self_delete_plugin_geturl.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_geturl", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
  std::wstring test_case = L"self_delete_plugin_invoke.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("self_delete_plugin_invoke", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPITester, DISABLED_SelfDeletePluginInvokeAlert) {
  std::wstring test_case = L"self_delete_plugin_invoke_alert.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);

  // Wait for the alert dialog and then close it.
  automation()->WaitForAppModalDialog(5000);
  scoped_ptr<WindowProxy> window(automation()->GetActiveWindow());
  ASSERT_TRUE(window.get());
  ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0));

  WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}

// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"execute_script_delete_in_paint.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("execute_script_delete_in_paint", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"self_delete_plugin_stream.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("self_delete_plugin_stream", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
  show_window_ = true;
  std::wstring test_case = L"verify_plugin_window_rect.html";
  GURL url = GetTestUrl(L"npapi", test_case);
  NavigateToURL(url);
  WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
  if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    show_window_ = true;
    std::wstring test_case = L"npobject_lifetime_test.html";
    GURL url = GetTestUrl(L"npapi", test_case);
    NavigateToURL(url);
    WaitForFinish("npobject_lifetime_test", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
  }
}

// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
  GURL url = GetTestUrl(L"npapi", L"new_fails.html");
  NavigateToURL(url);
  WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, kShortWaitTimeout);
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
 if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
    GURL url = GetTestUrl(L"npapi",
                          L"execute_script_delete_in_npn_evaluate.html");
    NavigateToURL(url);
    WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
                  kTestCompleteCookie, kTestCompleteSuccess,
                  kShortWaitTimeout);
 }
}

TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
  GURL url = GetTestUrl(L"npapi",
                        L"get_javascript_open_popup_with_plugin.html");
  NavigateToURL(url);
  WaitForFinish("plugin_popup_with_plugin_target", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                kShortWaitTimeout);
}
<|endoftext|>


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

#include "base/file_path.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"

#if defined(OS_WIN)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll";
#elif defined(OS_MACOSX)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin";
#elif defined(OS_LINUX)
static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so";
#endif

using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;

// Helper class pepper NPAPI tests.
class PepperTester : public NPAPITesterBase {
 protected:
  PepperTester() : NPAPITesterBase(kPepperTestPluginName) {}

  virtual void SetUp() {
    // TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox.
    launch_arguments_.AppendSwitch(switches::kNoSandbox);
    launch_arguments_.AppendSwitch(switches::kInternalPepper);
    launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin);
    NPAPITesterBase::SetUp();
  }
};

// Test that a pepper 3d plugin loads and renders.
// TODO(alokp): Enable the test after making sure it works on all platforms
// and buildbots have OpenGL support.
#if defined(OS_WIN)
// Disabled after failing on buildbots: crbug/46662
TEST_F(PepperTester, DISABLED_Pepper3D) {
  const FilePath dir(FILE_PATH_LITERAL("pepper"));
  const FilePath file(FILE_PATH_LITERAL("pepper_3d.html"));
  GURL url = ui_test_utils::GetTestUrl(dir, file);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("pepper_3d", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                action_max_timeout_ms());
}
#endif
<commit_msg>Enabled pepper3d test. Explicitly specified Mesa renderer to use for the 3d tests. BUG=46662 TEST=Manually test ui_tests.PepperTester.Pepper3D and npapi_pepper_test_plugin. Review URL: http://codereview.chromium.org/3067007<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"

#include "app/app_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"

#if defined(OS_WIN)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll";
#elif defined(OS_MACOSX)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin";
#elif defined(OS_LINUX)
static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so";
#endif

using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;

// Helper class pepper NPAPI tests.
class PepperTester : public NPAPITesterBase {
 protected:
  PepperTester() : NPAPITesterBase(kPepperTestPluginName) {}

  virtual void SetUp() {
    // TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox.
    launch_arguments_.AppendSwitch(switches::kNoSandbox);
    launch_arguments_.AppendSwitch(switches::kInternalPepper);
    launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin);
    // Use Mesa software renderer so it can run on testbots without any
    // graphics hardware.
    launch_arguments_.AppendSwitchWithValue(switches::kUseGL, "osmesa");
    NPAPITesterBase::SetUp();
  }
};

// Test that a pepper 3d plugin loads and renders.
// TODO(alokp): Enable the test after making sure it works on all platforms
// and buildbots have OpenGL support.
#if defined(OS_WIN)
TEST_F(PepperTester, Pepper3D) {
  const FilePath dir(FILE_PATH_LITERAL("pepper"));
  const FilePath file(FILE_PATH_LITERAL("pepper_3d.html"));
  GURL url = ui_test_utils::GetTestUrl(dir, file);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("pepper_3d", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                action_max_timeout_ms());
}
#endif
<|endoftext|>