<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include "string.h"

//if visual c++
#include <complex>
#define lapack_complex_float std::complex<float>
#define lapack_complex_double std::complex<double>

//#define ADD_
//#define HAVE_LAPACK_CONFIG_H
//#define LAPACK_COMPLEX_STRUCTURE

#include "lapacke.h"
#include "matrix.h"
//#include <armadillo/armadillo>
//using namespace arma;

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

    runButton = new QPushButton("Run",this);
    //runButton->setText("Run");
    runButton->setGeometry(QRect(QPoint(450,320),QSize(75,23)));
    connect(runButton, SIGNAL(clicked()), this, SLOT(on_runButton_clicked()));

    inputText = new QPlainTextEdit(this);
    inputText->setGeometry(10,50,411,261);

    inputLabel = new QLabel(this);
    inputLabel->setText("Input Text");
    inputLabel->setGeometry(10,30,411,13);

    outputText = new QTextBrowser(this);
    outputText->setGeometry(10,350,411,241);

    outputLabel = new QLabel(this);
    outputLabel->setText("Output");
    outputLabel->setGeometry(10,330,411,13);

}

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

std::string print_mat(Matrix A)
{
    std::string text;
    for (int i = 0; i < A.rows(); i++)
    {
        for (int j = 0; j < A.cols(); j++)
        {
            char buffer [50];
#if defined(_MSC_VER) && _MSC_VER >= 1400
            sprintf_s(buffer,sizeof(buffer),"%g",A(i,j));
#else
            sprintf(buffer,"%g",A(i,j));
#endif
            text.append(buffer);
            //text.append(std::to_string(A(i,j)));
            if (j != A.cols())
            {
                text.append(" ");
            }
        }
        text.append("\n");
    }
    return text;
}

std::string print_mat(double *A, int rows, int cols)
{
    std::string text;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            char buffer [50];
#if defined(_MSC_VER) && _MSC_VER >= 1400
            sprintf_s(buffer,sizeof(buffer),"%g",A[i*cols+j]);
#else
            sprintf(buffer,"%g",A[i*cols+j]);
#endif
            text.append(buffer);
            //text.append(std::to_string(A(i,j)));
            if (j != cols)
            {
                text.append(" ");
            }
        }
        text.append("\n");
    }
    return text;
}

std::string print_mat(int *A, int rows, int cols)
{
    std::string text;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            char buffer [50];
            //sprintf(buffer,"%g",A[i*cols+j]);
#if defined(_MSC_VER) && _MSC_VER >= 1400
            sprintf_s(buffer,sizeof(buffer),"%g",A[i*cols+j]);
#else
            sprintf(buffer,"%d",A[i*cols+j]);
#endif
            text.append(buffer);
            //text.append(std::to_string(A(i,j)));
            if (j != cols)
            {
                text.append(" ");
            }
        }
        text.append("\n");
    }
    return text;
}

void MainWindow::on_runButton_clicked()
{
    //outputText->append("Hello World!");
    std::string in_text = inputText->toPlainText().toStdString();
    outputText->append(QString::fromStdString(in_text));

    Matrix A(2,2);
    A[0][0] = 1;
    A[0][1] = 2;
    A[1][0] = 3;
    A[1][1] = 4;

    Matrix B(2,1);
    B[0][0] = 1;
    B[1][0] = 1;

    //double a[2*2] = {1,2,3,4};
    //double b[2*1] = {1,1};
    int ipiv[2] = {0,0};

    //int n = 2;
    //int nrhs = 1;
    //int lda = 2;
    //int ldb = 1;

    outputText->append(QString::fromStdString(print_mat(A.mat(),2,2)));
    outputText->append(QString::fromStdString(print_mat(B.mat(),2,1)));

    //int info = 0;

    LAPACKE_dgesv(LAPACK_ROW_MAJOR,A.rows(),B.cols(),A.mat(),A.cols(),ipiv,B.mat(),B.cols());

    //dgesv_(&n,&nrhs,a,&lda,ipiv,b,&ldb,&info);

    //outputText->append(QString::fromStdString(print_mat(ipiv,2,1)));
    outputText->append(QString::fromStdString(print_mat(B.mat(),2,1)));
    outputText->append(QString("%1\n").arg(B.cols()));

    //double A[2][2] = {1,2,3,4};
    //int ld = 2;

    //arma::mat A(2,2);
    //A << 1 << 2.4 << arma::endr << 3 << 4 << arma::endr;
}
<commit_msg>Testing out matrix solution functions.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include "string.h"

//if visual c++
#include <complex>
#define lapack_complex_float std::complex<float>
#define lapack_complex_double std::complex<double>

//#define ADD_
//#define HAVE_LAPACK_CONFIG_H
//#define LAPACK_COMPLEX_STRUCTURE

#include "lapacke.h"
#include "matrix.h"
//#include <armadillo/armadillo>
//using namespace arma;

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

    runButton = new QPushButton("Run",this);
    //runButton->setText("Run");
    runButton->setGeometry(QRect(QPoint(450,320),QSize(75,23)));
    connect(runButton, SIGNAL(clicked()), this, SLOT(on_runButton_clicked()));

    inputText = new QPlainTextEdit(this);
    inputText->setGeometry(10,50,411,261);

    inputLabel = new QLabel(this);
    inputLabel->setText("Input Text");
    inputLabel->setGeometry(10,30,411,13);

    outputText = new QTextBrowser(this);
    outputText->setGeometry(10,350,411,241);

    outputLabel = new QLabel(this);
    outputLabel->setText("Output");
    outputLabel->setGeometry(10,330,411,13);

}

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

std::string print_mat(Matrix A)
{
    std::string text;
    for (int i = 0; i < A.rows(); i++)
    {
        for (int j = 0; j < A.cols(); j++)
        {
            char buffer [50];
#if defined(_MSC_VER) && _MSC_VER >= 1400
            sprintf_s(buffer,sizeof(buffer),"%g",A(i,j));
#else
            sprintf(buffer,"%g",A(i,j));
#endif
            text.append(buffer);
            //text.append(std::to_string(A(i,j)));
            if (j != A.cols())
            {
                text.append(" ");
            }
        }
        text.append("\n");
    }
    return text;
}

std::string print_mat(double *A, int rows, int cols)
{
    std::string text;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            char buffer [50];
#if defined(_MSC_VER) && _MSC_VER >= 1400
            sprintf_s(buffer,sizeof(buffer),"%g",A[i*cols+j]);
#else
            sprintf(buffer,"%g",A[i*cols+j]);
#endif
            text.append(buffer);
            //text.append(std::to_string(A(i,j)));
            if (j != cols)
            {
                text.append(" ");
            }
        }
        text.append("\n");
    }
    return text;
}

std::string print_mat(int *A, int rows, int cols)
{
    std::string text;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            char buffer [50];
            //sprintf(buffer,"%g",A[i*cols+j]);
#if defined(_MSC_VER) && _MSC_VER >= 1400
            sprintf_s(buffer,sizeof(buffer),"%g",A[i*cols+j]);
#else
            sprintf(buffer,"%d",A[i*cols+j]);
#endif
            text.append(buffer);
            //text.append(std::to_string(A(i,j)));
            if (j != cols)
            {
                text.append(" ");
            }
        }
        text.append("\n");
    }
    return text;
}

void MainWindow::on_runButton_clicked()
{
    //outputText->append("Hello World!");
    std::string in_text = inputText->toPlainText().toStdString();
    outputText->append(QString::fromStdString(in_text));

    Matrix A(2,2);
    A[0][0] = 1;
    A[0][1] = 2;
    A[1][0] = 2;
    A[1][1] = 4;
    //Matrix Avec = A;

    Matrix B(2,1);
    B[0][0] = 1;
    B[1][0] = 1;
    //Matrix Bi = B;

    //double a[2*2] = {1,2,3,4};
    //double b[2*1] = {1,1};
    //int ipiv[2] = {0,0};

    //int n = 2;
    //int nrhs = 1;
    //int lda = 2;
    //int ldb = 1;

    outputText->append(QString::fromStdString(print_mat(A.mat(),2,2)));
    outputText->append(QString::fromStdString(print_mat(B.mat(),2,1)));

    //int info = 0;

    //LAPACKE_dgesv(LAPACK_ROW_MAJOR,A.rows(),B.cols(),A.mat(),A.cols(),ipiv,B.mat(),B.cols());
    //LAPACKE_dgeev(LAPACK_ROW_MAJOR,'N','V',A.rows(),A.mat(),A.cols(),B.mat(),Bi.mat(),Avec.mat(),Avec.cols(),Avec.mat(),Avec.cols());
    //LAPACKE_dsysv(LAPACK_ROW_MAJOR,'U',A.rows(),B.cols(),A.mat(),A.cols(),ipiv,B.mat(),B.cols());
    LAPACKE_dsyev(LAPACK_ROW_MAJOR,'V','U',A.rows(),A.mat(),A.cols(),B.mat());

    //dgesv_(&n,&nrhs,a,&lda,ipiv,b,&ldb,&info);

    //outputText->append(QString::fromStdString(print_mat(ipiv,2,1)));
    //outputText->append(QString::fromStdString(print_mat(A.mat(),2,2)));
    //outputText->append(QString::fromStdString(print_mat(B.mat(),2,1)));
    //outputText->append(QString::fromStdString(print_mat(Avec)));
    outputText->append(QString::fromStdString(print_mat(B)));
    outputText->append(QString::fromStdString(print_mat(A)));
    //outputText->append(QString("%1\n").arg(B.cols()));

    //double A[2][2] = {1,2,3,4};
    //int ld = 2;

    //arma::mat A(2,2);
    //A << 1 << 2.4 << arma::endr << 3 << 4 << arma::endr;
}
<|endoftext|>


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

#include <QDebug>

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

MainWindow::~MainWindow()
{
    delete field;
    delete ui;
}

void MainWindow::keyPressEvent(QKeyEvent *e){
    bool success = false;
    signed char pl = field->current_player;
    switch(e->key()){
        case Qt::Key_Z:
        case Qt::Key_1:
            success = field->try_step(1);
            break;
        case Qt::Key_X:
        case Qt::Key_2:
            success = field->try_step(2);
            break;
        case Qt::Key_C:
        case Qt::Key_3:
            success = field->try_step(3);
            break;
        case Qt::Key_A:
        case Qt::Key_4:
            success = field->try_step(4);
            break;
        case Qt::Key_D:
        case Qt::Key_6:
            success = field->try_step(6);
            break;
        case Qt::Key_Q:
        case Qt::Key_7:
            success = field->try_step(7);
            break;
        case Qt::Key_W:
        case Qt::Key_8:
            success = field->try_step(8);
            break;
        case Qt::Key_E:
        case Qt::Key_9:
            success = field->try_step(9);
    }
    if (success){
        show_pointer = false;
        this->repaint();
        if (field->winner){
            QMessageBox::information(this, tr("Game over"), tr(field->winner > 0 ? "Blue player win!" : "Red player win!"));
        }
        else {
            if(pl != field->current_player){
                if(field->current_player < 0)
                    QMessageBox::information(this, tr("Information"), tr("Red player kicks"));
                else
                    QMessageBox::information(this, tr("Information"), tr("Blue player kicks"));
            }
            if(field->penalty_mode){
                QMessageBox::information(this, tr("Information"), tr("PENALTY!"));
            }
            else{
                int direction = field->only_one_way();
                if(direction){
                    qDebug() << "Auto move\n";
                    QKeyEvent key(QEvent::KeyPress, Qt::Key_0 + direction, Qt::NoModifier);
                    QApplication::sendEvent(this, &key);
                    if (!key.isAccepted()) qDebug() << "something wrong\n";
                }
            }
        }
    }
}

void MainWindow::paintEvent(QPaintEvent *){
    QPainter painter(this);
    QPen light_blue_pen(QColor("#add8e6"), 1);
    QPen blue_pen(QColor("#00f"), 1);
    QPen red_pen(QColor("#f00"), 1);
    QPen std_pen(QColor("#000"), 1);
    QPen tip_pen(QColor("#be00be"), 1);

    int top_offset = ui->menuBar->height();

    // Рисуем сетку
    painter.setPen(light_blue_pen);
    for(int i = 0; i < FIELD_WIDTH / PX_SCALE; i++){
        painter.drawLine(PX_SCALE * i, top_offset, PX_SCALE * i, top_offset + FIELD_HEIGHT);
    }
    for(int i = 0; i < FIELD_HEIGHT / PX_SCALE; i++){
        painter.drawLine(0, top_offset + PX_SCALE * i, FIELD_WIDTH, top_offset + PX_SCALE * i);
    }

    // Рисуем ворота синих
    painter.setPen(blue_pen);
    painter.drawLine(FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset + FIELD_HEIGHT, FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset + FIELD_HEIGHT - PX_SCALE);
    painter.drawLine(FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset + FIELD_HEIGHT, FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset + FIELD_HEIGHT - PX_SCALE);

    // Рисуем ворота красных
    painter.setPen(red_pen);
    painter.drawLine(FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset, FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset + PX_SCALE);
    painter.drawLine(FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset, FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset + PX_SCALE);

    // Рисуем стартовую точку, и точки в воротах
    painter.setPen(std_pen);
    painter.drawEllipse(QPointF(FIELD_WIDTH / 2, top_offset + 1), 1, 1);
    painter.drawEllipse(QPointF(FIELD_WIDTH / 2, top_offset + FIELD_HEIGHT - 1), 1, 1);
    painter.drawEllipse(QPointF(FIELD_WIDTH / 2, top_offset + FIELD_HEIGHT / 2), 1, 1);

    int old_x = FIELD_WIDTH  / 2,
        old_y = FIELD_HEIGHT / 2;
    std::vector<signed char>::iterator iterator = field->steps.begin();
    while (iterator != field->steps.end()) {
        int index = abs((int) *iterator);
        int x = old_x - PX_SCALE * field->KEYS[index][0];
        int y = old_y - PX_SCALE * field->KEYS[index][1];
        painter.setPen(*iterator < 0 ? red_pen : blue_pen);
        painter.drawLine(old_x, top_offset + old_y, x, top_offset + y);
        old_x = x;
        old_y = y;
        ++iterator;
    }

    // Ball marker
    if(field->show_ball){
        painter.setPen(std_pen);
        painter.drawEllipse(QPointF(old_x, top_offset + old_y), 2, 2);
    }

    if(show_pointer){
        painter.setPen(tip_pen);
        // Without top_offset!
        painter.drawEllipse(QPointF(mouse_pointer.x(), mouse_pointer.y()), 2, 2);

        int ball_x = field->ball.x,
            ball_y = field->ball.y;

        for(int i = 0; i < 6; i++){
            int index = get_key_from_coord(mouse_pointer.x(), mouse_pointer.y(), old_x, top_offset + old_y);
            if(field->can_penalty(index) || field->can_step_from(field->KEYS[index][0], field->KEYS[index][1], ball_x, ball_y)){
                int x = old_x - PX_SCALE * field->KEYS[index][0];
                int y = old_y - PX_SCALE * field->KEYS[index][1];
                painter.drawLine(old_x, top_offset + old_y, x, top_offset + y);
                old_x = x;
                old_y = y;
                ball_x += field->KEYS[index][0];
                ball_y += field->KEYS[index][1];
            }
            else
                break;
        }
    }

}

void MainWindow::mouseMoveEvent(QMouseEvent *event){
    int top_offset = ui->menuBar->height();
    int mx = event->pos().x(),
        my = event->pos().y();
    const int bx = FIELD_WIDTH  / 2 - PX_SCALE * field->ball.x,
              by = FIELD_HEIGHT / 2 - PX_SCALE * field->ball.y + top_offset,
              cells_count = (field->penalty_mode ? 6 : (3 - field->current_step + 1)); // because current_step start from 1
    if((mx <= bx + PX_SCALE * cells_count + PX_SCALE / 3 && mx >= bx - PX_SCALE * cells_count - PX_SCALE / 3) && // mouse x in -3..3 or -6..6
       (my <= by + PX_SCALE * cells_count + PX_SCALE / 3 && my >= by - PX_SCALE * cells_count - PX_SCALE / 3)    // mouse y in -3..3 or -6..6
    ){
        const int local_mx = mx % PX_SCALE,
                  local_my = (my - top_offset) % PX_SCALE;
        if((local_mx <= PX_SCALE / 3 || local_mx >= PX_SCALE / 3 * 2) && // x and y can cling to grid point
           (local_my <= PX_SCALE / 3 || local_my >= PX_SCALE / 3 * 2)
        ){
            if(local_mx <= PX_SCALE / 3)
                mx -= local_mx;
            else // if(local_mx >= PX_SCALE / 3 * 2)
                mx += PX_SCALE - local_mx;
            if(local_my <= PX_SCALE / 3)
                my -= local_my;
            else // if(local_my >= PX_SCALE / 3 * 2)
                my += PX_SCALE - local_my;

            show_pointer = true;

            if(field->penalty_mode){
                int index = get_key_from_coord(mx, my, bx, by);

                mx = bx;
                my = by;
                for(int i = 0; i < 6; i++){
                    mx = mx - PX_SCALE * field->KEYS[index][0];
                    my = my - PX_SCALE * field->KEYS[index][1];
                }
            }
            mouse_pointer.setX(mx);
            mouse_pointer.setY(my);
            this->repaint();
        }
        return;
    }
    if(show_pointer){
        show_pointer = false;
        this->repaint();
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event){
    int top_offset = ui->menuBar->height();
    if(show_pointer && event->button() == Qt::LeftButton){
        int need_steps;
        int bx = FIELD_WIDTH  / 2 - PX_SCALE * field->ball.x,
            by = FIELD_HEIGHT / 2 - PX_SCALE * field->ball.y + top_offset;
        int s_x = abs(bx - mouse_pointer.x());
        int s_y = abs(by - mouse_pointer.y());
        if(s_x > s_y)
            need_steps = s_x / PX_SCALE;
        else
            need_steps = s_y / PX_SCALE;
        bool old_penalty = field->penalty_mode;
        for(int i = 0; i < need_steps; i++){
            qDebug() << "Click!" << need_steps << "\n";
            qint32 key_num = get_key_from_coord(mouse_pointer.x(), mouse_pointer.y());
            if(key_num == Qt::Key_5){
                qDebug() << "Ball position!\n";
                return;
            }
            if(field->penalty_mode != old_penalty)
                return;
            QKeyEvent key(QEvent::KeyPress, key_num, Qt::NoModifier);
            QApplication::sendEvent(this, &key);
            if (!key.isAccepted()) qDebug() << "something wrong\n";
        }
    }
}

qint32 MainWindow::get_key_from_coord(int x, int y){
    int top_offset = ui->menuBar->height();
    int bx = FIELD_WIDTH  / 2 - PX_SCALE * field->ball.x,
        by = FIELD_HEIGHT / 2 - PX_SCALE * field->ball.y + top_offset;

    // Don't move - this is a ball-point
    if(x == bx && y == by) return Qt::Key_5;

    if(x <  bx && y >  by) return Qt::Key_1;
    if(x == bx && y >  by) return Qt::Key_2;
    if(x >  bx && y >  by) return Qt::Key_3;
    if(x <  bx && y == by) return Qt::Key_4;
    if(x >  bx && y == by) return Qt::Key_6;
    if(x <  bx && y <  by) return Qt::Key_7;
    if(x == bx && y <  by) return Qt::Key_8;
    if(x >  bx && y <  by) return Qt::Key_9;

    // just in case
    return Qt::Key_5;
}

int MainWindow::get_key_from_coord(int x, int y, int bx, int by){
    // Don't move - this is a ball-point
    if(x == bx && y == by) return 5;

    if(x <  bx && y >  by) return 1;
    if(x == bx && y >  by) return 2;
    if(x >  bx && y >  by) return 3;
    if(x <  bx && y == by) return 4;
    if(x >  bx && y == by) return 6;
    if(x <  bx && y <  by) return 7;
    if(x == bx && y <  by) return 8;
    if(x >  bx && y <  by) return 9;

    // just in case
    return 5;
}

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
        tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
//        QTextStream in(&file);
//        textEdit->setText(in.readAll());

        file.close();
    }
}

void MainWindow::save()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "",
    tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            // error message
        } else {
//            QTextStream stream(&file);
//            stream << textEdit->toPlainText();
//            stream.flush();
            file.close();
        }
    }
}

void MainWindow::new_field()
{
    delete field;
    field = new FootballField;
    this->repaint();
}

<commit_msg>Fix gameover mouse tips<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

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

MainWindow::~MainWindow()
{
    delete field;
    delete ui;
}

void MainWindow::keyPressEvent(QKeyEvent *e){
    bool success = false;
    signed char pl = field->current_player;
    switch(e->key()){
        case Qt::Key_Z:
        case Qt::Key_1:
            success = field->try_step(1);
            break;
        case Qt::Key_X:
        case Qt::Key_2:
            success = field->try_step(2);
            break;
        case Qt::Key_C:
        case Qt::Key_3:
            success = field->try_step(3);
            break;
        case Qt::Key_A:
        case Qt::Key_4:
            success = field->try_step(4);
            break;
        case Qt::Key_D:
        case Qt::Key_6:
            success = field->try_step(6);
            break;
        case Qt::Key_Q:
        case Qt::Key_7:
            success = field->try_step(7);
            break;
        case Qt::Key_W:
        case Qt::Key_8:
            success = field->try_step(8);
            break;
        case Qt::Key_E:
        case Qt::Key_9:
            success = field->try_step(9);
    }
    if (success){
        show_pointer = false;
        this->repaint();
        if (field->winner){
            QMessageBox::information(this, tr("Game over"), tr(field->winner > 0 ? "Blue player win!" : "Red player win!"));
        }
        else {
            if(pl != field->current_player){
                if(field->current_player < 0)
                    QMessageBox::information(this, tr("Information"), tr("Red player kicks"));
                else
                    QMessageBox::information(this, tr("Information"), tr("Blue player kicks"));
            }
            if(field->penalty_mode){
                QMessageBox::information(this, tr("Information"), tr("PENALTY!"));
            }
            else{
                int direction = field->only_one_way();
                if(direction){
                    qDebug() << "Auto move\n";
                    QKeyEvent key(QEvent::KeyPress, Qt::Key_0 + direction, Qt::NoModifier);
                    QApplication::sendEvent(this, &key);
                    if (!key.isAccepted()) qDebug() << "something wrong\n";
                }
            }
        }
    }
}

void MainWindow::paintEvent(QPaintEvent *){
    QPainter painter(this);
    QPen light_blue_pen(QColor("#add8e6"), 1);
    QPen blue_pen(QColor("#00f"), 1);
    QPen red_pen(QColor("#f00"), 1);
    QPen std_pen(QColor("#000"), 1);
    QPen tip_pen(QColor("#be00be"), 1);

    int top_offset = ui->menuBar->height();

    // Рисуем сетку
    painter.setPen(light_blue_pen);
    for(int i = 0; i < FIELD_WIDTH / PX_SCALE; i++){
        painter.drawLine(PX_SCALE * i, top_offset, PX_SCALE * i, top_offset + FIELD_HEIGHT);
    }
    for(int i = 0; i < FIELD_HEIGHT / PX_SCALE; i++){
        painter.drawLine(0, top_offset + PX_SCALE * i, FIELD_WIDTH, top_offset + PX_SCALE * i);
    }

    // Рисуем ворота синих
    painter.setPen(blue_pen);
    painter.drawLine(FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset + FIELD_HEIGHT, FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset + FIELD_HEIGHT - PX_SCALE);
    painter.drawLine(FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset + FIELD_HEIGHT, FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset + FIELD_HEIGHT - PX_SCALE);

    // Рисуем ворота красных
    painter.setPen(red_pen);
    painter.drawLine(FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset, FIELD_WIDTH / 2 - PX_SCALE * 3, top_offset + PX_SCALE);
    painter.drawLine(FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset, FIELD_WIDTH / 2 + PX_SCALE * 3, top_offset + PX_SCALE);

    // Рисуем стартовую точку, и точки в воротах
    painter.setPen(std_pen);
    painter.drawEllipse(QPointF(FIELD_WIDTH / 2, top_offset + 1), 1, 1);
    painter.drawEllipse(QPointF(FIELD_WIDTH / 2, top_offset + FIELD_HEIGHT - 1), 1, 1);
    painter.drawEllipse(QPointF(FIELD_WIDTH / 2, top_offset + FIELD_HEIGHT / 2), 1, 1);

    int old_x = FIELD_WIDTH  / 2,
        old_y = FIELD_HEIGHT / 2;
    std::vector<signed char>::iterator iterator = field->steps.begin();
    while (iterator != field->steps.end()) {
        int index = abs((int) *iterator);
        int x = old_x - PX_SCALE * field->KEYS[index][0];
        int y = old_y - PX_SCALE * field->KEYS[index][1];
        painter.setPen(*iterator < 0 ? red_pen : blue_pen);
        painter.drawLine(old_x, top_offset + old_y, x, top_offset + y);
        old_x = x;
        old_y = y;
        ++iterator;
    }

    // Ball marker
    if(field->show_ball){
        painter.setPen(std_pen);
        painter.drawEllipse(QPointF(old_x, top_offset + old_y), 2, 2);
    }

    if(show_pointer && field->winner == 0){
        painter.setPen(tip_pen);
        // Without top_offset!
        painter.drawEllipse(QPointF(mouse_pointer.x(), mouse_pointer.y()), 2, 2);

        int ball_x = field->ball.x,
            ball_y = field->ball.y;

        for(int i = 0; i < 6; i++){
            int index = get_key_from_coord(mouse_pointer.x(), mouse_pointer.y(), old_x, top_offset + old_y);
            if(field->can_penalty(index) || field->can_step_from(field->KEYS[index][0], field->KEYS[index][1], ball_x, ball_y)){
                int x = old_x - PX_SCALE * field->KEYS[index][0];
                int y = old_y - PX_SCALE * field->KEYS[index][1];
                painter.drawLine(old_x, top_offset + old_y, x, top_offset + y);
                old_x = x;
                old_y = y;
                ball_x += field->KEYS[index][0];
                ball_y += field->KEYS[index][1];
            }
            else
                break;
        }
    }

}

void MainWindow::mouseMoveEvent(QMouseEvent *event){
    int top_offset = ui->menuBar->height();
    int mx = event->pos().x(),
        my = event->pos().y();
    const int bx = FIELD_WIDTH  / 2 - PX_SCALE * field->ball.x,
              by = FIELD_HEIGHT / 2 - PX_SCALE * field->ball.y + top_offset,
              cells_count = (field->penalty_mode ? 6 : (3 - field->current_step + 1)); // because current_step start from 1
    if((mx <= bx + PX_SCALE * cells_count + PX_SCALE / 3 && mx >= bx - PX_SCALE * cells_count - PX_SCALE / 3) && // mouse x in -3..3 or -6..6
       (my <= by + PX_SCALE * cells_count + PX_SCALE / 3 && my >= by - PX_SCALE * cells_count - PX_SCALE / 3)    // mouse y in -3..3 or -6..6
    ){
        const int local_mx = mx % PX_SCALE,
                  local_my = (my - top_offset) % PX_SCALE;
        if((local_mx <= PX_SCALE / 3 || local_mx >= PX_SCALE / 3 * 2) && // x and y can cling to grid point
           (local_my <= PX_SCALE / 3 || local_my >= PX_SCALE / 3 * 2)
        ){
            if(local_mx <= PX_SCALE / 3)
                mx -= local_mx;
            else // if(local_mx >= PX_SCALE / 3 * 2)
                mx += PX_SCALE - local_mx;
            if(local_my <= PX_SCALE / 3)
                my -= local_my;
            else // if(local_my >= PX_SCALE / 3 * 2)
                my += PX_SCALE - local_my;

            show_pointer = true;

            if(field->penalty_mode){
                int index = get_key_from_coord(mx, my, bx, by);

                mx = bx;
                my = by;
                for(int i = 0; i < 6; i++){
                    mx = mx - PX_SCALE * field->KEYS[index][0];
                    my = my - PX_SCALE * field->KEYS[index][1];
                }
            }
            mouse_pointer.setX(mx);
            mouse_pointer.setY(my);
            this->repaint();
        }
        return;
    }
    if(show_pointer){
        show_pointer = false;
        this->repaint();
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event){
    int top_offset = ui->menuBar->height();
    if(show_pointer && event->button() == Qt::LeftButton){
        int need_steps;
        int bx = FIELD_WIDTH  / 2 - PX_SCALE * field->ball.x,
            by = FIELD_HEIGHT / 2 - PX_SCALE * field->ball.y + top_offset;
        int s_x = abs(bx - mouse_pointer.x());
        int s_y = abs(by - mouse_pointer.y());
        if(s_x > s_y)
            need_steps = s_x / PX_SCALE;
        else
            need_steps = s_y / PX_SCALE;
        bool old_penalty = field->penalty_mode;
        for(int i = 0; i < need_steps; i++){
            qDebug() << "Click!" << need_steps << "\n";
            qint32 key_num = get_key_from_coord(mouse_pointer.x(), mouse_pointer.y());
            if(key_num == Qt::Key_5){
                qDebug() << "Ball position!\n";
                return;
            }
            if(field->penalty_mode != old_penalty)
                return;
            QKeyEvent key(QEvent::KeyPress, key_num, Qt::NoModifier);
            QApplication::sendEvent(this, &key);
            if (!key.isAccepted()) qDebug() << "something wrong\n";
        }
    }
}

qint32 MainWindow::get_key_from_coord(int x, int y){
    int top_offset = ui->menuBar->height();
    int bx = FIELD_WIDTH  / 2 - PX_SCALE * field->ball.x,
        by = FIELD_HEIGHT / 2 - PX_SCALE * field->ball.y + top_offset;

    // Don't move - this is a ball-point
    if(x == bx && y == by) return Qt::Key_5;

    if(x <  bx && y >  by) return Qt::Key_1;
    if(x == bx && y >  by) return Qt::Key_2;
    if(x >  bx && y >  by) return Qt::Key_3;
    if(x <  bx && y == by) return Qt::Key_4;
    if(x >  bx && y == by) return Qt::Key_6;
    if(x <  bx && y <  by) return Qt::Key_7;
    if(x == bx && y <  by) return Qt::Key_8;
    if(x >  bx && y <  by) return Qt::Key_9;

    // just in case
    return Qt::Key_5;
}

int MainWindow::get_key_from_coord(int x, int y, int bx, int by){
    // Don't move - this is a ball-point
    if(x == bx && y == by) return 5;

    if(x <  bx && y >  by) return 1;
    if(x == bx && y >  by) return 2;
    if(x >  bx && y >  by) return 3;
    if(x <  bx && y == by) return 4;
    if(x >  bx && y == by) return 6;
    if(x <  bx && y <  by) return 7;
    if(x == bx && y <  by) return 8;
    if(x >  bx && y <  by) return 9;

    // just in case
    return 5;
}

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
        tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
//        QTextStream in(&file);
//        textEdit->setText(in.readAll());

        file.close();
    }
}

void MainWindow::save()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "",
    tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            // error message
        } else {
//            QTextStream stream(&file);
//            stream << textEdit->toPlainText();
//            stream.flush();
            file.close();
        }
    }
}

void MainWindow::new_field()
{
    delete field;
    field = new FootballField;
    this->repaint();
}

<|endoftext|>


<commit_before><commit_msg>[sensor] english<commit_after><|endoftext|>


<commit_before>/*
    Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>
      @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "approverdaemon.h"
#include "ktpapproverfactory.h"

#include <KAboutData>
#include <KLocale>
#include <KComponentData>
#include <KDEDModule>

#include <TelepathyQt/Types>
#include <TelepathyQt/Debug>
#include <TelepathyQt/ClientRegistrar>
#include <TelepathyQt/Channel>
#include <TelepathyQt/TextChannel>
#include <TelepathyQt/IncomingFileTransferChannel>
#include <TelepathyQt/IncomingStreamTubeChannel>

class KTpApproverModule : public KDEDModule
{
public:
    KTpApproverModule(QObject *parent, const QVariantList & args)
        : KDEDModule(parent)
    {
        Q_UNUSED(args);

        Tp::registerTypes();
        Tp::enableDebug(false);
        Tp::enableWarnings(true);

        Tp::AccountFactoryPtr accountFactory =
            Tp::AccountFactory::create(QDBusConnection::sessionBus());
        Tp::ConnectionFactoryPtr connectionFactory =
            Tp::ConnectionFactory::create(QDBusConnection::sessionBus());

        Tp::ChannelFactoryPtr channelFactory =
            Tp::ChannelFactory::create(QDBusConnection::sessionBus());
        channelFactory->addCommonFeatures(Tp::Channel::FeatureCore);
        channelFactory->addFeaturesForTextChats(Tp::Features()
                                                    << Tp::TextChannel::FeatureCore
                                                    << Tp::TextChannel::FeatureMessageQueue);
        channelFactory->addFeaturesForIncomingFileTransfers(
                Tp::IncomingFileTransferChannel::FeatureCore);

        channelFactory->addFeaturesForIncomingStreamTubes(
                    Tp::IncomingStreamTubeChannel::FeatureCore);

        Tp::ContactFactoryPtr contactFactory =
            Tp::ContactFactory::create(Tp::Features()
                                        << Tp::Contact::FeatureAlias
                                        << Tp::Contact::FeatureAvatarData);

        m_registrar = Tp::ClientRegistrar::create(accountFactory, connectionFactory,
                                                  channelFactory, contactFactory);
        m_registrar->registerClient(Tp::SharedPtr<ApproverDaemon>(new ApproverDaemon()),
                                    "KTp.Approver");
    }

    static inline KAboutData aboutData()
    {
        KAboutData aboutData("ktp-approver", "kded_ktp_approver", KLocalizedString(), "0.4",
                             KLocalizedString(), KAboutData::License_LGPL,
                             ki18nc("@info:credit", "(C) 2010, Collabora Ltd."));
        aboutData.addAuthor(ki18nc("@info:credit", "George Kiagiadakis"),
                            KLocalizedString(), "george.kiagiadakis@collabora.co.uk");
        return aboutData;
    }

private:
    Tp::ClientRegistrarPtr m_registrar;
};

K_PLUGIN_FACTORY_DEFINITION(KTpApproverFactory, registerPlugin<KTpApproverModule>();)
K_EXPORT_PLUGIN(KTpApproverFactory(KTpApproverModule::aboutData()))
<commit_msg>Bump version to 0.5<commit_after>/*
    Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>
      @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "approverdaemon.h"
#include "ktpapproverfactory.h"

#include <KAboutData>
#include <KLocale>
#include <KComponentData>
#include <KDEDModule>

#include <TelepathyQt/Types>
#include <TelepathyQt/Debug>
#include <TelepathyQt/ClientRegistrar>
#include <TelepathyQt/Channel>
#include <TelepathyQt/TextChannel>
#include <TelepathyQt/IncomingFileTransferChannel>
#include <TelepathyQt/IncomingStreamTubeChannel>

class KTpApproverModule : public KDEDModule
{
public:
    KTpApproverModule(QObject *parent, const QVariantList & args)
        : KDEDModule(parent)
    {
        Q_UNUSED(args);

        Tp::registerTypes();
        Tp::enableDebug(false);
        Tp::enableWarnings(true);

        Tp::AccountFactoryPtr accountFactory =
            Tp::AccountFactory::create(QDBusConnection::sessionBus());
        Tp::ConnectionFactoryPtr connectionFactory =
            Tp::ConnectionFactory::create(QDBusConnection::sessionBus());

        Tp::ChannelFactoryPtr channelFactory =
            Tp::ChannelFactory::create(QDBusConnection::sessionBus());
        channelFactory->addCommonFeatures(Tp::Channel::FeatureCore);
        channelFactory->addFeaturesForTextChats(Tp::Features()
                                                    << Tp::TextChannel::FeatureCore
                                                    << Tp::TextChannel::FeatureMessageQueue);
        channelFactory->addFeaturesForIncomingFileTransfers(
                Tp::IncomingFileTransferChannel::FeatureCore);

        channelFactory->addFeaturesForIncomingStreamTubes(
                    Tp::IncomingStreamTubeChannel::FeatureCore);

        Tp::ContactFactoryPtr contactFactory =
            Tp::ContactFactory::create(Tp::Features()
                                        << Tp::Contact::FeatureAlias
                                        << Tp::Contact::FeatureAvatarData);

        m_registrar = Tp::ClientRegistrar::create(accountFactory, connectionFactory,
                                                  channelFactory, contactFactory);
        m_registrar->registerClient(Tp::SharedPtr<ApproverDaemon>(new ApproverDaemon()),
                                    "KTp.Approver");
    }

    static inline KAboutData aboutData()
    {
        KAboutData aboutData("ktp-approver", "kded_ktp_approver", KLocalizedString(), "0.5",
                             KLocalizedString(), KAboutData::License_LGPL,
                             ki18nc("@info:credit", "(C) 2010, Collabora Ltd."));
        aboutData.addAuthor(ki18nc("@info:credit", "George Kiagiadakis"),
                            KLocalizedString(), "george.kiagiadakis@collabora.co.uk");
        return aboutData;
    }

private:
    Tp::ClientRegistrarPtr m_registrar;
};

K_PLUGIN_FACTORY_DEFINITION(KTpApproverFactory, registerPlugin<KTpApproverModule>();)
K_EXPORT_PLUGIN(KTpApproverFactory(KTpApproverModule::aboutData()))
<|endoftext|>


<commit_before><commit_msg>Minor doxygen documentation update<commit_after><|endoftext|>


<commit_before><commit_msg>Updating spacing<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS sb19 (1.4.648); FILE MERGED 2004/12/08 19:33:19 sb 1.4.648.3: RESYNC: (1.6-1.7); FILE MERGED 2004/10/11 16:34:22 sb 1.4.648.2: RESYNC: (1.4-1.6); FILE MERGED 2004/10/07 14:21:53 os 1.4.648.1: #110409# static base URL has gone<commit_after><|endoftext|>


<commit_before>/*** Copyright (c), The University of North Carolina            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* ixmsg.c - Xmessage communicator */

#include "rodsClient.hpp"
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"

rodsEnv myRodsEnv;
rErrMsg_t errMsg;
int  connectFlag = 0;
int
printIxmsgHelp( char *cmd ) {

    printf( "usage: %s s [-t ticketNum] [-n startingMessageNumber] [-r numOfReceivers] [-H header] [-M message] \n" , cmd );
    printf( "usage: %s r [-n NumberOfMessages] [-t tickefStreamtNum] [-s startingSequenceNumber] [-c conditionString]\n" , cmd );
    printf( "usage: %s t \n" , cmd );
    printf( "usage: %s d -t ticketNum \n" , cmd );
    printf( "usage: %s c -t ticketNum \n" , cmd );
    printf( "usage: %s c -t ticketNum -s sequenceNum \n" , cmd );
    printf( "    s: send messages. If no ticketNum is given, 1 is used \n" );
    printf( "    r: receive messages. If no ticketNum is given, 1 is used \n" );
    printf( "    t: create new message stream and get a new ticketNum \n" );
    printf( "    d: drop message Stream \n" );
    printf( "    c: clear message Stream \n" );
    printf( "    e: erase a message \n" );
    printReleaseInfo( "ixmsg" );
    exit( 1 );
}

int
sendIxmsg( rcComm_t **inconn, sendXmsgInp_t *sendXmsgInp ) {
    int status;
    int sleepSec = 1;
    rcComm_t *conn;

    conn = *inconn;

    while ( connectFlag == 0 ) {
        conn = rcConnectXmsg( &myRodsEnv, &errMsg );
        if ( conn == NULL ) {
            sleep( sleepSec );
            sleepSec = 2 * sleepSec;
            if ( sleepSec > 10 ) {
                sleepSec = 10;
            }
            continue;
        }
        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            fprintf( stderr, "clientLogin error...Will try again\n" );
            sleep( sleepSec );
            sleepSec = 2 * sleepSec;
            if ( sleepSec > 10 ) {
                sleepSec = 10;
            }
            continue;
        }
        *inconn = conn;
        connectFlag = 1;
    }
    status = rcSendXmsg( conn, sendXmsgInp );
    /*  rcDisconnect(conn); **/
    if ( status < 0 ) {
        fprintf( stderr, "rsSendXmsg error. status = %d\n", status );
        exit( 9 );
    }
    return( status );
}

int
main( int argc, char **argv ) {
    rcComm_t *conn = NULL;
    int status;
    int mNum = 0;
    int tNum = 1;
    int opt;
    int sNum = 0;
    int sleepSec = 1;
    int rNum = 1;
    char  msgBuf[4000];
    char  msgHdr[HEADER_TYPE_LEN];
    char  condStr[NAME_LEN];
    char myHostName[MAX_NAME_LEN];
    char cmd[10];

    getXmsgTicketInp_t getXmsgTicketInp;
    xmsgTicketInfo_t xmsgTicketInfo;
    xmsgTicketInfo_t *outXmsgTicketInfo;
    sendXmsgInp_t sendXmsgInp;
    rcvXmsgInp_t rcvXmsgInp;
    rcvXmsgOut_t *rcvXmsgOut = NULL;

    msgBuf[0] = '\0';
    strcpy( msgHdr, "ixmsg" );;
    myHostName[0] = '\0';
    condStr[0] = '\0';

    if ( argc < 2 ) {
        printIxmsgHelp( argv[0] );
        exit( 1 );
    }

    strncpy( cmd, argv[1], 9 );
    status = getRodsEnv( &myRodsEnv );
    if ( status < 0 ) {
        fprintf( stderr, "getRodsEnv error, status = %d\n", status );
        exit( 1 );
    }

    while ( ( opt = getopt( argc, argv, "ht:n:r:H:M:c:s:" ) ) != ( char )EOF ) {
        switch ( opt ) {
        case 't':
            tNum = atoi( optarg );
            break;
        case 'n':
            mNum = atoi( optarg );
            break;
        case 'r':
            rNum = atoi( optarg );
            break;
        case 's':
            sNum = atoi( optarg );
            break;
        case 'H':
            strncpy( msgHdr, optarg, HEADER_TYPE_LEN - 1 );
            break;
        case 'M':
            strncpy( msgBuf, optarg, 3999 );
            break;
        case 'c':
            strncpy( condStr, optarg, NAME_LEN - 1 );
            break;
        case 'h':
            printIxmsgHelp( argv[0] );
            exit( 0 );
            break;
        default:
            fprintf( stderr, "Error: Unknown Option\n" );
            exit( 1 );
            break;
        }
    }

    gethostname( myHostName, MAX_NAME_LEN );
    memset( &xmsgTicketInfo, 0, sizeof( xmsgTicketInfo ) );

    if ( !strcmp( cmd, "s" ) ) {
        memset( &sendXmsgInp, 0, sizeof( sendXmsgInp ) );
        xmsgTicketInfo.sendTicket = tNum;
        xmsgTicketInfo.rcvTicket = tNum;
        xmsgTicketInfo.flag = 1;
        sendXmsgInp.ticket = xmsgTicketInfo;
        snprintf( sendXmsgInp.sendAddr, NAME_LEN, "%s:%i", myHostName, getpid() );
        sendXmsgInp.sendXmsgInfo.numRcv = rNum;
        sendXmsgInp.sendXmsgInfo.msgNumber = mNum;
        strcpy( sendXmsgInp.sendXmsgInfo.msgType, msgHdr );
        sendXmsgInp.sendXmsgInfo.msg = msgBuf;

        if ( strlen( msgBuf ) > 0 ) {
            status = sendIxmsg( &conn, &sendXmsgInp );
            if ( connectFlag == 1 ) {
                rcDisconnect( conn );
            }
            if ( status < 0 ) {
                exit( 8 );
            }
            exit( 0 );
        }
        printf( "Message Header : %s\n", msgHdr );
        printf( "Message Address: %s\n", sendXmsgInp.sendAddr );
        while ( fgets( msgBuf, 3999, stdin ) != NULL ) {
            if ( strstr( msgBuf, "/EOM" ) == msgBuf ) {
                if ( connectFlag == 1 ) {
                    rcDisconnect( conn );
                }
                exit( 0 );
            }
            sendXmsgInp.sendXmsgInfo.msgNumber = mNum;
            if ( mNum != 0 ) {
                mNum++;
            }
            sendXmsgInp.sendXmsgInfo.msg = msgBuf;
            status = sendIxmsg( &conn, &sendXmsgInp );
            if ( status < 0 ) {
                if ( connectFlag == 1 ) {
                    rcDisconnect( conn );
                }
                exit( 8 );
            }
        }
        if ( connectFlag == 1 ) {
            rcDisconnect( conn );
        }
    }
    else if ( !strcmp( cmd, "r" ) ) {
        memset( &rcvXmsgInp, 0, sizeof( rcvXmsgInp ) );
        rcvXmsgInp.rcvTicket = tNum;
        /*      rcvXmsgInp.msgNumber = mNum; */

        if ( mNum == 0 ) {
            mNum--;
        }

        while ( mNum != 0 ) {
            if ( connectFlag == 0 ) {
                conn = rcConnectXmsg( &myRodsEnv, &errMsg );
                if ( conn == NULL ) {
                    sleep( sleepSec );
                    sleepSec = 2 * sleepSec;
                    if ( sleepSec > 10 ) {
                        sleepSec = 10;
                    }
                    continue;
                }
                status = clientLogin( conn );
                if ( status != 0 ) {
                    rcDisconnect( conn );
                    sleep( sleepSec );
                    sleepSec = 2 * sleepSec;
                    if ( sleepSec > 10 ) {
                        sleepSec = 10;
                    }
                    continue;
                }
                connectFlag = 1;
            }
            if ( strlen( condStr ) > 0 ) {
                sprintf( rcvXmsgInp.msgCondition, "(*XSEQNUM  >= %d) && (%s)", sNum, condStr );
            }
            else {
                sprintf( rcvXmsgInp.msgCondition, "*XSEQNUM >= %d ", sNum );
            }

            status = rcRcvXmsg( conn, &rcvXmsgInp, &rcvXmsgOut );
            /*        rcDisconnect(conn); */
            if ( status  >= 0 ) {
                printf( "%s:%s#%i::%s: %s",
                        rcvXmsgOut->sendUserName, rcvXmsgOut->sendAddr,
                        rcvXmsgOut->seqNumber, rcvXmsgOut->msgType, rcvXmsgOut->msg );
                if ( rcvXmsgOut->msg[strlen( rcvXmsgOut->msg ) - 1] != '\n' ) {
                    printf( "\n" );
                }
                sleepSec = 1;
                mNum--;
                sNum = rcvXmsgOut->seqNumber + 1;
                free( rcvXmsgOut->msg );
                free( rcvXmsgOut );
                rcvXmsgOut = NULL;
            }
            else {
                sleep( sleepSec );
                sleepSec = 2 * sleepSec;
                if ( sleepSec > 10 ) {
                    sleepSec = 10;
                }
            }

        }
        if ( connectFlag == 1 ) {
            rcDisconnect( conn );
        }
    }
    else if ( !strcmp( cmd, "t" ) ) {
        memset( &getXmsgTicketInp, 0, sizeof( getXmsgTicketInp ) );
        getXmsgTicketInp.flag = 1;

        // =-=-=-=-=-=-=-
        // initialize pluggable api table
        irods::api_entry_table&  api_tbl = irods::get_client_api_table();
        irods::pack_entry_table& pk_tbl  = irods::get_pack_table();
        init_api_table( api_tbl, pk_tbl );

        conn = rcConnectXmsg( &myRodsEnv, &errMsg );
        if ( conn == NULL ) {
            fprintf( stderr, "rcConnect error\n" );
            exit( 1 );
        }
        status = clientLogin( conn );
        if ( status != 0 ) {
            fprintf( stderr, "clientLogin error\n" );
            rcDisconnect( conn );
            exit( 7 );
        }
        status = rcGetXmsgTicket( conn, &getXmsgTicketInp, &outXmsgTicketInfo );
        rcDisconnect( conn );
        if ( status != 0 ) {
            fprintf( stderr, "rcGetXmsgTicket error. status = %d\n", status );
            exit( 8 );
        }
        printf( "Send Ticket Number= %i\n", outXmsgTicketInfo->sendTicket );
        printf( "Recv Ticket Number= %i\n", outXmsgTicketInfo->rcvTicket );
        printf( "Ticket Expiry Time= %i\n", outXmsgTicketInfo->expireTime );
        printf( "Ticket Flag       = %i\n", outXmsgTicketInfo->flag );
        free( outXmsgTicketInfo );
    }
    else if ( !strcmp( cmd, "c" ) || !strcmp( cmd, "d" ) || !strcmp( cmd, "e" ) ) {
        memset( &sendXmsgInp, 0, sizeof( sendXmsgInp ) );
        xmsgTicketInfo.sendTicket = tNum;
        xmsgTicketInfo.rcvTicket = tNum;
        xmsgTicketInfo.flag = 1;
        sendXmsgInp.ticket = xmsgTicketInfo;
        snprintf( sendXmsgInp.sendAddr, NAME_LEN, "%s:%i", myHostName, getpid() );
        sendXmsgInp.sendXmsgInfo.numRcv = rNum;
        if ( !strcmp( cmd, "e" ) ) {
            sendXmsgInp.sendXmsgInfo.msgNumber = sNum;
        }
        else {
            sendXmsgInp.sendXmsgInfo.msgNumber = mNum;
        }
        strcpy( sendXmsgInp.sendXmsgInfo.msgType, msgHdr );
        sendXmsgInp.sendXmsgInfo.msg = msgBuf;
        if ( !strcmp( cmd, "c" ) ) {
            sendXmsgInp.sendXmsgInfo.miscInfo = strdup( "CLEAR_STREAM" );
        }
        if ( !strcmp( cmd, "e" ) ) {
            sendXmsgInp.sendXmsgInfo.miscInfo = strdup( "ERASE_MESSAGE" );
        }
        else {
            sendXmsgInp.sendXmsgInfo.miscInfo = strdup( "DROP_STREAM" );
        }
        status = sendIxmsg( &conn, &sendXmsgInp );
        if ( connectFlag == 1 ) {
            rcDisconnect( conn );
        }
        if ( status < 0 ) {
            exit( 8 );
        }
        exit( 0 );
    }
    else {
        fprintf( stderr, "wrong option. Check with -h\n" );
        exit( 9 );
    }

    exit( 0 );
}
<commit_msg>[#1985] disabled advanced cli-svr nego in ixmsg<commit_after>/*** Copyright (c), The University of North Carolina            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* ixmsg.c - Xmessage communicator */

#include "rodsClient.hpp"
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"

rodsEnv myRodsEnv;
rErrMsg_t errMsg;
int  connectFlag = 0;
int
printIxmsgHelp( char *cmd ) {

    printf( "usage: %s s [-t ticketNum] [-n startingMessageNumber] [-r numOfReceivers] [-H header] [-M message] \n" , cmd );
    printf( "usage: %s r [-n NumberOfMessages] [-t tickefStreamtNum] [-s startingSequenceNumber] [-c conditionString]\n" , cmd );
    printf( "usage: %s t \n" , cmd );
    printf( "usage: %s d -t ticketNum \n" , cmd );
    printf( "usage: %s c -t ticketNum \n" , cmd );
    printf( "usage: %s c -t ticketNum -s sequenceNum \n" , cmd );
    printf( "    s: send messages. If no ticketNum is given, 1 is used \n" );
    printf( "    r: receive messages. If no ticketNum is given, 1 is used \n" );
    printf( "    t: create new message stream and get a new ticketNum \n" );
    printf( "    d: drop message Stream \n" );
    printf( "    c: clear message Stream \n" );
    printf( "    e: erase a message \n" );
    printReleaseInfo( "ixmsg" );
    exit( 1 );
}

int
sendIxmsg( rcComm_t **inconn, sendXmsgInp_t *sendXmsgInp ) {
    int status;
    int sleepSec = 1;
    rcComm_t *conn;

    conn = *inconn;

    while ( connectFlag == 0 ) {
        conn = rcConnectXmsg( &myRodsEnv, &errMsg );
        if ( conn == NULL ) {
            sleep( sleepSec );
            sleepSec = 2 * sleepSec;
            if ( sleepSec > 10 ) {
                sleepSec = 10;
            }
            continue;
        }
        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            fprintf( stderr, "clientLogin error...Will try again\n" );
            sleep( sleepSec );
            sleepSec = 2 * sleepSec;
            if ( sleepSec > 10 ) {
                sleepSec = 10;
            }
            continue;
        }
        *inconn = conn;
        connectFlag = 1;
    }
    status = rcSendXmsg( conn, sendXmsgInp );
    /*  rcDisconnect(conn); **/
    if ( status < 0 ) {
        fprintf( stderr, "rsSendXmsg error. status = %d\n", status );
        exit( 9 );
    }
    return( status );
}

int
main( int argc, char **argv ) {
    rcComm_t *conn = NULL;
    int status;
    int mNum = 0;
    int tNum = 1;
    int opt;
    int sNum = 0;
    int sleepSec = 1;
    int rNum = 1;
    char  msgBuf[4000];
    char  msgHdr[HEADER_TYPE_LEN];
    char  condStr[NAME_LEN];
    char myHostName[MAX_NAME_LEN];
    char cmd[10];

    getXmsgTicketInp_t getXmsgTicketInp;
    xmsgTicketInfo_t xmsgTicketInfo;
    xmsgTicketInfo_t *outXmsgTicketInfo;
    sendXmsgInp_t sendXmsgInp;
    rcvXmsgInp_t rcvXmsgInp;
    rcvXmsgOut_t *rcvXmsgOut = NULL;

    msgBuf[0] = '\0';
    strcpy( msgHdr, "ixmsg" );;
    myHostName[0] = '\0';
    condStr[0] = '\0';

    if ( argc < 2 ) {
        printIxmsgHelp( argv[0] );
        exit( 1 );
    }

    strncpy( cmd, argv[1], 9 );
    status = getRodsEnv( &myRodsEnv );
    if ( status < 0 ) {
        fprintf( stderr, "getRodsEnv error, status = %d\n", status );
        exit( 1 );
    }

    // DISABLE ADVANCED CLIENT-SERVER NEGOCIATION FOR XMSG CLIENT
    putenv("irodsClientServerNegotiation=''");
    // DISABLE ADVANCED CLIENT-SERVER NEGOCIATION FOR XMSG CLIENT

    while ( ( opt = getopt( argc, argv, "ht:n:r:H:M:c:s:" ) ) != ( char )EOF ) {
        switch ( opt ) {
        case 't':
            tNum = atoi( optarg );
            break;
        case 'n':
            mNum = atoi( optarg );
            break;
        case 'r':
            rNum = atoi( optarg );
            break;
        case 's':
            sNum = atoi( optarg );
            break;
        case 'H':
            strncpy( msgHdr, optarg, HEADER_TYPE_LEN - 1 );
            break;
        case 'M':
            strncpy( msgBuf, optarg, 3999 );
            break;
        case 'c':
            strncpy( condStr, optarg, NAME_LEN - 1 );
            break;
        case 'h':
            printIxmsgHelp( argv[0] );
            exit( 0 );
            break;
        default:
            fprintf( stderr, "Error: Unknown Option\n" );
            exit( 1 );
            break;
        }
    }

    gethostname( myHostName, MAX_NAME_LEN );
    memset( &xmsgTicketInfo, 0, sizeof( xmsgTicketInfo ) );

    if ( !strcmp( cmd, "s" ) ) {
        memset( &sendXmsgInp, 0, sizeof( sendXmsgInp ) );
        xmsgTicketInfo.sendTicket = tNum;
        xmsgTicketInfo.rcvTicket = tNum;
        xmsgTicketInfo.flag = 1;
        sendXmsgInp.ticket = xmsgTicketInfo;
        snprintf( sendXmsgInp.sendAddr, NAME_LEN, "%s:%i", myHostName, getpid() );
        sendXmsgInp.sendXmsgInfo.numRcv = rNum;
        sendXmsgInp.sendXmsgInfo.msgNumber = mNum;
        strcpy( sendXmsgInp.sendXmsgInfo.msgType, msgHdr );
        sendXmsgInp.sendXmsgInfo.msg = msgBuf;

        if ( strlen( msgBuf ) > 0 ) {
            status = sendIxmsg( &conn, &sendXmsgInp );
            if ( connectFlag == 1 ) {
                rcDisconnect( conn );
            }
            if ( status < 0 ) {
                exit( 8 );
            }
            exit( 0 );
        }
        printf( "Message Header : %s\n", msgHdr );
        printf( "Message Address: %s\n", sendXmsgInp.sendAddr );
        while ( fgets( msgBuf, 3999, stdin ) != NULL ) {
            if ( strstr( msgBuf, "/EOM" ) == msgBuf ) {
                if ( connectFlag == 1 ) {
                    rcDisconnect( conn );
                }
                exit( 0 );
            }
            sendXmsgInp.sendXmsgInfo.msgNumber = mNum;
            if ( mNum != 0 ) {
                mNum++;
            }
            sendXmsgInp.sendXmsgInfo.msg = msgBuf;
            status = sendIxmsg( &conn, &sendXmsgInp );
            if ( status < 0 ) {
                if ( connectFlag == 1 ) {
                    rcDisconnect( conn );
                }
                exit( 8 );
            }
        }
        if ( connectFlag == 1 ) {
            rcDisconnect( conn );
        }
    }
    else if ( !strcmp( cmd, "r" ) ) {
        memset( &rcvXmsgInp, 0, sizeof( rcvXmsgInp ) );
        rcvXmsgInp.rcvTicket = tNum;
        /*      rcvXmsgInp.msgNumber = mNum; */

        if ( mNum == 0 ) {
            mNum--;
        }

        while ( mNum != 0 ) {
            if ( connectFlag == 0 ) {
                conn = rcConnectXmsg( &myRodsEnv, &errMsg );
                if ( conn == NULL ) {
                    sleep( sleepSec );
                    sleepSec = 2 * sleepSec;
                    if ( sleepSec > 10 ) {
                        sleepSec = 10;
                    }
                    continue;
                }
                status = clientLogin( conn );
                if ( status != 0 ) {
                    rcDisconnect( conn );
                    sleep( sleepSec );
                    sleepSec = 2 * sleepSec;
                    if ( sleepSec > 10 ) {
                        sleepSec = 10;
                    }
                    continue;
                }
                connectFlag = 1;
            }
            if ( strlen( condStr ) > 0 ) {
                sprintf( rcvXmsgInp.msgCondition, "(*XSEQNUM  >= %d) && (%s)", sNum, condStr );
            }
            else {
                sprintf( rcvXmsgInp.msgCondition, "*XSEQNUM >= %d ", sNum );
            }

            status = rcRcvXmsg( conn, &rcvXmsgInp, &rcvXmsgOut );
            /*        rcDisconnect(conn); */
            if ( status  >= 0 ) {
                printf( "%s:%s#%i::%s: %s",
                        rcvXmsgOut->sendUserName, rcvXmsgOut->sendAddr,
                        rcvXmsgOut->seqNumber, rcvXmsgOut->msgType, rcvXmsgOut->msg );
                if ( rcvXmsgOut->msg[strlen( rcvXmsgOut->msg ) - 1] != '\n' ) {
                    printf( "\n" );
                }
                sleepSec = 1;
                mNum--;
                sNum = rcvXmsgOut->seqNumber + 1;
                free( rcvXmsgOut->msg );
                free( rcvXmsgOut );
                rcvXmsgOut = NULL;
            }
            else {
                sleep( sleepSec );
                sleepSec = 2 * sleepSec;
                if ( sleepSec > 10 ) {
                    sleepSec = 10;
                }
            }

        }
        if ( connectFlag == 1 ) {
            rcDisconnect( conn );
        }
    }
    else if ( !strcmp( cmd, "t" ) ) {
        memset( &getXmsgTicketInp, 0, sizeof( getXmsgTicketInp ) );
        getXmsgTicketInp.flag = 1;

        // =-=-=-=-=-=-=-
        // initialize pluggable api table
        irods::api_entry_table&  api_tbl = irods::get_client_api_table();
        irods::pack_entry_table& pk_tbl  = irods::get_pack_table();
        init_api_table( api_tbl, pk_tbl );

        conn = rcConnectXmsg( &myRodsEnv, &errMsg );
        if ( conn == NULL ) {
            fprintf( stderr, "rcConnect error\n" );
            exit( 1 );
        }
        status = clientLogin( conn );
        if ( status != 0 ) {
            fprintf( stderr, "clientLogin error\n" );
            rcDisconnect( conn );
            exit( 7 );
        }
        status = rcGetXmsgTicket( conn, &getXmsgTicketInp, &outXmsgTicketInfo );
        rcDisconnect( conn );
        if ( status != 0 ) {
            fprintf( stderr, "rcGetXmsgTicket error. status = %d\n", status );
            exit( 8 );
        }
        printf( "Send Ticket Number= %i\n", outXmsgTicketInfo->sendTicket );
        printf( "Recv Ticket Number= %i\n", outXmsgTicketInfo->rcvTicket );
        printf( "Ticket Expiry Time= %i\n", outXmsgTicketInfo->expireTime );
        printf( "Ticket Flag       = %i\n", outXmsgTicketInfo->flag );
        free( outXmsgTicketInfo );
    }
    else if ( !strcmp( cmd, "c" ) || !strcmp( cmd, "d" ) || !strcmp( cmd, "e" ) ) {
        memset( &sendXmsgInp, 0, sizeof( sendXmsgInp ) );
        xmsgTicketInfo.sendTicket = tNum;
        xmsgTicketInfo.rcvTicket = tNum;
        xmsgTicketInfo.flag = 1;
        sendXmsgInp.ticket = xmsgTicketInfo;
        snprintf( sendXmsgInp.sendAddr, NAME_LEN, "%s:%i", myHostName, getpid() );
        sendXmsgInp.sendXmsgInfo.numRcv = rNum;
        if ( !strcmp( cmd, "e" ) ) {
            sendXmsgInp.sendXmsgInfo.msgNumber = sNum;
        }
        else {
            sendXmsgInp.sendXmsgInfo.msgNumber = mNum;
        }
        strcpy( sendXmsgInp.sendXmsgInfo.msgType, msgHdr );
        sendXmsgInp.sendXmsgInfo.msg = msgBuf;
        if ( !strcmp( cmd, "c" ) ) {
            sendXmsgInp.sendXmsgInfo.miscInfo = strdup( "CLEAR_STREAM" );
        }
        if ( !strcmp( cmd, "e" ) ) {
            sendXmsgInp.sendXmsgInfo.miscInfo = strdup( "ERASE_MESSAGE" );
        }
        else {
            sendXmsgInp.sendXmsgInfo.miscInfo = strdup( "DROP_STREAM" );
        }
        status = sendIxmsg( &conn, &sendXmsgInp );
        if ( connectFlag == 1 ) {
            rcDisconnect( conn );
        }
        if ( status < 0 ) {
            exit( 8 );
        }
        exit( 0 );
    }
    else {
        fprintf( stderr, "wrong option. Check with -h\n" );
        exit( 9 );
    }

    exit( 0 );
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkOpenGLPolyDataMapper2D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkOpenGLPolyDataMapper2D.h"
#include <GL/gl.h>
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkOpenGLPolyDataMapper2D* vtkOpenGLPolyDataMapper2D::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLPolyDataMapper2D");
  if(ret)
    {
    return (vtkOpenGLPolyDataMapper2D*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkOpenGLPolyDataMapper2D;
}

void vtkOpenGLPolyDataMapper2D::RenderOpaqueGeometry(vtkViewport* viewport,
						     vtkActor2D* actor)
{
  int numPts;
  vtkPolyData *input= (vtkPolyData *)this->Input;
  int npts, j;
  vtkPoints *p, *displayPts;
  vtkCellArray *aPrim;
  vtkScalars *c=NULL;
  unsigned char *rgba;
	unsigned char color[4];
  int *pts;
  int cellScalars = 0;
  int cellNum = 0;

  vtkDebugMacro (<< "vtkOpenGLPolyDataMapper2D::Render");

  if ( input == NULL )
    {
    vtkErrorMacro(<< "No input!");
    return;
    }
  else
    {
    input->Update();
    numPts = input->GetNumberOfPoints();
    }

  if (numPts == 0)
    {
    vtkDebugMacro(<< "No points!");
    return;
    }

  if ( this->LookupTable == NULL )
    {
    this->CreateDefaultLookupTable();
    }

  //
  // if something has changed regenrate colors and display lists
  // if required
  //
  if ( this->GetMTime() > this->BuildTime ||
       input->GetMTime() > this->BuildTime ||
       this->LookupTable->GetMTime() > this->BuildTime ||
       actor->GetProperty()->GetMTime() > this->BuildTime)
    {
    // sets this->Colors as side effect
    this->GetColors();
    this->BuildTime.Modified();
    }

  // Get the position of the actor
  int *size = viewport->GetSize();
  int* actorPos =
    actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);

  // Set up the font color from the text actor
  float*  actorColor = actor->GetProperty()->GetColor();
  color[0] = (unsigned char) (actorColor[0] * 255.0);
  color[1] = (unsigned char) (actorColor[1] * 255.0);
  color[2] = (unsigned char) (actorColor[2] * 255.0);
  color[3] = (unsigned char) (255.0*actor->GetProperty()->GetOpacity());

  // Transform the points, if necessary
  p = input->GetPoints();
  if ( this->TransformCoordinate )
    {
    int *itmp;
    numPts = p->GetNumberOfPoints();
    displayPts = vtkPoints::New();
    displayPts->SetNumberOfPoints(numPts);
    for ( j=0; j < numPts; j++ )
      {
      this->TransformCoordinate->SetValue(p->GetPoint(j));
      itmp = this->TransformCoordinate->GetComputedViewportValue(viewport);
      displayPts->SetPoint(j,itmp[0], itmp[1], 0.0);
      }
    p = displayPts;
    }

  // Set up the coloring
  if ( this->Colors )
    {
    c = this->Colors;
    c->InitColorTraversal(actor->GetProperty()->GetOpacity(),
			  this->LookupTable, this->ColorMode);
    if (!input->GetPointData()->GetScalars())
      {
      cellScalars = 1;
      }
    }
  vtkDebugMacro(<< c);
  vtkDebugMacro(<< cellScalars);

  // set the colors for the foreground
  glColor4ubv(color);

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glLoadIdentity();
  glDisable( GL_LIGHTING);
  glOrtho(-actorPos[0],-actorPos[0] + size[0] - 1,
	  -actorPos[1], -actorPos[1] +size[1] -1, 0, 1);

  aPrim = input->GetPolys();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_POLYGON);
    for (j = 0; j < npts; j++)
      {
      if (c)
	{
	if (cellScalars)
	  {
	  rgba = c->GetColor(cellNum);
	  }
	else
	  {
	  rgba = c->GetColor(pts[j]);
	  }
	glColor4ubv(rgba);
	}
      glVertex2fv(p->GetPoint(pts[j]));
      }
    glEnd();
    }

  aPrim = input->GetLines();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_LINE_STRIP);
    for (j = 0; j < npts; j++)
      {
      if (c)
	{
	if (cellScalars)
	  {
	  rgba = c->GetColor(cellNum);
	  }
	else
	  {
	  rgba = c->GetColor(pts[j]);
	  }
	glColor4ubv(rgba);
	}
      glVertex2fv(p->GetPoint(pts[j]));
      }
    glEnd();
    }

  if ( this->TransformCoordinate )
    {
    p->Delete();
    }

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION);
  glPopMatrix();
  glMatrixMode( GL_MODELVIEW);
  glPopMatrix();
  glEnable( GL_LIGHTING);
}

<commit_msg>ENH: Added rendering of vertices.  Added line width and point size<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLPolyDataMapper2D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkOpenGLPolyDataMapper2D.h"
#include <GL/gl.h>
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkOpenGLPolyDataMapper2D* vtkOpenGLPolyDataMapper2D::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLPolyDataMapper2D");
  if(ret)
    {
    return (vtkOpenGLPolyDataMapper2D*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkOpenGLPolyDataMapper2D;
}

void vtkOpenGLPolyDataMapper2D::RenderOpaqueGeometry(vtkViewport* viewport,
						     vtkActor2D* actor)
{
  int numPts;
  vtkPolyData *input= (vtkPolyData *)this->Input;
  int npts, j;
  vtkPoints *p, *displayPts;
  vtkCellArray *aPrim;
  vtkScalars *c=NULL;
  unsigned char *rgba;
	unsigned char color[4];
  int *pts;
  int cellScalars = 0;
  int cellNum = 0;

  vtkDebugMacro (<< "vtkOpenGLPolyDataMapper2D::Render");

  if ( input == NULL )
    {
    vtkErrorMacro(<< "No input!");
    return;
    }
  else
    {
    input->Update();
    numPts = input->GetNumberOfPoints();
    }

  if (numPts == 0)
    {
    vtkDebugMacro(<< "No points!");
    return;
    }

  if ( this->LookupTable == NULL )
    {
    this->CreateDefaultLookupTable();
    }

  //
  // if something has changed regenrate colors and display lists
  // if required
  //
  if ( this->GetMTime() > this->BuildTime ||
       input->GetMTime() > this->BuildTime ||
       this->LookupTable->GetMTime() > this->BuildTime ||
       actor->GetProperty()->GetMTime() > this->BuildTime)
    {
    // sets this->Colors as side effect
    this->GetColors();
    this->BuildTime.Modified();
    }

  // Get the position of the actor
  int *size = viewport->GetSize();
  int* actorPos =
    actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);

  // Set up the font color from the text actor
  float*  actorColor = actor->GetProperty()->GetColor();
  color[0] = (unsigned char) (actorColor[0] * 255.0);
  color[1] = (unsigned char) (actorColor[1] * 255.0);
  color[2] = (unsigned char) (actorColor[2] * 255.0);
  color[3] = (unsigned char) (255.0*actor->GetProperty()->GetOpacity());

  // Transform the points, if necessary
  p = input->GetPoints();
  if ( this->TransformCoordinate )
    {
    int *itmp;
    numPts = p->GetNumberOfPoints();
    displayPts = vtkPoints::New();
    displayPts->SetNumberOfPoints(numPts);
    for ( j=0; j < numPts; j++ )
      {
      this->TransformCoordinate->SetValue(p->GetPoint(j));
      itmp = this->TransformCoordinate->GetComputedViewportValue(viewport);
      displayPts->SetPoint(j,itmp[0], itmp[1], 0.0);
      }
    p = displayPts;
    }

  // Set up the coloring
  if ( this->Colors )
    {
    c = this->Colors;
    c->InitColorTraversal(actor->GetProperty()->GetOpacity(),
			  this->LookupTable, this->ColorMode);
    if (!input->GetPointData()->GetScalars())
      {
      cellScalars = 1;
      }
    }
  vtkDebugMacro(<< c);
  vtkDebugMacro(<< cellScalars);

  // set the colors for the foreground
  glColor4ubv(color);

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glLoadIdentity();
  glDisable( GL_LIGHTING);
  glOrtho(-actorPos[0],-actorPos[0] + size[0] - 1,
	  -actorPos[1], -actorPos[1] +size[1] -1, 0, 1);

  aPrim = input->GetPolys();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_POLYGON);
    for (j = 0; j < npts; j++)
      {
      if (c)
	{
	if (cellScalars)
	  {
	  rgba = c->GetColor(cellNum);
	  }
	else
	  {
	  rgba = c->GetColor(pts[j]);
	  }
	glColor4ubv(rgba);
	}
      glVertex2fv(p->GetPoint(pts[j]));
      }
    glEnd();
    }

  // Set the LineWidth
  glLineWidth(actor->GetProperty()->GetLineWidth());

  aPrim = input->GetLines();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_LINE_STRIP);
    for (j = 0; j < npts; j++)
      {
      if (c)
	{
	if (cellScalars)
	  {
	  rgba = c->GetColor(cellNum);
	  }
	else
	  {
	  rgba = c->GetColor(pts[j]);
	  }
	glColor4ubv(rgba);
	}
      glVertex2fv(p->GetPoint(pts[j]));
      }
    glEnd();
    }

  // Set the PointSize
  glPointSize(actor->GetProperty()->GetPointSize());

  aPrim = input->GetVerts();
  glBegin(GL_POINTS);
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    for (j = 0; j < npts; j++)
      {
      if (c)
	{
	if (cellScalars)
	  {
	  rgba = c->GetColor(cellNum);
	  }
	else
	  {
	  rgba = c->GetColor(pts[j]);
	  }
	glColor4ubv(rgba);
	}
      glVertex2fv(p->GetPoint(pts[j]));
      }
    }
  glEnd();

  if ( this->TransformCoordinate )
    {
    p->Delete();
    }

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION);
  glPopMatrix();
  glMatrixMode( GL_MODELVIEW);
  glPopMatrix();
  glEnable( GL_LIGHTING);
}

<|endoftext|>


<commit_before>/*
   Copyright (c) 2005, 2011, Oracle and/or its affiliates.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

#include "sql_priv.h"
#include "sql_binlog.h"
#include "sql_parse.h"                          // check_global_access
#include "sql_acl.h"                            // *_ACL
#include "rpl_rli.h"
#include "base64.h"
#include "slave.h"                              // apply_event_and_update_pos
#include "log_event.h"                          // Format_description_log_event,
                                                // EVENT_LEN_OFFSET,
                                                // EVENT_TYPE_OFFSET,
                                                // FORMAT_DESCRIPTION_LOG_EVENT,
                                                // START_EVENT_V3,
                                                // Log_event_type,
                                                // Log_event
/**
  Execute a BINLOG statement.

  To execute the BINLOG command properly the server needs to know
  which format the BINLOG command's event is in.  Therefore, the first
  BINLOG statement seen must be a base64 encoding of the
  Format_description_log_event, as outputted by mysqlbinlog.  This
  Format_description_log_event is cached in
  rli->description_event_for_exec.

  @param thd Pointer to THD object for the client thread executing the
  statement.
*/

void mysql_client_binlog_statement(THD* thd)
{
  ulonglong save_skip_replication;
  DBUG_ENTER("mysql_client_binlog_statement");
  DBUG_PRINT("info",("binlog base64: '%*s'",
                     (int) (thd->lex->comment.length < 2048 ?
                            thd->lex->comment.length : 2048),
                     thd->lex->comment.str));

  if (check_global_access(thd, SUPER_ACL))
    DBUG_VOID_RETURN;

  size_t coded_len= thd->lex->comment.length;
  if (!coded_len)
  {
    my_error(ER_SYNTAX_ERROR, MYF(0));
    DBUG_VOID_RETURN;
  }
  size_t decoded_len= base64_needed_decoded_length(coded_len);

  /*
    option_bits will be changed when applying the event. But we don't expect
    it be changed permanently after BINLOG statement, so backup it first.
    It will be restored at the end of this function.
  */
  ulonglong thd_options= thd->variables.option_bits;

  /*
    Allocation
  */

  /*
    If we do not have a Format_description_event, we create a dummy
    one here.  In this case, the first event we read must be a
    Format_description_event.
  */
  my_bool have_fd_event= TRUE;
  int err;
  Relay_log_info *rli;
  rli= thd->rli_fake;
  if (!rli)
  {
    rli= thd->rli_fake= new Relay_log_info(FALSE);
#ifdef HAVE_valgrind
    rli->is_fake= TRUE;
#endif
    have_fd_event= FALSE;
  }
  if (rli && !rli->relay_log.description_event_for_exec)
  {
    rli->relay_log.description_event_for_exec=
      new Format_description_log_event(4);
    have_fd_event= FALSE;
  }

  const char *error= 0;
  char *buf= (char *) my_malloc(decoded_len, MYF(MY_WME));
  Log_event *ev = 0;

  /*
    Out of memory check
  */
  if (!(rli &&
        rli->relay_log.description_event_for_exec &&
        buf))
  {
    my_error(ER_OUTOFMEMORY, MYF(0), 1);  /* needed 1 bytes */
    goto end;
  }

  rli->sql_thd= thd;
  rli->no_storage= TRUE;

  for (char const *strptr= thd->lex->comment.str ;
       strptr < thd->lex->comment.str + thd->lex->comment.length ; )
  {
    char const *endptr= 0;
    int bytes_decoded= base64_decode(strptr, coded_len, buf, &endptr);

#ifndef HAVE_valgrind
      /*
        This debug printout should not be used for valgrind builds
        since it will read from unassigned memory.
      */
    DBUG_PRINT("info",
               ("bytes_decoded: %d  strptr: 0x%lx  endptr: 0x%lx ('%c':%d)",
                bytes_decoded, (long) strptr, (long) endptr, *endptr,
                *endptr));
#endif

    if (bytes_decoded < 0)
    {
      my_error(ER_BASE64_DECODE_ERROR, MYF(0));
      goto end;
    }
    else if (bytes_decoded == 0)
      break; // If no bytes where read, the string contained only whitespace

    DBUG_ASSERT(bytes_decoded > 0);
    DBUG_ASSERT(endptr > strptr);
    coded_len-= endptr - strptr;
    strptr= endptr;

    /*
      Now we have one or more events stored in the buffer. The size of
      the buffer is computed based on how much base64-encoded data
      there were, so there should be ample space for the data (maybe
      even too much, since a statement can consist of a considerable
      number of events).

      TODO: Switch to use a stream-based base64 encoder/decoder in
      order to be able to read exactly what is necessary.
    */

    DBUG_PRINT("info",("binlog base64 decoded_len: %lu  bytes_decoded: %d",
                       (ulong) decoded_len, bytes_decoded));

    /*
      Now we start to read events of the buffer, until there are no
      more.
    */
    for (char *bufptr= buf ; bytes_decoded > 0 ; )
    {
      /*
        Checking that the first event in the buffer is not truncated.
      */
      ulong event_len;
      if (bytes_decoded < EVENT_LEN_OFFSET + 4 ||
          (event_len= uint4korr(bufptr + EVENT_LEN_OFFSET)) >
           (uint) bytes_decoded)
      {
        my_error(ER_SYNTAX_ERROR, MYF(0));
        goto end;
      }
      DBUG_PRINT("info", ("event_len=%lu, bytes_decoded=%d",
                          event_len, bytes_decoded));

      /*
        If we have not seen any Format_description_event, then we must
        see one; it is the only statement that can be read in base64
        without a prior Format_description_event.
      */
      if (!have_fd_event)
      {
        int type = (uchar)bufptr[EVENT_TYPE_OFFSET];
        if (type == FORMAT_DESCRIPTION_EVENT || type == START_EVENT_V3)
          have_fd_event= TRUE;
        else
        {
          my_error(ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT,
                   MYF(0), Log_event::get_type_str((Log_event_type)type));
          goto end;
        }
      }

      ev= Log_event::read_log_event(bufptr, event_len, &error,
                                    rli->relay_log.description_event_for_exec,
                                    0);

      DBUG_PRINT("info",("binlog base64 err=%s", error));
      if (!ev)
      {
        /*
          This could actually be an out-of-memory, but it is more likely
          causes by a bad statement
        */
        my_error(ER_SYNTAX_ERROR, MYF(0));
        goto end;
      }

      bytes_decoded -= event_len;
      bufptr += event_len;

      DBUG_PRINT("info",("ev->get_type_code()=%d", ev->get_type_code()));
      ev->thd= thd;
      /*
        We go directly to the application phase, since we don't need
        to check if the event shall be skipped or not.

        Neither do we have to update the log positions, since that is
        not used at all: the rli_fake instance is used only for error
        reporting.
      */
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
      save_skip_replication= thd->variables.option_bits&OPTION_SKIP_REPLICATION;
      thd->variables.option_bits=
        (thd->variables.option_bits & ~OPTION_SKIP_REPLICATION) |
        (ev->flags & LOG_EVENT_SKIP_REPLICATION_F ?
         OPTION_SKIP_REPLICATION : 0);

      err= ev->apply_event(rli);

      thd->variables.option_bits=
        (thd->variables.option_bits & ~OPTION_SKIP_REPLICATION) |
        save_skip_replication;
#else
      err= 0;
#endif
      /*
        Format_description_log_event should not be deleted because it
        will be used to read info about the relay log's format; it
        will be deleted when the SQL thread does not need it,
        i.e. when this thread terminates.
      */
      if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT)
        delete ev;
      ev= 0;
      if (err)
      {
        /*
          TODO: Maybe a better error message since the BINLOG statement
          now contains several events.
        */
        my_error(ER_UNKNOWN_ERROR, MYF(0));
        goto end;
      }
    }
  }

  DBUG_PRINT("info",("binlog base64 execution finished successfully"));
  my_ok(thd);

end:
  thd->variables.option_bits= thd_options;
  rli->slave_close_thread_tables(thd);
  my_free(buf);
  DBUG_VOID_RETURN;
}
<commit_msg>compilation warning: unused variable<commit_after>/*
   Copyright (c) 2005, 2011, Oracle and/or its affiliates.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

#include "sql_priv.h"
#include "sql_binlog.h"
#include "sql_parse.h"                          // check_global_access
#include "sql_acl.h"                            // *_ACL
#include "rpl_rli.h"
#include "base64.h"
#include "slave.h"                              // apply_event_and_update_pos
#include "log_event.h"                          // Format_description_log_event,
                                                // EVENT_LEN_OFFSET,
                                                // EVENT_TYPE_OFFSET,
                                                // FORMAT_DESCRIPTION_LOG_EVENT,
                                                // START_EVENT_V3,
                                                // Log_event_type,
                                                // Log_event
/**
  Execute a BINLOG statement.

  To execute the BINLOG command properly the server needs to know
  which format the BINLOG command's event is in.  Therefore, the first
  BINLOG statement seen must be a base64 encoding of the
  Format_description_log_event, as outputted by mysqlbinlog.  This
  Format_description_log_event is cached in
  rli->description_event_for_exec.

  @param thd Pointer to THD object for the client thread executing the
  statement.
*/

void mysql_client_binlog_statement(THD* thd)
{
  DBUG_ENTER("mysql_client_binlog_statement");
  DBUG_PRINT("info",("binlog base64: '%*s'",
                     (int) (thd->lex->comment.length < 2048 ?
                            thd->lex->comment.length : 2048),
                     thd->lex->comment.str));

  if (check_global_access(thd, SUPER_ACL))
    DBUG_VOID_RETURN;

  size_t coded_len= thd->lex->comment.length;
  if (!coded_len)
  {
    my_error(ER_SYNTAX_ERROR, MYF(0));
    DBUG_VOID_RETURN;
  }
  size_t decoded_len= base64_needed_decoded_length(coded_len);

  /*
    option_bits will be changed when applying the event. But we don't expect
    it be changed permanently after BINLOG statement, so backup it first.
    It will be restored at the end of this function.
  */
  ulonglong thd_options= thd->variables.option_bits;

  /*
    Allocation
  */

  /*
    If we do not have a Format_description_event, we create a dummy
    one here.  In this case, the first event we read must be a
    Format_description_event.
  */
  my_bool have_fd_event= TRUE;
  int err;
  Relay_log_info *rli;
  rli= thd->rli_fake;
  if (!rli)
  {
    rli= thd->rli_fake= new Relay_log_info(FALSE);
#ifdef HAVE_valgrind
    rli->is_fake= TRUE;
#endif
    have_fd_event= FALSE;
  }
  if (rli && !rli->relay_log.description_event_for_exec)
  {
    rli->relay_log.description_event_for_exec=
      new Format_description_log_event(4);
    have_fd_event= FALSE;
  }

  const char *error= 0;
  char *buf= (char *) my_malloc(decoded_len, MYF(MY_WME));
  Log_event *ev = 0;

  /*
    Out of memory check
  */
  if (!(rli &&
        rli->relay_log.description_event_for_exec &&
        buf))
  {
    my_error(ER_OUTOFMEMORY, MYF(0), 1);  /* needed 1 bytes */
    goto end;
  }

  rli->sql_thd= thd;
  rli->no_storage= TRUE;

  for (char const *strptr= thd->lex->comment.str ;
       strptr < thd->lex->comment.str + thd->lex->comment.length ; )
  {
    char const *endptr= 0;
    int bytes_decoded= base64_decode(strptr, coded_len, buf, &endptr);

#ifndef HAVE_valgrind
      /*
        This debug printout should not be used for valgrind builds
        since it will read from unassigned memory.
      */
    DBUG_PRINT("info",
               ("bytes_decoded: %d  strptr: 0x%lx  endptr: 0x%lx ('%c':%d)",
                bytes_decoded, (long) strptr, (long) endptr, *endptr,
                *endptr));
#endif

    if (bytes_decoded < 0)
    {
      my_error(ER_BASE64_DECODE_ERROR, MYF(0));
      goto end;
    }
    else if (bytes_decoded == 0)
      break; // If no bytes where read, the string contained only whitespace

    DBUG_ASSERT(bytes_decoded > 0);
    DBUG_ASSERT(endptr > strptr);
    coded_len-= endptr - strptr;
    strptr= endptr;

    /*
      Now we have one or more events stored in the buffer. The size of
      the buffer is computed based on how much base64-encoded data
      there were, so there should be ample space for the data (maybe
      even too much, since a statement can consist of a considerable
      number of events).

      TODO: Switch to use a stream-based base64 encoder/decoder in
      order to be able to read exactly what is necessary.
    */

    DBUG_PRINT("info",("binlog base64 decoded_len: %lu  bytes_decoded: %d",
                       (ulong) decoded_len, bytes_decoded));

    /*
      Now we start to read events of the buffer, until there are no
      more.
    */
    for (char *bufptr= buf ; bytes_decoded > 0 ; )
    {
      /*
        Checking that the first event in the buffer is not truncated.
      */
      ulong event_len;
      if (bytes_decoded < EVENT_LEN_OFFSET + 4 ||
          (event_len= uint4korr(bufptr + EVENT_LEN_OFFSET)) >
           (uint) bytes_decoded)
      {
        my_error(ER_SYNTAX_ERROR, MYF(0));
        goto end;
      }
      DBUG_PRINT("info", ("event_len=%lu, bytes_decoded=%d",
                          event_len, bytes_decoded));

      /*
        If we have not seen any Format_description_event, then we must
        see one; it is the only statement that can be read in base64
        without a prior Format_description_event.
      */
      if (!have_fd_event)
      {
        int type = (uchar)bufptr[EVENT_TYPE_OFFSET];
        if (type == FORMAT_DESCRIPTION_EVENT || type == START_EVENT_V3)
          have_fd_event= TRUE;
        else
        {
          my_error(ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT,
                   MYF(0), Log_event::get_type_str((Log_event_type)type));
          goto end;
        }
      }

      ev= Log_event::read_log_event(bufptr, event_len, &error,
                                    rli->relay_log.description_event_for_exec,
                                    0);

      DBUG_PRINT("info",("binlog base64 err=%s", error));
      if (!ev)
      {
        /*
          This could actually be an out-of-memory, but it is more likely
          causes by a bad statement
        */
        my_error(ER_SYNTAX_ERROR, MYF(0));
        goto end;
      }

      bytes_decoded -= event_len;
      bufptr += event_len;

      DBUG_PRINT("info",("ev->get_type_code()=%d", ev->get_type_code()));
      ev->thd= thd;
      /*
        We go directly to the application phase, since we don't need
        to check if the event shall be skipped or not.

        Neither do we have to update the log positions, since that is
        not used at all: the rli_fake instance is used only for error
        reporting.
      */
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
      ulonglong save_skip_replication=
                        thd->variables.option_bits & OPTION_SKIP_REPLICATION;
      thd->variables.option_bits=
        (thd->variables.option_bits & ~OPTION_SKIP_REPLICATION) |
        (ev->flags & LOG_EVENT_SKIP_REPLICATION_F ?
         OPTION_SKIP_REPLICATION : 0);

      err= ev->apply_event(rli);

      thd->variables.option_bits=
        (thd->variables.option_bits & ~OPTION_SKIP_REPLICATION) |
        save_skip_replication;
#else
      err= 0;
#endif
      /*
        Format_description_log_event should not be deleted because it
        will be used to read info about the relay log's format; it
        will be deleted when the SQL thread does not need it,
        i.e. when this thread terminates.
      */
      if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT)
        delete ev;
      ev= 0;
      if (err)
      {
        /*
          TODO: Maybe a better error message since the BINLOG statement
          now contains several events.
        */
        my_error(ER_UNKNOWN_ERROR, MYF(0));
        goto end;
      }
    }
  }

  DBUG_PRINT("info",("binlog base64 execution finished successfully"));
  my_ok(thd);

end:
  thd->variables.option_bits= thd_options;
  rli->slave_close_thread_tables(thd);
  my_free(buf);
  DBUG_VOID_RETURN;
}
<|endoftext|>