<commit_before>#include "converterconfigurationdialog.h"
#include "checkboxdelegate.h"
#include "cmdlinehighlighterdelegate.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QMessageBox>
#include <QDialogButtonBox>
#include <QHeaderView>
#include <QDebug>
#include <QApplication>

ConverterConfigurationDialog::ConverterConfigurationDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f)
{
    // allocate
    auto headingLabel = new QLabel("Configure External Converters");
    mainConverterLocationLabel = new QLabel("Location of Main Converter:");
    mainConverterLocationEdit = new FancyLineEdit;
    contextMenu = new QMenu(this);
    contextToolBar = new QToolBar(this);
    browseButton = new QPushButton("Browse ...");
    additionalConvertersLabel = new QLabel("Additional converters:");
    auto stdButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    auto mainLayout = new QVBoxLayout;
    auto mainConverterLayout = new QHBoxLayout;

    // set model
    tableView.setModel(&convertersModel);

    // configure view
    tableView.verticalHeader()->setHidden(true);
    tableView.setSelectionMode(QAbstractItemView::SingleSelection);
    tableView.setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView.setContextMenuPolicy(Qt::CustomContextMenu);
    tableView.horizontalHeader()->setStretchLastSection(true);

    // configure menu & toolbar
    initMenu();
    initToolBar();
    contextToolBar->hide();

    // configure fonts
    QFont defaultFont{qApp->font()};
    QFont heading2Font{defaultFont};
    QFont heading1Font{defaultFont};
    heading2Font.setPointSize(defaultFont.pointSize() + 2);
    heading1Font.setPointSize(defaultFont.pointSize() + 4);

    // configure widgets
    headingLabel->setFont(heading1Font);
    headingLabel->setAlignment(Qt::AlignHCenter);
    mainConverterLocationEdit->hideEditButton();
    mainConverterLocationLabel->setFont(heading2Font);
    additionalConvertersLabel->setFont(heading2Font);

    // attach widgets to main layout
    mainLayout->addWidget(headingLabel);
    mainLayout->addSpacing(6);
    mainLayout->addWidget(mainConverterLocationLabel);
    mainConverterLayout->addWidget(mainConverterLocationEdit);
    mainConverterLayout->addWidget(browseButton);
    mainLayout->addLayout(mainConverterLayout);
    mainLayout->addSpacing(6);
    mainLayout->addWidget(additionalConvertersLabel);
    mainLayout->addWidget(&tableView);
    mainLayout->addWidget(stdButtons);
    setLayout(mainLayout);

    // hide unnecessary columns
    tableView.setColumnHidden(0, true);
    tableView.setColumnHidden(3, true);
    tableView.setColumnHidden(6, true);
    tableView.setColumnHidden(9, true);
    tableView.setColumnHidden(10, true);

    // set delegates
    tableView.setItemDelegateForColumn(8, new CmdLineHighlighterDelegate(this));
    tableView.setItemDelegateForColumn(1, new CheckBoxDelegate(this));

    // connect signals / slots
    connect(mainConverterLocationEdit, &QLineEdit::editingFinished, this, [this] {
       mainConverterPath = mainConverterLocationEdit->text();
    });
    connect(browseButton, &QPushButton::clicked, this, &ConverterConfigurationDialog::promptForResamplerLocation);
    connect(&tableView, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){
        contextMenu->popup(QPoint{this->mapToGlobal(pos).x(), this->mapToGlobal(pos).y() + contextMenu->sizeHint().height()});
    });
    connect(&tableView, &QTableView::clicked, this, [this](const QModelIndex& modelIndex) {
        QPoint p{tableView.columnViewportPosition(modelIndex.column()) , tableView.rowViewportPosition(modelIndex.row())};
        contextToolBar->move(p + QPoint{0, (int)tableView.geometry().top() + contextToolBar->sizeHint().height() * 3} );
        contextToolBar->show();
        contextToolBar->raise();
    });
    connect(stdButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(stdButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);
}

void ConverterConfigurationDialog::initMenu() {
    contextMenu->addAction("New", [this] {
       onNewRequested(tableView.currentIndex());
    }, QKeySequence::New);

    contextMenu->addAction("Edit ...", [this] {
       onEditRequested(tableView.currentIndex());
    });

    contextMenu->addAction("Clone", [this] {
       onCloneRequested(tableView.currentIndex());
    }, QKeySequence::Copy);

    contextMenu->addAction("Delete", [this] {
       onDeleteRequested(tableView.currentIndex());
    }, {QKeySequence::Delete});

    contextMenu->addAction("Move Up", [this] {
        onMoveUpRequested(tableView.currentIndex());
    });

    contextMenu->addAction("Move Down", [this] {
        onMoveDownRequested(tableView.currentIndex());
    });

}

void ConverterConfigurationDialog::initToolBar() {
    contextToolBar->addAction("New", [this] {
       onNewRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Edit ...", [this] {
       onEditRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Clone", [this] {
       onCloneRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Delete", [this] {
       onDeleteRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Move Up", [this] {
        onMoveUpRequested(tableView.currentIndex());
        //contextToolBar->hide();
    });

    qDebug() << contextToolBar->addAction("Move Down", [this] {
        onMoveDownRequested(tableView.currentIndex());
        //contextToolBar->hide();
    });

    contextToolBar->setContentsMargins(0, 0, 0, 0);
    contextToolBar->setMinimumWidth(tableView.width() / 2);
    contextToolBar->setMaximumWidth(tableView.width());

}

void ConverterConfigurationDialog::showEvent(QShowEvent* event) {

    if(mainConverterPath.isEmpty() || !QFile::exists(mainConverterPath)) {
       promptForResamplerLocation();
    }

    mainConverterLocationLabel->setText(QString{"Location of Main Converter (%1):"}.arg(expectedMainConverter));
    mainConverterLocationEdit->setText(mainConverterPath);

    QDialog::showEvent(event);
}

void ConverterConfigurationDialog::resizeEvent(QResizeEvent *event)
{
    int tw = event->size().width();

    static const QVector<double> columnWidths {
        0,      /* "Priority" */
        10,     /* "Enabled" */
        20,     /* "Name" */
        0 ,     /* "Comment" */
        12,     /* "Input File Extension" */
        12,     /* "Output File Extension" */
        0 ,     /* "Executable" */
        20,     /* "Executable Path" */
        20,     /* "Command Line" */
        0 ,     /* "Download Locations" */
        0      /* "Operating Systems" */
    };

    for(int col = 0; col < convertersModel.columnCount({}) - 1; col++) {
        tableView.horizontalHeader()->resizeSection(col, tw * columnWidths.at(col)/100.0);
    }

    tableView.horizontalHeader()->setHidden(false);

    QDialog::resizeEvent(event);
}

QVector<ConverterDefinition> ConverterConfigurationDialog::getConverterDefinitions() const
{
    return convertersModel.getConverterDefinitions();
}

void ConverterConfigurationDialog::setConverterDefinitions(const QVector<ConverterDefinition> &value)
{
    convertersModel.setConverterDefinitions(value);
}

void ConverterConfigurationDialog::promptForResamplerLocation() {
    QString s("Please locate the file: ");
    s.append(expectedMainConverter);

#if defined (Q_OS_WIN)
    QString filter = "*.exe";
#else
    QString filter = "";
#endif

    QString cp = QFileDialog::getOpenFileName(this, s, mainConverterPath,  filter);

    if(!cp.isNull()) {
        mainConverterPath = cp;
        if(mainConverterPath.lastIndexOf(expectedMainConverter, -1, Qt::CaseInsensitive) == -1) { // safeguard against wrong executable being configured
            mainConverterPath.clear();
            QMessageBox::warning(this, tr("Converter Location"), tr("That is not the right program!\n"), QMessageBox::Ok);
        }
    }
}

QString ConverterConfigurationDialog::getMainConverterPath() const
{
    return mainConverterPath;
}

void ConverterConfigurationDialog::setMainConverterPath(const QString &value)
{
    mainConverterPath = value;
}

QString ConverterConfigurationDialog::getExpectedMainConverter() const
{
    return expectedMainConverter;
}

void ConverterConfigurationDialog::setExpectedMainConverter(const QString &value)
{
    expectedMainConverter = value;
    // set tooltips
    mainConverterLocationLabel->setToolTip(QString{"Please enter the location of %1 in the box below.\n"
                                           "(%1 is the command-line audio converter that Ferocious was designed to work with.)"
                                           }.arg(expectedMainConverter));
    mainConverterLocationEdit->setToolTip(QString{"Location of %1\n"
                                          "Note: you can also use drag-and-drop, or the 'Browse' button"}.arg(expectedMainConverter));
    browseButton->setToolTip(QString{"Browse to location of %1"}.arg(expectedMainConverter));
    additionalConvertersLabel->setToolTip("Use the table below to cofigure additional converters for specialized file formats.");

}

void ConverterConfigurationDialog::onNewRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 0 )
        return;

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        converterDefinitions.insert(row, {});
        convertersModel.setConverterDefinitions(converterDefinitions);
    }
}

void ConverterConfigurationDialog::onEditRequested(const QModelIndex& modelIndex)
{
    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if (converterDefinitions.isEmpty())
        return;

    int row = modelIndex.row();

    if (row < 0)
        return;

    auto dlg = new ConverterConfigurationEditDialog(this);
    if(row < converterDefinitions.count()) {
        dlg->setConverterDefinition(converterDefinitions.at(row));
        int result = dlg->exec();
        if(result == QDialog::Accepted) {
            converterDefinitions[row] = dlg->getConverterDefinition();
            convertersModel.setConverterDefinitions(converterDefinitions);
        }
    }
}

void ConverterConfigurationDialog::onDeleteRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 0 )
        return;

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        converterDefinitions.removeAt(row);
        convertersModel.setConverterDefinitions(converterDefinitions);
    }
}

void ConverterConfigurationDialog::onCloneRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 0 )
        return;

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        converterDefinitions.insert(row, converterDefinitions.at(row));
        convertersModel.setConverterDefinitions(converterDefinitions);
    }
}

void ConverterConfigurationDialog::onMoveUpRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 1 ) {
        return;
    }

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        qSwap(converterDefinitions[row], converterDefinitions[row - 1]);
        convertersModel.setConverterDefinitions(converterDefinitions);
        tableView.selectRow(row - 1);
    }
}

void ConverterConfigurationDialog::onMoveDownRequested(const QModelIndex& modelIndex)
{

    int row = modelIndex.row();

    if(row < 0 ) {
        return;
    }

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count() - 1) {
        qSwap(converterDefinitions[row], converterDefinitions[row + 1]);
        convertersModel.setConverterDefinitions(converterDefinitions);
        tableView.selectRow(row + 1);
    }
}
<commit_msg>improved QToolBar popup position<commit_after>#include "converterconfigurationdialog.h"
#include "checkboxdelegate.h"
#include "cmdlinehighlighterdelegate.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QMessageBox>
#include <QDialogButtonBox>
#include <QHeaderView>
#include <QDebug>
#include <QApplication>

ConverterConfigurationDialog::ConverterConfigurationDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f)
{
    // allocate
    auto headingLabel = new QLabel("Configure External Converters");
    mainConverterLocationLabel = new QLabel("Location of Main Converter:");
    mainConverterLocationEdit = new FancyLineEdit;
    contextMenu = new QMenu(this);
    contextToolBar = new QToolBar(this);
    browseButton = new QPushButton("Browse ...");
    additionalConvertersLabel = new QLabel("Additional converters:");
    auto stdButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    auto mainLayout = new QVBoxLayout;
    auto mainConverterLayout = new QHBoxLayout;

    // set model
    tableView.setModel(&convertersModel);

    // configure view
    tableView.verticalHeader()->setHidden(true);
    tableView.setSelectionMode(QAbstractItemView::SingleSelection);
    tableView.setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView.setContextMenuPolicy(Qt::CustomContextMenu);
    tableView.horizontalHeader()->setStretchLastSection(true);

    // configure menu & toolbar
    initMenu();
    initToolBar();
    contextToolBar->hide();

    // configure fonts
    QFont defaultFont{qApp->font()};
    QFont heading2Font{defaultFont};
    QFont heading1Font{defaultFont};
    heading2Font.setPointSize(defaultFont.pointSize() + 2);
    heading1Font.setPointSize(defaultFont.pointSize() + 4);

    // configure widgets
    headingLabel->setFont(heading1Font);
    headingLabel->setAlignment(Qt::AlignHCenter);
    mainConverterLocationEdit->hideEditButton();
    mainConverterLocationLabel->setFont(heading2Font);
    additionalConvertersLabel->setFont(heading2Font);

    // attach widgets to main layout
    mainLayout->addWidget(headingLabel);
    mainLayout->addSpacing(6);
    mainLayout->addWidget(mainConverterLocationLabel);
    mainConverterLayout->addWidget(mainConverterLocationEdit);
    mainConverterLayout->addWidget(browseButton);
    mainLayout->addLayout(mainConverterLayout);
    mainLayout->addSpacing(6);
    mainLayout->addWidget(additionalConvertersLabel);
    mainLayout->addWidget(&tableView);
    mainLayout->addWidget(stdButtons);
    setLayout(mainLayout);

    // hide unnecessary columns
    tableView.setColumnHidden(0, true);
    tableView.setColumnHidden(3, true);
    tableView.setColumnHidden(6, true);
    tableView.setColumnHidden(9, true);
    tableView.setColumnHidden(10, true);

    // set delegates
    tableView.setItemDelegateForColumn(8, new CmdLineHighlighterDelegate(this));
    tableView.setItemDelegateForColumn(1, new CheckBoxDelegate(this));

    // connect signals / slots
    connect(mainConverterLocationEdit, &QLineEdit::editingFinished, this, [this] {
       mainConverterPath = mainConverterLocationEdit->text();
    });
    connect(browseButton, &QPushButton::clicked, this, &ConverterConfigurationDialog::promptForResamplerLocation);
    connect(&tableView, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){
        contextMenu->popup(QPoint{this->mapToGlobal(pos).x(), this->mapToGlobal(pos).y() + contextMenu->sizeHint().height()});
        contextToolBar->hide();
    });
    connect(&tableView, &QTableView::clicked, this, [this](const QModelIndex& modelIndex) {
        QPoint p{tableView.columnViewportPosition(modelIndex.column()) , tableView.rowViewportPosition(std::min(tableView.model()->rowCount() - 2,  modelIndex.row()))};
        contextToolBar->move(p + QPoint{0, (int)tableView.geometry().top() + contextToolBar->sizeHint().height() * 3} );
        contextToolBar->show();
        contextToolBar->raise();
    });
    connect(stdButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(stdButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);
}

void ConverterConfigurationDialog::initMenu() {
    contextMenu->addAction("New", [this] {
       onNewRequested(tableView.currentIndex());
    }, QKeySequence::New);

    contextMenu->addAction("Edit ...", [this] {
       onEditRequested(tableView.currentIndex());
    });

    contextMenu->addAction("Clone", [this] {
       onCloneRequested(tableView.currentIndex());
    }, QKeySequence::Copy);

    contextMenu->addAction("Delete", [this] {
       onDeleteRequested(tableView.currentIndex());
    }, {QKeySequence::Delete});

    contextMenu->addAction("Move Up", [this] {
        onMoveUpRequested(tableView.currentIndex());
    });

    contextMenu->addAction("Move Down", [this] {
        onMoveDownRequested(tableView.currentIndex());
    });

}

void ConverterConfigurationDialog::initToolBar() {
    contextToolBar->addAction("New", [this] {
       onNewRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Edit ...", [this] {
       onEditRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Clone", [this] {
       onCloneRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Delete", [this] {
       onDeleteRequested(tableView.currentIndex());
       contextToolBar->hide();
    });

    contextToolBar->addAction("Move Up", [this] {
        onMoveUpRequested(tableView.currentIndex());
        //contextToolBar->hide();
    });

    qDebug() << contextToolBar->addAction("Move Down", [this] {
        onMoveDownRequested(tableView.currentIndex());
        //contextToolBar->hide();
    });

    contextToolBar->setContentsMargins(0, 0, 0, 0);
    contextToolBar->setMinimumWidth(tableView.width() / 2);
    contextToolBar->setMaximumWidth(tableView.width());

}

void ConverterConfigurationDialog::showEvent(QShowEvent* event) {

    if(mainConverterPath.isEmpty() || !QFile::exists(mainConverterPath)) {
       promptForResamplerLocation();
    }

    mainConverterLocationLabel->setText(QString{"Location of Main Converter (%1):"}.arg(expectedMainConverter));
    mainConverterLocationEdit->setText(mainConverterPath);

    QDialog::showEvent(event);
}

void ConverterConfigurationDialog::resizeEvent(QResizeEvent *event)
{
    int tw = event->size().width();

    static const QVector<double> columnWidths {
        0,      /* "Priority" */
        10,     /* "Enabled" */
        20,     /* "Name" */
        0 ,     /* "Comment" */
        12,     /* "Input File Extension" */
        12,     /* "Output File Extension" */
        0 ,     /* "Executable" */
        20,     /* "Executable Path" */
        20,     /* "Command Line" */
        0 ,     /* "Download Locations" */
        0      /* "Operating Systems" */
    };

    for(int col = 0; col < convertersModel.columnCount({}) - 1; col++) {
        tableView.horizontalHeader()->resizeSection(col, tw * columnWidths.at(col)/100.0);
    }

    tableView.horizontalHeader()->setHidden(false);

    QDialog::resizeEvent(event);
}

QVector<ConverterDefinition> ConverterConfigurationDialog::getConverterDefinitions() const
{
    return convertersModel.getConverterDefinitions();
}

void ConverterConfigurationDialog::setConverterDefinitions(const QVector<ConverterDefinition> &value)
{
    convertersModel.setConverterDefinitions(value);
}

void ConverterConfigurationDialog::promptForResamplerLocation() {
    QString s("Please locate the file: ");
    s.append(expectedMainConverter);

#if defined (Q_OS_WIN)
    QString filter = "*.exe";
#else
    QString filter = "";
#endif

    QString cp = QFileDialog::getOpenFileName(this, s, mainConverterPath,  filter);

    if(!cp.isNull()) {
        mainConverterPath = cp;
        if(mainConverterPath.lastIndexOf(expectedMainConverter, -1, Qt::CaseInsensitive) == -1) { // safeguard against wrong executable being configured
            mainConverterPath.clear();
            QMessageBox::warning(this, tr("Converter Location"), tr("That is not the right program!\n"), QMessageBox::Ok);
        }
    }
}

QString ConverterConfigurationDialog::getMainConverterPath() const
{
    return mainConverterPath;
}

void ConverterConfigurationDialog::setMainConverterPath(const QString &value)
{
    mainConverterPath = value;
}

QString ConverterConfigurationDialog::getExpectedMainConverter() const
{
    return expectedMainConverter;
}

void ConverterConfigurationDialog::setExpectedMainConverter(const QString &value)
{
    expectedMainConverter = value;
    // set tooltips
    mainConverterLocationLabel->setToolTip(QString{"Please enter the location of %1 in the box below.\n"
                                           "(%1 is the command-line audio converter that Ferocious was designed to work with.)"
                                           }.arg(expectedMainConverter));
    mainConverterLocationEdit->setToolTip(QString{"Location of %1\n"
                                          "Note: you can also use drag-and-drop, or the 'Browse' button"}.arg(expectedMainConverter));
    browseButton->setToolTip(QString{"Browse to location of %1"}.arg(expectedMainConverter));
    additionalConvertersLabel->setToolTip("Use the table below to cofigure additional converters for specialized file formats.");

}

void ConverterConfigurationDialog::onNewRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 0 )
        return;

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        converterDefinitions.insert(row, {});
        convertersModel.setConverterDefinitions(converterDefinitions);
    }
}

void ConverterConfigurationDialog::onEditRequested(const QModelIndex& modelIndex)
{
    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if (converterDefinitions.isEmpty())
        return;

    int row = modelIndex.row();

    if (row < 0)
        return;

    auto dlg = new ConverterConfigurationEditDialog(this);
    if(row < converterDefinitions.count()) {
        dlg->setConverterDefinition(converterDefinitions.at(row));
        int result = dlg->exec();
        if(result == QDialog::Accepted) {
            converterDefinitions[row] = dlg->getConverterDefinition();
            convertersModel.setConverterDefinitions(converterDefinitions);
        }
    }
}

void ConverterConfigurationDialog::onDeleteRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 0 )
        return;

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        converterDefinitions.removeAt(row);
        convertersModel.setConverterDefinitions(converterDefinitions);
    }
}

void ConverterConfigurationDialog::onCloneRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 0 )
        return;

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        converterDefinitions.insert(row, converterDefinitions.at(row));
        convertersModel.setConverterDefinitions(converterDefinitions);
    }
}

void ConverterConfigurationDialog::onMoveUpRequested(const QModelIndex& modelIndex)
{
    int row = modelIndex.row();

    if(row < 1 ) {
        return;
    }

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count()) {
        qSwap(converterDefinitions[row], converterDefinitions[row - 1]);
        convertersModel.setConverterDefinitions(converterDefinitions);
        tableView.selectRow(row - 1);
    }
}

void ConverterConfigurationDialog::onMoveDownRequested(const QModelIndex& modelIndex)
{

    int row = modelIndex.row();

    if(row < 0 ) {
        return;
    }

    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();
    if(row < converterDefinitions.count() - 1) {
        qSwap(converterDefinitions[row], converterDefinitions[row + 1]);
        convertersModel.setConverterDefinitions(converterDefinitions);
        tableView.selectRow(row + 1);
    }
}
<|endoftext|>


<commit_before><commit_msg>fix filament_test on aarch64 mac<commit_after><|endoftext|>


<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <grpc++/grpc++.h>

#include <p4/bm/dataplane_interface.grpc.pb.h>
#include <p4/v1/p4runtime.grpc.pb.h>

#include <google/protobuf/util/message_differencer.h>

#include <gtest/gtest.h>

#include <memory>
#include <string>

#include "base_test.h"

namespace p4v1 = ::p4::v1;

namespace sswitch_grpc {

namespace testing {

namespace {

using google::protobuf::util::MessageDifferencer;

constexpr char ternary_json[] = TESTDATADIR "/ternary.json";
constexpr char ternary_proto[] = TESTDATADIR "/ternary.proto.txt";

class SimpleSwitchGrpcTest_Ternary : public SimpleSwitchGrpcBaseTest {
 protected:
  SimpleSwitchGrpcTest_Ternary()
      : SimpleSwitchGrpcBaseTest(ternary_proto),
        dataplane_channel(grpc::CreateChannel(
            dp_grpc_server_addr, grpc::InsecureChannelCredentials())),
        dataplane_stub(p4::bm::DataplaneInterface::NewStub(
            dataplane_channel)) { }

  void SetUp() override {
    SimpleSwitchGrpcBaseTest::SetUp();
    update_json(ternary_json);
    t_id = get_table_id(p4info, "ingress.ter");
    mf_id = get_mf_id(p4info, "ingress.ter", "h.hdr.f1");
    a_nop_id = get_action_id(p4info, "NoAction");
    a_s1_id = get_action_id(p4info, "ingress.send_1");
    a_s2_id = get_action_id(p4info, "ingress.send_2");
  }

  p4v1::Entity make_entry(const std::string &v, const std::string &mask,
                        int32_t priority, int a_id) const {
    p4v1::Entity entity;
    auto table_entry = entity.mutable_table_entry();
    table_entry->set_table_id(t_id);
    auto match = table_entry->add_match();
    match->set_field_id(mf_id);
    auto ternary = match->mutable_ternary();
    ternary->set_value(v);
    ternary->set_mask(mask);
    table_entry->set_priority(priority);
    auto table_action = table_entry->mutable_action();
    auto action = table_action->mutable_action();
    action->set_action_id(a_id);
    return entity;
  }

  grpc::Status add_entry(const p4v1::Entity &entry) const {
    p4v1::WriteRequest request;
    request.set_device_id(device_id);
    auto update = request.add_updates();
    update->set_type(p4v1::Update_Type_INSERT);
    update->mutable_entity()->CopyFrom(entry);
    ClientContext context;
    p4v1::WriteResponse rep;
    return Write(&context, request, &rep);
  }

  grpc::Status read_entry(const p4v1::Entity &entry,
                          p4v1::ReadResponse *rep) const {
    p4v1::ReadRequest request;
    request.set_device_id(device_id);
    auto *entity = request.add_entities();
    entity->CopyFrom(entry);
    ClientContext context;
    std::unique_ptr<grpc::ClientReader<p4v1::ReadResponse> > reader(
        p4runtime_stub->Read(&context, request));
    reader->Read(rep);
    return reader->Finish();
  }

  grpc::Status send_and_receive(const std::string &pkt, int ig_port,
                                p4::bm::PacketStreamResponse *rcv_pkt) {
    static uint64_t id = 1;
    p4::bm::PacketStreamRequest request;
    request.set_id(id++);
    request.set_device_id(device_id);
    request.set_port(ig_port);
    request.set_packet(pkt);
    ClientContext context;
    auto stream = dataplane_stub->PacketStream(&context);
    stream->Write(request);
    stream->Read(rcv_pkt);
    stream->WritesDone();
    return stream->Finish();
  }

  std::shared_ptr<grpc::Channel> dataplane_channel{nullptr};
  std::unique_ptr<p4::bm::DataplaneInterface::Stub> dataplane_stub{nullptr};
  int t_id;
  int mf_id;
  int a_nop_id;
  int a_s1_id;
  int a_s2_id;
};

TEST_F(SimpleSwitchGrpcTest_Ternary, ReadEntry) {
  int priority = 128;
  auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id);
  {
    auto status = add_entry(entity);
    EXPECT_TRUE(status.ok());
  }
  {
    p4v1::ReadResponse rep;
    auto status = read_entry(entity, &rep);
    EXPECT_TRUE(status.ok());
    ASSERT_EQ(1u, rep.entities().size());
    EXPECT_TRUE(MessageDifferencer::Equals(entity, rep.entities().Get(0)));
  }
}

TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityOrder) {
  int priority_lo = 128, priority_hi = 333;
  int ig_port = 3;
  std::string pkt("\xaa\xbb");
  p4::bm::PacketStreamResponse rcv_pkt;
  auto entity_lo = make_entry("\xaa\xbb", "\xff\xff", priority_lo, a_s1_id);
  {
    auto status = add_entry(entity_lo);
    EXPECT_TRUE(status.ok());
  }
  {
    auto status = send_and_receive(pkt, ig_port, &rcv_pkt);
    EXPECT_TRUE(status.ok());
    EXPECT_EQ(1, rcv_pkt.port());
  }
  auto entity_hi = make_entry("\xaa\x0b", "\xff\x0f", priority_hi, a_s2_id);
  {
    auto status = add_entry(entity_hi);
    EXPECT_TRUE(status.ok());
  }
  {
    auto status = send_and_receive(pkt, ig_port, &rcv_pkt);
    EXPECT_TRUE(status.ok());
    EXPECT_EQ(2, rcv_pkt.port());
  }
}

// zero is the lowest priority in P4Runtime (which corresponds to a high
// priority value in bmv2); this test was added for the following issue:
// https://github.com/p4lang/behavioral-model/issues/618
TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityZero) {
  int priority = 0;
  int ig_port = 3;
  std::string pkt("\xaa\xbb");
  p4::bm::PacketStreamResponse rcv_pkt;
  auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id);
  {
    auto status = add_entry(entity);
    EXPECT_TRUE(status.ok());
  }
  {
    auto status = send_and_receive(pkt, ig_port, &rcv_pkt);
    EXPECT_TRUE(status.ok());
    EXPECT_EQ(1, rcv_pkt.port());
  }
}

}  // namespace

}  // namespace testing

}  // namespace sswitch_grpc
<commit_msg>Change simple_switch_grpc priority zero test<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <grpc++/grpc++.h>

#include <p4/bm/dataplane_interface.grpc.pb.h>
#include <p4/v1/p4runtime.grpc.pb.h>

#include <google/protobuf/util/message_differencer.h>

#include <gtest/gtest.h>

#include <memory>
#include <string>

#include "base_test.h"

namespace p4v1 = ::p4::v1;

namespace sswitch_grpc {

namespace testing {

namespace {

using google::protobuf::util::MessageDifferencer;

constexpr char ternary_json[] = TESTDATADIR "/ternary.json";
constexpr char ternary_proto[] = TESTDATADIR "/ternary.proto.txt";

class SimpleSwitchGrpcTest_Ternary : public SimpleSwitchGrpcBaseTest {
 protected:
  SimpleSwitchGrpcTest_Ternary()
      : SimpleSwitchGrpcBaseTest(ternary_proto),
        dataplane_channel(grpc::CreateChannel(
            dp_grpc_server_addr, grpc::InsecureChannelCredentials())),
        dataplane_stub(p4::bm::DataplaneInterface::NewStub(
            dataplane_channel)) { }

  void SetUp() override {
    SimpleSwitchGrpcBaseTest::SetUp();
    update_json(ternary_json);
    t_id = get_table_id(p4info, "ingress.ter");
    mf_id = get_mf_id(p4info, "ingress.ter", "h.hdr.f1");
    a_nop_id = get_action_id(p4info, "NoAction");
    a_s1_id = get_action_id(p4info, "ingress.send_1");
    a_s2_id = get_action_id(p4info, "ingress.send_2");
  }

  p4v1::Entity make_entry(const std::string &v, const std::string &mask,
                        int32_t priority, int a_id) const {
    p4v1::Entity entity;
    auto table_entry = entity.mutable_table_entry();
    table_entry->set_table_id(t_id);
    auto match = table_entry->add_match();
    match->set_field_id(mf_id);
    auto ternary = match->mutable_ternary();
    ternary->set_value(v);
    ternary->set_mask(mask);
    table_entry->set_priority(priority);
    auto table_action = table_entry->mutable_action();
    auto action = table_action->mutable_action();
    action->set_action_id(a_id);
    return entity;
  }

  grpc::Status add_entry(const p4v1::Entity &entry) const {
    p4v1::WriteRequest request;
    request.set_device_id(device_id);
    auto update = request.add_updates();
    update->set_type(p4v1::Update_Type_INSERT);
    update->mutable_entity()->CopyFrom(entry);
    ClientContext context;
    p4v1::WriteResponse rep;
    return Write(&context, request, &rep);
  }

  grpc::Status read_entry(const p4v1::Entity &entry,
                          p4v1::ReadResponse *rep) const {
    p4v1::ReadRequest request;
    request.set_device_id(device_id);
    auto *entity = request.add_entities();
    entity->CopyFrom(entry);
    ClientContext context;
    std::unique_ptr<grpc::ClientReader<p4v1::ReadResponse> > reader(
        p4runtime_stub->Read(&context, request));
    reader->Read(rep);
    return reader->Finish();
  }

  grpc::Status send_and_receive(const std::string &pkt, int ig_port,
                                p4::bm::PacketStreamResponse *rcv_pkt) {
    static uint64_t id = 1;
    p4::bm::PacketStreamRequest request;
    request.set_id(id++);
    request.set_device_id(device_id);
    request.set_port(ig_port);
    request.set_packet(pkt);
    ClientContext context;
    auto stream = dataplane_stub->PacketStream(&context);
    stream->Write(request);
    stream->Read(rcv_pkt);
    stream->WritesDone();
    return stream->Finish();
  }

  std::shared_ptr<grpc::Channel> dataplane_channel{nullptr};
  std::unique_ptr<p4::bm::DataplaneInterface::Stub> dataplane_stub{nullptr};
  int t_id;
  int mf_id;
  int a_nop_id;
  int a_s1_id;
  int a_s2_id;
};

TEST_F(SimpleSwitchGrpcTest_Ternary, ReadEntry) {
  int priority = 128;
  auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id);
  {
    auto status = add_entry(entity);
    EXPECT_TRUE(status.ok());
  }
  {
    p4v1::ReadResponse rep;
    auto status = read_entry(entity, &rep);
    EXPECT_TRUE(status.ok());
    ASSERT_EQ(1u, rep.entities().size());
    EXPECT_TRUE(MessageDifferencer::Equals(entity, rep.entities().Get(0)));
  }
}

TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityOrder) {
  int priority_lo = 128, priority_hi = 333;
  int ig_port = 3;
  std::string pkt("\xaa\xbb");
  p4::bm::PacketStreamResponse rcv_pkt;
  auto entity_lo = make_entry("\xaa\xbb", "\xff\xff", priority_lo, a_s1_id);
  {
    auto status = add_entry(entity_lo);
    EXPECT_TRUE(status.ok());
  }
  {
    auto status = send_and_receive(pkt, ig_port, &rcv_pkt);
    EXPECT_TRUE(status.ok());
    EXPECT_EQ(1, rcv_pkt.port());
  }
  auto entity_hi = make_entry("\xaa\x0b", "\xff\x0f", priority_hi, a_s2_id);
  {
    auto status = add_entry(entity_hi);
    EXPECT_TRUE(status.ok());
  }
  {
    auto status = send_and_receive(pkt, ig_port, &rcv_pkt);
    EXPECT_TRUE(status.ok());
    EXPECT_EQ(2, rcv_pkt.port());
  }
}

// zero is not a valid priority value in P4Runtime
TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityZero) {
  int priority = 0;
  std::string pkt("\xaa\xbb");
  p4::bm::PacketStreamResponse rcv_pkt;
  auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id);
  auto status = add_entry(entity);
  EXPECT_FALSE(status.ok());
}

}  // namespace

}  // namespace testing

}  // namespace sswitch_grpc
<|endoftext|>


<commit_before>/*
 * Copyright 2016 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cartographer_ros/node.h"
#include "cartographer_ros/node_options.h"
#include "cartographer_ros/ros_log_sink.h"
#include "gflags/gflags.h"
#include "tf2_ros/transform_listener.h"

DEFINE_string(configuration_directory, "",
              "First directory in which configuration files are searched, "
              "second is always the Cartographer installation to allow "
              "including files from there.");
DEFINE_string(configuration_basename, "",
              "Basename, i.e. not containing any directory prefix, of the "
              "configuration file.");
DEFINE_string(map_filename, "", "If non-empty, filename of a map to load.");
DEFINE_bool(
    start_trajectory_with_default_topics, true,
    "Enable to immediately start the first trajectory with default topics.");

namespace cartographer_ros {
namespace {

void Run() {
  constexpr double kTfBufferCacheTimeInSeconds = 1e6;
  tf2_ros::Buffer tf_buffer{::ros::Duration(kTfBufferCacheTimeInSeconds)};
  tf2_ros::TransformListener tf(tf_buffer);
  NodeOptions node_options;
  TrajectoryOptions trajectory_options;
  std::tie(node_options, trajectory_options) =
      LoadOptions(FLAGS_configuration_directory, FLAGS_configuration_basename);

  Node node(node_options, &tf_buffer);
  if (!FLAGS_map_filename.empty()) {
    node.LoadMap(FLAGS_map_filename);
  }

  if (FLAGS_start_trajectory_with_default_topics) {
    node.StartTrajectoryWithDefaultTopics(trajectory_options);
  }

  ::ros::spin();

  node.FinishAllTrajectories();
  node.RunFinalOptimization();
}

}  // namespace
}  // namespace cartographer_ros

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  CHECK(!FLAGS_configuration_directory.empty())
      << "-configuration_directory is missing.";
  CHECK(!FLAGS_configuration_basename.empty())
      << "-configuration_basename is missing.";

  ::ros::init(argc, argv, "cartographer_node");
  ::ros::start();

  cartographer_ros::ScopedRosLogSink ros_log_sink;
  cartographer_ros::Run();
  ::ros::shutdown();
}
<commit_msg>Serialize state before shutdown (#502)<commit_after>/*
 * Copyright 2016 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cartographer_ros/node.h"
#include "cartographer_ros/node_options.h"
#include "cartographer_ros/ros_log_sink.h"
#include "gflags/gflags.h"
#include "tf2_ros/transform_listener.h"

DEFINE_string(configuration_directory, "",
              "First directory in which configuration files are searched, "
              "second is always the Cartographer installation to allow "
              "including files from there.");
DEFINE_string(configuration_basename, "",
              "Basename, i.e. not containing any directory prefix, of the "
              "configuration file.");
DEFINE_string(map_filename, "", "If non-empty, filename of a map to load.");
DEFINE_bool(
    start_trajectory_with_default_topics, true,
    "Enable to immediately start the first trajectory with default topics.");
DEFINE_string(save_map_filename, "",
              "If non-empty, serialize state and write it to disk before shutting down.");

namespace cartographer_ros {
namespace {

void Run() {
  constexpr double kTfBufferCacheTimeInSeconds = 1e6;
  tf2_ros::Buffer tf_buffer{::ros::Duration(kTfBufferCacheTimeInSeconds)};
  tf2_ros::TransformListener tf(tf_buffer);
  NodeOptions node_options;
  TrajectoryOptions trajectory_options;
  std::tie(node_options, trajectory_options) =
      LoadOptions(FLAGS_configuration_directory, FLAGS_configuration_basename);

  Node node(node_options, &tf_buffer);
  if (!FLAGS_map_filename.empty()) {
    node.LoadMap(FLAGS_map_filename);
  }

  if (FLAGS_start_trajectory_with_default_topics) {
    node.StartTrajectoryWithDefaultTopics(trajectory_options);
  }

  ::ros::spin();

  node.FinishAllTrajectories();
  node.RunFinalOptimization();

  if (!FLAGS_save_map_filename.empty()) {
    node.SerializeState(FLAGS_save_map_filename);
  }
}

}  // namespace
}  // namespace cartographer_ros

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  CHECK(!FLAGS_configuration_directory.empty())
      << "-configuration_directory is missing.";
  CHECK(!FLAGS_configuration_basename.empty())
      << "-configuration_basename is missing.";

  ::ros::init(argc, argv, "cartographer_node");
  ::ros::start();

  cartographer_ros::ScopedRosLogSink ros_log_sink;
  cartographer_ros::Run();
  ::ros::shutdown();
}
<|endoftext|>


<commit_before>#include <windows.h>         //     API
#include <assert.h>

//  :
HINSTANCE hInst; 	//
LPCTSTR szWindowClass = "Kostyuk";
LPCTSTR szTitle = "lab 9. Assembler usage";

const int N_OF_BITS = 32; //
CHAR char_buf[ N_OF_BITS + 1 ]; // -

int arr1[ 3 ][ 3 ] = { { 10, 12, 33 },{ 24, 52, 46 },{ 17, 28, 95 } };
int arr2[ 3 ][ 3 ] = { { 3, 2, 1 },{ 6, 5, 4 },{ 9, 8, 7 } };
int arr3[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };
int arr4[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };
int arr5[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };

void MTransponse( int nrows, int ncols ) {
	__asm {

		mov ebx, 0; i = 0

		per_row:
			cmp ebx, nrows; if i == nrows
			je do_exit
			mov ecx, 0; j = 0

		per_col:
			cmp ecx, ncols; if j == ncols
			je per_row_end;

			mov eax, ebx; eax = i
			mul ncols; eax:edx = ebx * ncols = i * ncols

			add eax, ecx; eax = i * ncols + j
			mov esi, eax; esi = i * ncols + j

			mov eax, arr1[ esi * 4 ]; temp = src[ i * ncols + j ]

			push eax; copy eax (temp) to stack

			mov eax, ecx; eax = j
			mul nrows; eax:ecx = ecx * nrows = j * nrows
			add eax, ebx; eax = j * nrows + i
			mov edi, eax; edi = j * nrows + i

			pop eax; restore eax (temp) from stack

			mov arr5[ edi * 4 ], eax; dest[ j * nrows + i ] = temp

			inc ecx; j++
			jmp per_col

		per_row_end:
			inc ebx; i++
			jmp per_row

		do_exit:
			; do nothing
	}

}

void MElementWiseMul( int nrows, int ncols ) {

	int n_of_elements = nrows * ncols;

	__asm {
			mov ecx, n_of_elements; comment
		r3 :
			mov eax, arr1[ ecx * 4 - 4 ];    arg1
			mov edx, arr2[ ecx * 4 - 4 ];    arg2
			mul edx;  edx  aex
			mov arr3[ ecx * 4 - 4 ], eax;
			loop r3
	}

}

void MSum( int nrows, int ncols ) {

	int n_of_elements = nrows * ncols;

	__asm {
			mov ecx, n_of_elements; comment

		r1 :
			mov eax, arr1[ ecx * 4 - 4 ];    arg1
			mov edx, arr2[ ecx * 4 - 4 ];    arg2
			add eax, edx;    1  2
			mov arr4[ ecx * 4 - 4 ], eax;
			loop r1
	}

}

void PrintArray3x3( HDC _hdc, const RECT & _client, int _array[ 3 ][ 3 ], int _padding_x, int _padding_y, char * _buf ) {

	for ( int row = 0; row < 3; ++row ) {
		TextOut( _hdc, _padding_x, 20 * row + _padding_y + 20, _buf, wsprintf( _buf, "%d %d %d", _array[ row ][ 0 ], _array[ row ][ 1 ], _array[ row ][ 2 ] ) );
	}

}

void PrintArrays( HDC _hdc, const RECT & _client ) {

	//
	char buff[ 60 ];

	int padding_y = 10;
	int padding_x = 10;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 1:" ) );
	PrintArray3x3( _hdc, _client, arr1, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 2:" ) );
	PrintArray3x3( _hdc, _client, arr2, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Mul result:" ) );
	PrintArray3x3( _hdc, _client, arr3, padding_x, padding_y, buff );

	padding_x = 10;
	padding_y += 110;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Sum result:" ) );
	PrintArray3x3( _hdc, _client, arr4, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Src 1 tranposed:" ) );
	PrintArray3x3( _hdc, _client, arr5, padding_x, padding_y, buff );

}

//

ATOM MyRegisterClass( HINSTANCE hInstance );
BOOL InitInstance( HINSTANCE, int );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );

//
int APIENTRY WinMain( HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR     lpCmdLine,
	int       nCmdShow )
{
	MSG msg;

	//
	MyRegisterClass( hInstance );

	//
	if ( !InitInstance( hInstance, nCmdShow ) )
	{
		return FALSE;
	}

	//
	while ( GetMessage( &msg, NULL, 0, 0 ) )
	{
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}
	return msg.wParam;
}

//  FUNCTION: MyRegisterClass()
//

ATOM MyRegisterClass( HINSTANCE hInstance )
{
	WNDCLASSEX wcex;
	wcex.cbSize = sizeof( WNDCLASSEX );
	wcex.style = CS_HREDRAW | CS_VREDRAW;	//
	wcex.lpfnWndProc = (WNDPROC)WndProc; //
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;		//
	wcex.hIcon = LoadIcon( NULL, IDI_APPLICATION );		//
	wcex.hCursor = LoadCursor( NULL, IDC_ARROW );    //
	wcex.hbrBackground = GetSysColorBrush( COLOR_WINDOW );   //
	wcex.lpszMenuName = NULL;		//
	wcex.lpszClassName = szWindowClass;	//
	wcex.hIconSm = NULL;

	return RegisterClassEx( &wcex ); //
}

// FUNCTION: InitInstance(HANDLE, int)
//          hInst
BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )
{
	HWND hWnd;

	hInst = hInstance; //      hInst

	hWnd = CreateWindow( szWindowClass, //
		szTitle,   //
		WS_OVERLAPPEDWINDOW, //
		CW_USEDEFAULT,	//
		CW_USEDEFAULT, 	//   Y
		CW_USEDEFAULT,    //
		CW_USEDEFAULT,    //   Y
		NULL,	//
		NULL,       //
		hInstance,  //
		NULL );     //  .

	if ( !hWnd ) //    ,   FALSE
	{
		return FALSE;
	}
	ShowWindow( hWnd, nCmdShow );		//
	UpdateWindow( hWnd );			//
	return TRUE;				//
}

//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//   .     ,
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
	PAINTSTRUCT ps;
	HDC hdc;
	RECT rt;
	char sprintf_buf[ 60 ];

	switch ( message )
	{
	case WM_CREATE: //
		//do_stuff();
		MElementWiseMul( 3, 3 );
		MSum( 3, 3 );
		MTransponse( 3, 3 );
		break;

	case WM_PAINT:  //
		hdc = BeginPaint( hWnd, &ps );	//
		GetClientRect( hWnd, &rt ); //

		//TextOut( hdc, 10, 10, sprintf_buf, wsprintf( sprintf_buf, "%d", subs(11) ));

		PrintArrays( hdc, rt );

		EndPaint( hWnd, &ps );	//
		break;

	case WM_DESTROY: //
		PostQuitMessage( 0 );
		break;
	default:
		//  ,
		return DefWindowProc( hWnd, message, wParam, lParam );
	}
	return 0;
}<commit_msg>Base structure for matrix multiplication function<commit_after>#include <windows.h>         //     API
#include <assert.h>

//  :
HINSTANCE hInst; 	//
LPCTSTR szWindowClass = "Kostyuk";
LPCTSTR szTitle = "lab 9. Assembler usage";

const int N_OF_BITS = 32; //
CHAR char_buf[ N_OF_BITS + 1 ]; // -

int arr1[ 3 ][ 3 ] = { { 10, 12, 33 },{ 24, 52, 46 },{ 17, 28, 95 } };
int arr2[ 3 ][ 3 ] = { { 3, 2, 1 },{ 6, 5, 4 },{ 9, 8, 7 } };
int arr3[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };
int arr4[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };
int arr5[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };
int arr6[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } };

void MTransponse( int nrows, int ncols ) {
	__asm {

		mov ebx, 0; i = 0

		per_row:
			cmp ebx, nrows; if i == nrows
			je do_exit
			mov ecx, 0; j = 0

		per_col:
			cmp ecx, ncols; if j == ncols
			je per_row_end;

			mov eax, ebx; eax = i
			mul ncols; eax:edx = ebx * ncols = i * ncols

			add eax, ecx; eax = i * ncols + j
			mov esi, eax; esi = i * ncols + j

			mov eax, arr1[ esi * 4 ]; temp = src[ i * ncols + j ]

			push eax; copy eax (temp) to stack

			mov eax, ecx; eax = j
			mul nrows; eax:ecx = ecx * nrows = j * nrows
			add eax, ebx; eax = j * nrows + i
			mov edi, eax; edi = j * nrows + i

			pop eax; restore eax (temp) from stack

			mov arr5[ edi * 4 ], eax; dest[ j * nrows + i ] = temp

			inc ecx; j++
			jmp per_col

		per_row_end:
			inc ebx; i++
			jmp per_row

		do_exit:
			; do nothing
	}

}

void MElementWiseMul( int nrows, int ncols ) {

	int n_of_elements = nrows * ncols;

	__asm {
			mov ecx, n_of_elements; comment
		r3 :
			mov eax, arr1[ ecx * 4 - 4 ];    arg1
			mov edx, arr2[ ecx * 4 - 4 ];    arg2
			mul edx;  edx  aex
			mov arr3[ ecx * 4 - 4 ], eax;
			loop r3
	}

}

void MSum( int nrows, int ncols ) {

	int n_of_elements = nrows * ncols;

	__asm {
			mov ecx, n_of_elements; comment

		r1 :
			mov eax, arr1[ ecx * 4 - 4 ];    arg1
			mov edx, arr2[ ecx * 4 - 4 ];    arg2
			add eax, edx;    1  2
			mov arr4[ ecx * 4 - 4 ], eax;
			loop r1
	}

}

void MMul( int n, int m, int p ) {

	int i, j, k;

	__asm {

		jmp start;

		start:
			mov i, 0; i = 0

		outer_loop:
			mov eax, i; eax = i
			cmp eax, n; if i == n
			je do_exit; then exit
			mov j, 0; else j = 0 and jmp middle_loop

		middle_loop:
			mov eax, j; eax = j
			cmp eax, m; if j == m
			je outer_loop_end; then exit middle_loop

			mov k, 0; else k = 0 and jmp inner_loop

		inner_loop:
			mov eax, k; eax = k
			cmp eax, p; if k == p
			je middle_loop_end; then exit inner loop

			inc k; k++
			jmp inner_loop; start new inner_loop iteration

		middle_loop_end:
			inc j; j++
			jmp middle_loop; start new middle_loop iteration

		outer_loop_end:
			inc i; i++
			jmp outer_loop; start new outer_loop iteration

		do_exit:
	}

}

void PrintArray3x3( HDC _hdc, const RECT & _client, int _array[ 3 ][ 3 ], int _padding_x, int _padding_y, char * _buf ) {

	for ( int row = 0; row < 3; ++row ) {
		TextOut( _hdc, _padding_x, 20 * row + _padding_y + 20, _buf, wsprintf( _buf, "%d %d %d", _array[ row ][ 0 ], _array[ row ][ 1 ], _array[ row ][ 2 ] ) );
	}

}

void PrintArrays( HDC _hdc, const RECT & _client ) {

	//
	char buff[ 60 ];

	int padding_y = 10;
	int padding_x = 10;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 1:" ) );
	PrintArray3x3( _hdc, _client, arr1, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 2:" ) );
	PrintArray3x3( _hdc, _client, arr2, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "EW Mul result:" ) );
	PrintArray3x3( _hdc, _client, arr3, padding_x, padding_y, buff );

	padding_x = 10;
	padding_y += 110;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Sum result:" ) );
	PrintArray3x3( _hdc, _client, arr4, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Src 1 tranposed:" ) );
	PrintArray3x3( _hdc, _client, arr5, padding_x, padding_y, buff );

	padding_x += 140;

	TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Src1 x Src2 = " ) );
	PrintArray3x3( _hdc, _client, arr6, padding_x, padding_y, buff );
}

//

ATOM MyRegisterClass( HINSTANCE hInstance );
BOOL InitInstance( HINSTANCE, int );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );

//
int APIENTRY WinMain( HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR     lpCmdLine,
	int       nCmdShow )
{
	MSG msg;

	//
	MyRegisterClass( hInstance );

	//
	if ( !InitInstance( hInstance, nCmdShow ) )
	{
		return FALSE;
	}

	//
	while ( GetMessage( &msg, NULL, 0, 0 ) )
	{
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}
	return msg.wParam;
}

//  FUNCTION: MyRegisterClass()
//

ATOM MyRegisterClass( HINSTANCE hInstance )
{
	WNDCLASSEX wcex;
	wcex.cbSize = sizeof( WNDCLASSEX );
	wcex.style = CS_HREDRAW | CS_VREDRAW;	//
	wcex.lpfnWndProc = (WNDPROC)WndProc; //
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;		//
	wcex.hIcon = LoadIcon( NULL, IDI_APPLICATION );		//
	wcex.hCursor = LoadCursor( NULL, IDC_ARROW );    //
	wcex.hbrBackground = GetSysColorBrush( COLOR_WINDOW );   //
	wcex.lpszMenuName = NULL;		//
	wcex.lpszClassName = szWindowClass;	//
	wcex.hIconSm = NULL;

	return RegisterClassEx( &wcex ); //
}

// FUNCTION: InitInstance(HANDLE, int)
//          hInst
BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )
{
	HWND hWnd;

	hInst = hInstance; //      hInst

	hWnd = CreateWindow( szWindowClass, //
		szTitle,   //
		WS_OVERLAPPEDWINDOW, //
		CW_USEDEFAULT,	//
		CW_USEDEFAULT, 	//   Y
		CW_USEDEFAULT,    //
		CW_USEDEFAULT,    //   Y
		NULL,	//
		NULL,       //
		hInstance,  //
		NULL );     //  .

	if ( !hWnd ) //    ,   FALSE
	{
		return FALSE;
	}
	ShowWindow( hWnd, nCmdShow );		//
	UpdateWindow( hWnd );			//
	return TRUE;				//
}

//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//   .     ,
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
	PAINTSTRUCT ps;
	HDC hdc;
	RECT rt;
	char sprintf_buf[ 60 ];

	switch ( message )
	{
	case WM_CREATE: //
		//do_stuff();
		MElementWiseMul( 3, 3 );
		MSum( 3, 3 );
		MTransponse( 3, 3 );
		MMul( 3, 3, 3 );
		break;

	case WM_PAINT:  //
		hdc = BeginPaint( hWnd, &ps );	//
		GetClientRect( hWnd, &rt ); //

		//TextOut( hdc, 10, 10, sprintf_buf, wsprintf( sprintf_buf, "%d", subs(11) ));

		PrintArrays( hdc, rt );

		EndPaint( hWnd, &ps );	//
		break;

	case WM_DESTROY: //
		PostQuitMessage( 0 );
		break;
	default:
		//  ,
		return DefWindowProc( hWnd, message, wParam, lParam );
	}
	return 0;
}<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

#include "./pn_test_proactor.hpp"

#include <proton/connection.h>
#include <proton/condition.h>
#include <proton/delivery.h>
#include <proton/link.h>
#include <proton/listener.h>
#include <proton/netaddr.h>
#include <proton/proactor.h>
#include <proton/session.h>
#include <proton/sasl.h>
#include <proton/ssl.h>
#include <proton/transport.h>

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

typedef struct app_data_t {
  const char *amqp_address;
  const char *container_id;

  pn_ssl_domain_t *server_ssl_domain;

  bool connection_succeeded;
  bool transport_error;
} app_data_t;

/* Note must be run in the current directory to find certificate files */
#define SSL_FILE(NAME) "ssl-certs/" NAME
#define SSL_PW "tclientpw"
/* Windows vs. OpenSSL certificates */
#if defined(_WIN32)
#  define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.p12")
#  define SET_CREDENTIALS(DOMAIN, NAME)                                 \
  pn_ssl_domain_set_credentials(DOMAIN, SSL_FILE(NAME "-full.p12"), "", SSL_PW)
#else
#  define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.pem")
#  define SET_CREDENTIALS(DOMAIN, NAME)                                 \
  pn_ssl_domain_set_credentials(DOMAIN, CERTIFICATE(NAME), SSL_FILE(NAME "-private-key.pem"), SSL_PW)
#endif

/* Returns true to continue, false if finished */
static bool server_handler(app_data_t* app, pn_event_t* event) {
  pn_listener_t *l = pn_event_listener(event);
  switch (pn_event_type(event)) {

   // Server side
   case PN_LISTENER_ACCEPT: {
     /* Configure a transport to allow SSL and SASL connections. See ssl_domain setup in main() */
     pn_transport_t *t = pn_transport();
     pn_transport_set_server(t); /* Must call before pn_sasl() */
     pn_sasl_allowed_mechs(pn_sasl(t), "ANONYMOUS");
     if (app->server_ssl_domain) {
       pn_ssl_init(pn_ssl(t), app->server_ssl_domain, NULL);
     }
     pn_listener_accept2(l, NULL, t);

     /* Accept only one connection */
     pn_listener_close(l);
     break;
   }

   case PN_TRANSPORT_CLOSED:
    break;

   default: break;
  }
  return true;
}

static bool client_handler(app_data_t* app, pn_event_t* event) {
  switch (pn_event_type(event)) {
   // Client side
   case PN_CONNECTION_INIT: {
     pn_connection_t* c = pn_event_connection(event);
     pn_session_t* s = pn_session(pn_event_connection(event));
     pn_connection_set_container(c, app->container_id);
     pn_connection_open(c);
     pn_session_open(s);
     {
     pn_link_t* l = pn_sender(s, "my_sender");
     pn_terminus_set_address(pn_link_target(l), app->amqp_address);
     pn_link_open(l);
     break;
     }
   }

   case PN_CONNECTION_BOUND: {
     break;
   }

   case PN_CONNECTION_REMOTE_OPEN:
    app->connection_succeeded = true;
    pn_connection_close(pn_event_connection(event));
    break;

   case PN_TRANSPORT_ERROR:
    app->transport_error = true;
    break;

   case PN_CONNECTION_REMOTE_CLOSE:
    pn_connection_close(pn_event_connection(event));
    break;

   case PN_SESSION_REMOTE_CLOSE:
    pn_connection_close(pn_event_connection(event));
    break;

   case PN_LINK_REMOTE_CLOSE:
   case PN_LINK_REMOTE_DETACH:
    pn_connection_close(pn_event_connection(event));
    break;

   default: break;
  }
  return true;
}

typedef bool handler_t(app_data_t* app, pn_event_t* event);
void run(pn_proactor_t *p, app_data_t *app, handler_t *shandler, handler_t *chandler) {
  /* Loop and handle server/client events */
  do {
    pn_event_batch_t *events = pn_proactor_wait(p);
    pn_event_t *e;
    for (e = pn_event_batch_next(events); e; e = pn_event_batch_next(events)) {
      if (pn_event_type(e)==PN_PROACTOR_INACTIVE) {
        return;
      }

      if (pn_event_listener(e)) {
        if (!shandler(app, e)) {
          return;
        }
      } else {
        if (!chandler(app, e)) {
          return;
        }
      }
    }
    pn_proactor_done(p, events);
  } while(true);
}

TEST_CASE("ssl") {
  struct app_data_t app = {0};

  app.container_id = "ssl-test";
  app.amqp_address = "fubar";

  pn_test::auto_free<pn_proactor_t, pn_proactor_free> proactor(pn_proactor());

  /* Configure server for default SSL */
  pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free>
    sd(pn_ssl_domain(PN_SSL_MODE_SERVER));
  app.server_ssl_domain = sd;

  /* Configure a client for SSL */
  pn_transport_t *t = pn_transport();
  pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free>
    cd(pn_ssl_domain(PN_SSL_MODE_CLIENT));

  SECTION("Default connections don't verify") {
    REQUIRE(pn_ssl_init(pn_ssl(t), NULL, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==false);
    CHECK(app.transport_error==true);
  }

  SECTION("Anonymous connections don't verify") {
    REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tclient")) == 0);
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER_NAME, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==false);
    CHECK(app.transport_error==true);
  }

  SECTION("Anonymous connections connect if anonymous allowed") {
#ifndef _WIN32
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_ANONYMOUS_PEER, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==true);
    CHECK(app.transport_error==false);
#else
    SUCCEED("Skipped: Windows schannel does not support anonymous connections");
#endif
  }
}
<commit_msg>PROTON-2021: [c] Round out the ssl certificate verification tests<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

#include "./pn_test_proactor.hpp"

#include <proton/connection.h>
#include <proton/condition.h>
#include <proton/delivery.h>
#include <proton/link.h>
#include <proton/listener.h>
#include <proton/netaddr.h>
#include <proton/proactor.h>
#include <proton/session.h>
#include <proton/sasl.h>
#include <proton/ssl.h>
#include <proton/transport.h>

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

typedef struct app_data_t {
  const char *amqp_address;
  const char *container_id;

  pn_ssl_domain_t *server_ssl_domain;

  bool connection_succeeded;
  bool transport_error;
} app_data_t;

/* Note must be run in the current directory to find certificate files */
#define SSL_FILE(NAME) "ssl-certs/" NAME
#define SSL_PW(NAME) NAME "pw"
/* Windows vs. OpenSSL certificates */
#if defined(_WIN32)
#  define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.p12")
#  define SET_CREDENTIALS(DOMAIN, NAME)                                 \
  pn_ssl_domain_set_credentials(DOMAIN, SSL_FILE(NAME "-full.p12"), "", SSL_PW(NAME))
#else
#  define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.pem")
#  define SET_CREDENTIALS(DOMAIN, NAME)                                 \
  pn_ssl_domain_set_credentials(DOMAIN, CERTIFICATE(NAME), SSL_FILE(NAME "-private-key.pem"), SSL_PW(NAME))
#endif

/* Returns true to continue, false if finished */
static bool server_handler(app_data_t* app, pn_event_t* event) {
  pn_listener_t *l = pn_event_listener(event);
  switch (pn_event_type(event)) {

   // Server side
   case PN_LISTENER_ACCEPT: {
     /* Configure a transport to allow SSL and SASL connections. See ssl_domain setup in main() */
     pn_transport_t *t = pn_transport();
     pn_transport_set_server(t); /* Must call before pn_sasl() */
     pn_sasl_allowed_mechs(pn_sasl(t), "ANONYMOUS");
     pn_ssl_init(pn_ssl(t), app->server_ssl_domain, NULL);
     pn_listener_accept2(l, NULL, t);

     /* Accept only one connection */
     pn_listener_close(l);
     break;
   }

   case PN_TRANSPORT_CLOSED:
    break;

   default: break;
  }
  return true;
}

static bool client_handler(app_data_t* app, pn_event_t* event) {
  switch (pn_event_type(event)) {
   // Client side
   case PN_CONNECTION_INIT: {
     pn_connection_t* c = pn_event_connection(event);
     pn_session_t* s = pn_session(pn_event_connection(event));
     pn_connection_set_container(c, app->container_id);
     pn_connection_open(c);
     pn_session_open(s);
     {
     pn_link_t* l = pn_sender(s, "my_sender");
     pn_terminus_set_address(pn_link_target(l), app->amqp_address);
     pn_link_open(l);
     break;
     }
   }

   case PN_CONNECTION_BOUND: {
     break;
   }

   case PN_CONNECTION_REMOTE_OPEN:
    app->connection_succeeded = true;
    pn_connection_close(pn_event_connection(event));
    break;

   case PN_TRANSPORT_ERROR:
    app->transport_error = true;
    break;

   case PN_CONNECTION_REMOTE_CLOSE:
    pn_connection_close(pn_event_connection(event));
    break;

   case PN_SESSION_REMOTE_CLOSE:
    pn_connection_close(pn_event_connection(event));
    break;

   case PN_LINK_REMOTE_CLOSE:
   case PN_LINK_REMOTE_DETACH:
    pn_connection_close(pn_event_connection(event));
    break;

   default: break;
  }
  return true;
}

typedef bool handler_t(app_data_t* app, pn_event_t* event);
void run(pn_proactor_t *p, app_data_t *app, handler_t *shandler, handler_t *chandler) {
  /* Loop and handle server/client events */
  do {
    pn_event_batch_t *events = pn_proactor_wait(p);
    pn_event_t *e;
    for (e = pn_event_batch_next(events); e; e = pn_event_batch_next(events)) {
      if (pn_event_type(e)==PN_PROACTOR_INACTIVE) {
        return;
      }

      if (pn_event_listener(e)) {
        if (!shandler(app, e)) {
          return;
        }
      } else {
        if (!chandler(app, e)) {
          return;
        }
      }
    }
    pn_proactor_done(p, events);
  } while(true);
}

TEST_CASE("ssl certificate verification tests") {
  struct app_data_t app = {0};

  app.container_id = "ssl-test";
  app.amqp_address = "fubar";

  pn_test::auto_free<pn_proactor_t, pn_proactor_free> proactor(pn_proactor());

  /* Configure server for default SSL */
  pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free>
    sd(pn_ssl_domain(PN_SSL_MODE_SERVER));
  app.server_ssl_domain = sd;

  /* Configure a client for SSL */
  pn_transport_t *t = pn_transport();
  pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free>
    cd(pn_ssl_domain(PN_SSL_MODE_CLIENT));

  SECTION("Default connections don't verify to self signed server (even with correct name)") {
    REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), NULL, NULL) == 0);
    REQUIRE(pn_ssl_set_peer_hostname(pn_ssl(t), "test_server") == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==false);
    CHECK(app.transport_error==true);
  }

  SECTION("Connections noname verify to self signed cert if cert allowed (even with no name)") {
    REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0);
    REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tserver")) == 0);
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==true);
    CHECK(app.transport_error==false);
  }

  SECTION("Connections don't noname verify to self signed cert without cert allowed") {
    REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0);
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==false);
    CHECK(app.transport_error==true);
  }

  SECTION("Connections verify with self signed server if cert allowed") {
    REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0);
    REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tserver")) == 0);
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER_NAME, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);
    REQUIRE(pn_ssl_set_peer_hostname(pn_ssl(t), "test_server") == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==true);
    CHECK(app.transport_error==false);
  }

  SECTION("Anonymous server connections don't verify") {
    REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tserver")) == 0);
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER_NAME, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==false);
    CHECK(app.transport_error==true);
  }

  SECTION("Anonymous connections connect if anonymous allowed") {
#ifndef _WIN32
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_ANONYMOUS_PEER, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==true);
    CHECK(app.transport_error==false);
#else
    SUCCEED("Skipped: Windows schannel does not support anonymous connections");
#endif
  }

  SECTION("Default server (anonymous) doesn't verify against default client (verify peername)") {
    app.server_ssl_domain = 0;
    REQUIRE(pn_ssl_init(pn_ssl(t), NULL, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==false);
    CHECK(app.transport_error==true);
  }

  SECTION("Default server (anonymous) connects if anonymous allowed") {
#ifndef _WIN32
    app.server_ssl_domain = 0;
    REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_ANONYMOUS_PEER, NULL) == 0);
    REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0);

    pn_proactor_listen(proactor, pn_listener(), "", 16);
    pn_proactor_connect2(proactor, NULL, t, "");

    run(proactor, &app, server_handler, client_handler);
    CHECK(app.connection_succeeded==true);
    CHECK(app.transport_error==false);
#else
    SUCCEED("Skipped: Windows schannel does not support anonymous connections");
#endif
  }
}
<|endoftext|>


<commit_before>#ifndef INCLUDE_H
#define INCLUDE_H

#include "STANDARD.H"

#include <stdbool.h>
#include <windows.h>
#include <mmsystem.h>
#include <ddraw.h>
#include <d3d.h>
#include <dinput.h>
#include <dsound.h>
#include <windowsx.h>
#include <time.h>
#include "SPECIFIC.H"
#include <stdio.h>

#if !defined(__cplusplus)
//#error Dude insists on C++ !!!
#endif

#define global extern
#define local static
#define defglobal

typedef void* Handle;

enum
{
	LOG_OUTPUT,
	LOG_RESET,
	LOG_END
};

#define LOG_DO_STRLEN 0xffffffff

//#define Log2(type, fmt, ...) Log_real("[DBLOG] [%s] %s", STRINGIFY(type), )

//#define Log(type, fmt, ...) S_Warn("[DBLOG] [" STRINGIFY(type) "] " fmt, __VA_ARGS__)
#define Log(type, fmt, ...) Log_real(type, #type, fmt, __VA_ARGS__)

#define ArraySize(a) (sizeof(a)/sizeof((a)[0]))
#define Zero(thing) memset(&(thing),0,sizeof(thing))
#define ZeroArray(a) memset((a),0,sizeof(a))
#define EndOfArray(a) ((a)+ArraySize(a))
#define InitDXStruct(s) memset(&(s),0,sizeof(s)),(s).dwSize=sizeof(s)
#define DefLocalString(x,y) local char Lsz##x[]=y
#define LocalString(x) Lsz##x
#define DefValueName(x) local char Lsz##x[]=#x
#define ValueName(x) Lsz##x
#define Align(x,b) (x)=(x)&~((b)-1)

void DebugPrint(const char* message);
void Log_backend(char type, char* fmt, ...);
inline void Log_real(char ctype, char* type, char* fmt, ...)
{
	char buf[128], pbuf[1024];
	char tbuf[15];
	memset(tbuf, ' ', 14);
	tbuf[14] = 0;
	strcpy(tbuf, type + 3);
	ZeroArray(buf);
	ZeroArray(pbuf);
	strcpy(buf, "[DBLOG] [");
	strcat(buf, tbuf);
	strcat(buf, "] ");

	va_list args;
	va_start(args, fmt);
	vsprintf(pbuf, fmt, args);
	va_end(args);

	char res[1152];
	ZeroArray(res);
	strcat(res, buf);
	strcat(res, pbuf);

	DebugPrint(res);
	Log_backend(ctype, pbuf);
}

/*** dxerror.cpp ***/
char* ERR_Describe_DX(HRESULT hr);
char* ERR_Describe_Init(int nError);

enum InitResult	// possible initialisation results
{
	INIT_OK,

	INIT_ERR_PreferredAdapterNotFound,
	INIT_ERR_CantCreateWindow,
	INIT_ERR_CantCreateDirectDraw,
	INIT_ERR_CantInitRenderer,
	INIT_ERR_CantCreateDirectInput,
	INIT_ERR_CantCreateKeyboardDevice,
	INIT_ERR_CantSetKBCooperativeLevel,
	INIT_ERR_CantSetKBDataFormat,
	INIT_ERR_CantAcquireKeyboard,
	INIT_ERR_CantSetDSCooperativeLevel,

	INIT_ERR_DD_SetExclusiveMode,
	INIT_ERR_DD_ClearExclusiveMode,
	INIT_ERR_SetDisplayMode,
	INIT_ERR_CreateScreenBuffers,
	INIT_ERR_GetBackBuffer,
	INIT_ERR_CreatePalette,
	INIT_ERR_SetPalette,
	INIT_ERR_CreatePrimarySurface,
	INIT_ERR_CreateBackBuffer,
	INIT_ERR_CreateClipper,
	INIT_ERR_SetClipperHWnd,
	INIT_ERR_SetClipper,
	INIT_ERR_CreateZBuffer,
	INIT_ERR_AttachZBuffer,
	INIT_ERR_CreateRenderBuffer,
	INIT_ERR_CreatePictureBuffer,
	INIT_ERR_D3D_Create,
	INIT_ERR_CreateDevice,
	INIT_ERR_CreateViewport,
	INIT_ERR_AddViewport,
	INIT_ERR_SetViewport2,
	INIT_ERR_SetCurrentViewport,

	INIT_ERR_ClearRenderBuffer,
	INIT_ERR_UpdateRenderInfo,
	INIT_ERR_GetThirdBuffer,

	INIT_ERR_GoFullScreen,
	INIT_ERR_GoWindowed,

	INIT_ERR_WrongBitDepth,
	INIT_ERR_GetPixelFormat,
	INIT_ERR_GetDisplayMode
};
typedef void* Position;	// iterator for linked lists etc
/*** settings.cpp ***/
struct AppSettings
{
	Position DisplayAdapter;			// G_DisplayAdapterList[DisplayAdapter] is the one we're using...
	Position SoundAdapter;				// same for sound card
	Position Joystick;					// and joystick
	Position FullScreenMode;			// hardware fullscreen mode x/y/bpp
	int nRenderMode;					// none/internal/HAL/RGB
	int nWindowWidth, nWindowHeight;		// size of desktop window
	int nAspectMode;					// 4:3 / 16:9 / any
	bool tPerspectiveCorrect;			// perspective correct textures
	bool tDither;						// dithering on/off
	bool tZBuffer;						// render using z buffer
	bool tBilinearFiltering;			// use bilinear filtering when texture mapping
	bool tTripleBuffering;				// use three buffers instead of two, for better performance but more memory usage
										//	bool tMipMap;						// use mipmapped textures
										//	bool tAntialias;					// antialias edges
	bool tFullScreen;					// switch to full screen or run in window
	bool tSoundEnabled;					// false = disable sound
	bool tLaraMic;						// position mic at lara instead of camera (for paul & toby)
	bool tJoystickEnabled;				// false = disable joystick
	bool tDisable16BitTextures;			// true = disable 16 bit textures (for 2MB Mystique etc)
	bool tDontSortPrimitives;			// true = no need to sort primitives (for PowerVR)
	bool tFlipBroken;					// true = driver doesn't wait for flip to finish before rendering.  must do it myself...
	bool tDisableFMV;					// true = don't play any FMVs
	int nTexelAdjustMode;				// never / when filtering / always
	int nNearestAdjustment;				// non-filtered texel adjustment
	int nLinearAdjustment;				// bilinear filtered texel adjustment
};
enum
{
	RENDERER_NONE,
	RENDERER_INTERNAL,
	RENDERER_HAL,
	RENDERER_HOWMANY
};

enum
{
	TEXEL_NEVER,
	TEXEL_WHENFILTERING,
	TEXEL_ALWAYS,
	TEXEL_HOWMANY
};
global struct AppSettings G_AppSettings;

#define DXCB_FRONT 1
#define DXCB_BACK 2
#define DXCB_THIRD 4
#define DXCB_ZBUFFER 8
#define DXCB_RENDER 16
#define DXCB_PICTURE 32
#define DXCB_CLIENT 64
#define DXCB_CLRWINDOW 256

bool HWR_Init();
void HWR_InitVertexList();
bool HWR_IsVertexBufferFull();
void HWR_InitState();
void HWR_BeginScene();
void HWR_EndScene();
void HWR_DrawPolyList();
void HWR_LoadTexturePages(int nPages, char* pImage, uint8* pPalette);
void HWR_FreeTexturePages();
void HWR_RestoreTexturePages();
void HWR_ResetCurrentTexture();
void HWR_ResetColorKey();
void HWR_ResetZBuffer();
void HWR_SetCurrentTexture(DWORD dwHandle);
void HWR_EnableColorKey(bool tEnable);
void HWR_EnableZBuffer(bool tWrite, bool tCompare);
void HWR_GetAllTextureHandles();
extern "C" void __cdecl HWR_DrawRoomBucket(void*);

bool TIME_Init();

/*** misc ***/
inline bool DX_TRY(HRESULT hr)
{
	if (SUCCEEDED(hr))
		return false;
	Log(LT_Error, "ERROR : %s", ERR_Describe_DX(hr));
	return true;
}

inline bool DX_FAILED(HRESULT hr)
{
	return FAILED(hr);
}

#endif<commit_msg>Fix clang warning<commit_after>#ifndef INCLUDE_H
#define INCLUDE_H

#include "STANDARD.H"

#include <stdbool.h>
#include <windows.h>
#include <mmsystem.h>
#include <ddraw.h>
#include <d3d.h>
#include <dinput.h>
#include <dsound.h>
#include <windowsx.h>
#include <time.h>
#include "SPECIFIC.H"
#include <stdio.h>

#if !defined(__cplusplus)
//#error Dude insists on C++ !!!
#endif

#define global extern
#define local static
#define defglobal

typedef void* Handle;

enum
{
	LOG_OUTPUT,
	LOG_RESET,
	LOG_END
};

#define LOG_DO_STRLEN 0xffffffff

//#define Log2(type, fmt, ...) Log_real("[DBLOG] [%s] %s", STRINGIFY(type), )

//#define Log(type, fmt, ...) S_Warn("[DBLOG] [" STRINGIFY(type) "] " fmt, __VA_ARGS__)
#define Log(type, fmt, ...) Log_real(type, #type, fmt, __VA_ARGS__)

#define ArraySize(a) (sizeof(a)/sizeof((a)[0]))
#define Zero(thing) memset(&(thing),0,sizeof(thing))
#define ZeroArray(a) memset((a),0,sizeof(a))
#define EndOfArray(a) ((a)+ArraySize(a))
#define InitDXStruct(s) memset(&(s),0,sizeof(s)),(s).dwSize=sizeof(s)
#define DefLocalString(x,y) local char Lsz##x[]=y
#define LocalString(x) Lsz##x
#define DefValueName(x) local char Lsz##x[]=#x
#define ValueName(x) Lsz##x
#define Align(x,b) ((x)=(x)&~((b)-1))

void DebugPrint(const char* message);
void Log_backend(char type, char* fmt, ...);
inline void Log_real(char ctype, const char* type, const char* fmt, ...)
{
	char buf[128], pbuf[1024];
	char tbuf[15];
	memset(tbuf, ' ', 14);
	tbuf[14] = 0;
	strcpy(tbuf, type + 3);
	ZeroArray(buf);
	ZeroArray(pbuf);
	strcpy(buf, "[DBLOG] [");
	strcat(buf, tbuf);
	strcat(buf, "] ");

	va_list args;
	va_start(args, fmt);
	vsprintf(pbuf, fmt, args);
	va_end(args);

	char res[1152];
	ZeroArray(res);
	strcat(res, buf);
	strcat(res, pbuf);

	DebugPrint(res);
	Log_backend(ctype, pbuf);
}

/*** dxerror.cpp ***/
char* ERR_Describe_DX(HRESULT hr);
char* ERR_Describe_Init(int nError);

enum InitResult	// possible initialisation results
{
	INIT_OK,

	INIT_ERR_PreferredAdapterNotFound,
	INIT_ERR_CantCreateWindow,
	INIT_ERR_CantCreateDirectDraw,
	INIT_ERR_CantInitRenderer,
	INIT_ERR_CantCreateDirectInput,
	INIT_ERR_CantCreateKeyboardDevice,
	INIT_ERR_CantSetKBCooperativeLevel,
	INIT_ERR_CantSetKBDataFormat,
	INIT_ERR_CantAcquireKeyboard,
	INIT_ERR_CantSetDSCooperativeLevel,

	INIT_ERR_DD_SetExclusiveMode,
	INIT_ERR_DD_ClearExclusiveMode,
	INIT_ERR_SetDisplayMode,
	INIT_ERR_CreateScreenBuffers,
	INIT_ERR_GetBackBuffer,
	INIT_ERR_CreatePalette,
	INIT_ERR_SetPalette,
	INIT_ERR_CreatePrimarySurface,
	INIT_ERR_CreateBackBuffer,
	INIT_ERR_CreateClipper,
	INIT_ERR_SetClipperHWnd,
	INIT_ERR_SetClipper,
	INIT_ERR_CreateZBuffer,
	INIT_ERR_AttachZBuffer,
	INIT_ERR_CreateRenderBuffer,
	INIT_ERR_CreatePictureBuffer,
	INIT_ERR_D3D_Create,
	INIT_ERR_CreateDevice,
	INIT_ERR_CreateViewport,
	INIT_ERR_AddViewport,
	INIT_ERR_SetViewport2,
	INIT_ERR_SetCurrentViewport,

	INIT_ERR_ClearRenderBuffer,
	INIT_ERR_UpdateRenderInfo,
	INIT_ERR_GetThirdBuffer,

	INIT_ERR_GoFullScreen,
	INIT_ERR_GoWindowed,

	INIT_ERR_WrongBitDepth,
	INIT_ERR_GetPixelFormat,
	INIT_ERR_GetDisplayMode
};
typedef void* Position;	// iterator for linked lists etc
/*** settings.cpp ***/
struct AppSettings
{
	Position DisplayAdapter;			// G_DisplayAdapterList[DisplayAdapter] is the one we're using...
	Position SoundAdapter;				// same for sound card
	Position Joystick;					// and joystick
	Position FullScreenMode;			// hardware fullscreen mode x/y/bpp
	int nRenderMode;					// none/internal/HAL/RGB
	int nWindowWidth, nWindowHeight;		// size of desktop window
	int nAspectMode;					// 4:3 / 16:9 / any
	bool tPerspectiveCorrect;			// perspective correct textures
	bool tDither;						// dithering on/off
	bool tZBuffer;						// render using z buffer
	bool tBilinearFiltering;			// use bilinear filtering when texture mapping
	bool tTripleBuffering;				// use three buffers instead of two, for better performance but more memory usage
										//	bool tMipMap;						// use mipmapped textures
										//	bool tAntialias;					// antialias edges
	bool tFullScreen;					// switch to full screen or run in window
	bool tSoundEnabled;					// false = disable sound
	bool tLaraMic;						// position mic at lara instead of camera (for paul & toby)
	bool tJoystickEnabled;				// false = disable joystick
	bool tDisable16BitTextures;			// true = disable 16 bit textures (for 2MB Mystique etc)
	bool tDontSortPrimitives;			// true = no need to sort primitives (for PowerVR)
	bool tFlipBroken;					// true = driver doesn't wait for flip to finish before rendering.  must do it myself...
	bool tDisableFMV;					// true = don't play any FMVs
	int nTexelAdjustMode;				// never / when filtering / always
	int nNearestAdjustment;				// non-filtered texel adjustment
	int nLinearAdjustment;				// bilinear filtered texel adjustment
};
enum
{
	RENDERER_NONE,
	RENDERER_INTERNAL,
	RENDERER_HAL,
	RENDERER_HOWMANY
};

enum
{
	TEXEL_NEVER,
	TEXEL_WHENFILTERING,
	TEXEL_ALWAYS,
	TEXEL_HOWMANY
};
global struct AppSettings G_AppSettings;

#define DXCB_FRONT 1
#define DXCB_BACK 2
#define DXCB_THIRD 4
#define DXCB_ZBUFFER 8
#define DXCB_RENDER 16
#define DXCB_PICTURE 32
#define DXCB_CLIENT 64
#define DXCB_CLRWINDOW 256

bool HWR_Init();
void HWR_InitVertexList();
bool HWR_IsVertexBufferFull();
void HWR_InitState();
void HWR_BeginScene();
void HWR_EndScene();
void HWR_DrawPolyList();
void HWR_LoadTexturePages(int nPages, char* pImage, uint8* pPalette);
void HWR_FreeTexturePages();
void HWR_RestoreTexturePages();
void HWR_ResetCurrentTexture();
void HWR_ResetColorKey();
void HWR_ResetZBuffer();
void HWR_SetCurrentTexture(DWORD dwHandle);
void HWR_EnableColorKey(bool tEnable);
void HWR_EnableZBuffer(bool tWrite, bool tCompare);
void HWR_GetAllTextureHandles();
extern "C" void __cdecl HWR_DrawRoomBucket(void*);

bool TIME_Init();

/*** misc ***/
inline bool DX_TRY(HRESULT hr)
{
	if (SUCCEEDED(hr))
		return false;
	Log(LT_Error, "ERROR : %s", ERR_Describe_DX(hr));
	return true;
}

inline bool DX_FAILED(HRESULT hr)
{
	return FAILED(hr);
}

#endif<|endoftext|>


<commit_before>#include "PSOUTPUT.H"

#include "SPECTYPES.H"
#include "SPECIFIC.H"

static struct VIBRATION vib[2];

void VibratePad()//604EC, 61064
{
	return;
}

void SetupPadVibration(short num, short acc, short lev, short sus, int dec, int len)//604A4(<), 6101C(<) (F)
{
	struct VIBRATION* v = &vib[num];

	v->Acc = acc;
	v->Lev = lev;
	v->Flag = 0;
	v->Rate = 0;
	v->Vib = 0;
	v->Sus = len - dec;
	v->Dec = dec;
	v->Len = len;

	return;
}<commit_msg>Add VibratePad()<commit_after>#include "PSOUTPUT.H"

#include "PSXINPUT.H"
#include "SAVEGAME.H"
#include "SPECTYPES.H"

static struct VIBRATION vib[2];

void VibratePad()//604EC(<), 61064(<) (F)
{
	int i;
	struct VIBRATION* v;

	if (DualShock == 0 && savegame.VibrateOn)
	{
		//loc_60510
		Motors[0] = 0;
		Motors[1] = 0;
		return;
	}

	//loc_6052C
	for (i = 0; i < 2; i++, v = &vib[i])
	{
		if (v->Len != 0)
		{
			if (v->Flag == 0)
			{
				v->Rate += v->Acc;

				if (v->Rate > v->Lev)
				{
					v->Rate = v->Lev;
					v->Flag = 1;
				}//loc_605DC
			}
			else if (v->Flag == 1)
			{
				//loc_60588
				if (v->Sus > v->Len)
				{
					v->Flag = 2;
				}//loc_605DC
			}
			else if (v->Flag == 2)
			{
				//loc_605AC
				v->Rate -= v->Dec;

				if (v->Rate * 65536 < 0)
				{
					v->Rate = 0;
					v->Flag = 3;
				}//loc_605DC
			}

			//loc_605DC
			v->Vib += v->Rate;

			if (i != 0)
			{
				if (v->Vib / 16 != 0)
				{
					Motors[1] = v->Vib / 16;
					v->Vib &= 0xFF;
				}//loc_60650
				else
				{
					//loc_60618
					Motors[1] = 0;
				}//loc_60650
			}
			else
			{
				//loc_60628
				if (v->Vib / 24 != 0)
				{
					Motors[0] = 1;
					v->Vib -= 4096;
				}
				else
				{
					//loc_60648
					Motors[0] = 0;
				}

				//loc_60650
				v->Len--;
			}
		}
		else
		{
			//loc_60664
			Motors[i] = 0;
		}
	}
}

void SetupPadVibration(short num, short acc, short lev, short sus, int dec, int len)//604A4(<), 6101C(<) (F)
{
	struct VIBRATION* v = &vib[num];

	v->Acc = acc;
	v->Lev = lev;
	v->Flag = 0;
	v->Rate = 0;
	v->Vib = 0;
	v->Sus = len - dec;
	v->Dec = dec;
	v->Len = len;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QDebug>
#include <QtDeclarative/QDeclarativeExtensionPlugin>
#include <QtDeclarative/qdeclarative.h>

#include "qsparqlresultslist_p.h"

QSparqlResultsList::QSparqlResultsList(QObject *parent) :
    QAbstractListModel(parent),
    m_connection(0), m_result(0), m_options(0)
{
}

int QSparqlResultsList::rowCount(const QModelIndex &) const
{
    return m_result->size();
}

QVariant QSparqlResultsList::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    m_result->setPos(index.row());
    QSparqlResultRow row = m_result->current();
    int i = role - (Qt::UserRole + 1);

    if (i >= row.count())
        return row.binding(i - row.count()).toString();
    else
        return row.value(i);
}

void QSparqlResultsList::reload()
{
    if (m_options == 0 || m_query.isEmpty())
        return;

    if (m_result != 0) {
        if (!m_result->isFinished())
            return;
        else
            delete m_result;
    }

    delete m_connection;

    /* Create and run the sparql query */
    m_connection = new QSparqlConnection(m_options->driverName(), m_options->options());
    m_result = m_connection->exec(QSparqlQuery(m_query));
    connect(m_result, SIGNAL(finished()), this, SLOT(queryFinished()));
}

void QSparqlResultsList::queryFinished()
{
    QHash<int, QByteArray> roleNames;
    roleNames = QAbstractItemModel::roleNames();

    if (m_result->first()) {
        QSparqlResultRow resultRow = m_result->current();

        // Create two set of declarative variables from the variable names used
        // in the select statement
        // 'foo' is just a literal like 1234, but '$foo' is "1234"^^xsd:integer
        // 'bar' is a string 'http://www.w3.org/2002/07/owl#sameAs', but '$bar'
        // is a uri <http://www.w3.org/2002/07/owl#sameAs>
        for (int i = 0; i < resultRow.count(); i++) {
            roleNames.insert((Qt::UserRole + 1) + i, resultRow.binding(i).name().toLatin1());
        }

        for (int i = 0; i < resultRow.count(); i++) {
            roleNames.insert((Qt::UserRole + 1) + i + resultRow.count(), QByteArray("$") + resultRow.binding(i).name().toLatin1());
        }

        setRoleNames(roleNames);
    }

    reset();
}

QSparqlConnectionOptionsWrapper* QSparqlResultsList::options() const
{
    return m_options;
}

void QSparqlResultsList::setOptions(QSparqlConnectionOptionsWrapper *options)
{
    m_options = options;
    reload();
}

QString QSparqlResultsList::query() const
{
    return m_query;
}

void
QSparqlResultsList::setQuery(const QString &query)
{
    m_query = query;
    reload();
}
<commit_msg>* Remove the QtDeclarative header includes as QSparqlResultsList doesn't have any declarative code in it<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QDebug>

#include "qsparqlresultslist_p.h"

QSparqlResultsList::QSparqlResultsList(QObject *parent) :
    QAbstractListModel(parent),
    m_connection(0), m_result(0), m_options(0)
{
}

int QSparqlResultsList::rowCount(const QModelIndex &) const
{
    return m_result->size();
}

QVariant QSparqlResultsList::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    m_result->setPos(index.row());
    QSparqlResultRow row = m_result->current();
    int i = role - (Qt::UserRole + 1);

    if (i >= row.count())
        return row.binding(i - row.count()).toString();
    else
        return row.value(i);
}

void QSparqlResultsList::reload()
{
    if (m_options == 0 || m_query.isEmpty())
        return;

    if (m_result != 0) {
        if (!m_result->isFinished())
            return;
        else
            delete m_result;
    }

    delete m_connection;

    /* Create and run the sparql query */
    m_connection = new QSparqlConnection(m_options->driverName(), m_options->options());
    m_result = m_connection->exec(QSparqlQuery(m_query));
    connect(m_result, SIGNAL(finished()), this, SLOT(queryFinished()));
}

void QSparqlResultsList::queryFinished()
{
    QHash<int, QByteArray> roleNames;
    roleNames = QAbstractItemModel::roleNames();

    if (m_result->first()) {
        QSparqlResultRow resultRow = m_result->current();

        // Create two set of declarative variables from the variable names used
        // in the select statement
        // 'foo' is just a literal like 1234, but '$foo' is "1234"^^xsd:integer
        // 'bar' is a string 'http://www.w3.org/2002/07/owl#sameAs', but '$bar'
        // is a uri <http://www.w3.org/2002/07/owl#sameAs>
        for (int i = 0; i < resultRow.count(); i++) {
            roleNames.insert((Qt::UserRole + 1) + i, resultRow.binding(i).name().toLatin1());
        }

        for (int i = 0; i < resultRow.count(); i++) {
            roleNames.insert((Qt::UserRole + 1) + i + resultRow.count(), QByteArray("$") + resultRow.binding(i).name().toLatin1());
        }

        setRoleNames(roleNames);
    }

    reset();
}

QSparqlConnectionOptionsWrapper* QSparqlResultsList::options() const
{
    return m_options;
}

void QSparqlResultsList::setOptions(QSparqlConnectionOptionsWrapper *options)
{
    m_options = options;
    reload();
}

QString QSparqlResultsList::query() const
{
    return m_query;
}

void
QSparqlResultsList::setQuery(const QString &query)
{
    m_query = query;
    reload();
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef MAKE_UNIQUE_H__
#define MAKE_UNIQUE_H__

#include <cstdlib>
#include <memory>
#include <type_traits>

namespace osrm
{
// Taken from http://msdn.microsoft.com/en-us/library/dn439780.asp
// Note, that the snippet is broken there and needed minor massaging

// make_unique<T>
template <class T, class... Types> std::unique_ptr<T> make_unique(Types &&... Args)
{
    return (std::unique_ptr<T>(new T(std::forward<Types>(Args)...)));
}

// make_unique<T[]>
template <class T> std::unique_ptr<T> make_unique(std::size_t Size)
{
    return (std::unique_ptr<T>(new T[Size]()));
}

// make_unique<T[N]> disallowed
template <class T, class... Types>
typename std::enable_if<std::extent<T>::value != 0, void>::type make_unique(Types &&...) = delete;
}
#endif
<commit_msg>fix typo<commit_after>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef MAKE_UNIQUE_H__
#define MAKE_UNIQUE_H__

#include <cstdlib>
#include <memory>
#include <type_traits>

namespace osrm
{
// Taken from http://msdn.microsoft.com/en-us/library/dn439780.asp
// Note, that the snippet was broken there and needed minor massaging

// make_unique<T>
template <class T, class... Types> std::unique_ptr<T> make_unique(Types &&... Args)
{
    return (std::unique_ptr<T>(new T(std::forward<Types>(Args)...)));
}

// make_unique<T[]>
template <class T> std::unique_ptr<T> make_unique(std::size_t Size)
{
    return (std::unique_ptr<T>(new T[Size]()));
}

// make_unique<T[N]> disallowed
template <class T, class... Types>
typename std::enable_if<std::extent<T>::value != 0, void>::type make_unique(Types &&...) = delete;
}
#endif
<|endoftext|>