<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "savefmtdialog.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QInputDialog>
#include <QApplication>
#include <QStyle>

using namespace Vipster;

MainWindow::MainWindow(QString path, QWidget *parent):
    QMainWindow{parent},
    ui{new Ui::MainWindow},
    path{path}
{
    ui->setupUi(this);
    connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);
    connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);
    setupUI();
    newMol();
}

MainWindow::MainWindow(QString path, std::vector<IO::Data> &&d, QWidget *parent):
    QMainWindow{parent},
    ui{new Ui::MainWindow},
    path{path}
{
    ui->setupUi(this);
    setupUI();
    connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);
    connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);
    for(auto&& mol: d){
        newData(std::move(mol));
    }
}

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

void MainWindow::setupUI()
{
    ui->firstStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));
    ui->preStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));
    ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    ui->nextStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekForward));
    ui->lastStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));
    // setup left dock-area
    baseWidgets = {
        ui->paramDock,
        ui->configDock,
        ui->settingsDock,
        ui->mpseDock,
        ui->pseDock,
        ui->dataDock,
    };
    for(auto& w: baseWidgets){
        tabifyDockWidget(ui->molDock, w);
    }
    ui->molDock->raise();
    // setup right dock-area
    toolWidgets = {
        ui->scriptDock,
        ui->pickDock,
        ui->cellModDock,
        ui->millerDock,
    };
    for(auto& w: toolWidgets){
        auto action = ui->toolBar->addAction(w->windowTitle());
        action->setCheckable(true);
        connect(action, &QAction::toggled, w, &QWidget::setVisible);
        w->hide();
    }
#ifdef Q_OS_MACOS
    setDockOptions(dockOptions()^VerticalTabs);
#endif
    // fill in global PSE
    ui->pseWidget->setPSE(&Vipster::pse);
    // fill in menu-options
    for(const auto& pair:IOPlugins){
        const auto& param_map = Vipster::params[pair.first];
        if(!param_map.empty()){
            auto* param_menu = ui->menuLoad_Parameter_set->addMenu(
                        QString::fromStdString(pair.second->name));
            for(const auto& p: param_map){
                param_menu->addAction(QString::fromStdString(p.first),
                                      this, &MainWindow::loadParam);
            }
        }
        const auto& conf_map = Vipster::configs[pair.first];
        if(!conf_map.empty()){
            auto* conf_menu = ui->menuLoad_IO_Config->addMenu(
                        QString::fromStdString(pair.second->name));
            for(const auto& p: conf_map){
                conf_menu->addAction(QString::fromStdString(p.first),
                                     this, &MainWindow::loadConfig);
            }
        }
    }
}

void MainWindow::updateWidgets(uint8_t change)
{
    ui->openGLWidget->updateWidget(change);
    ui->molWidget->updateWidget(change);
    for(auto& w: baseWidgets){
        static_cast<BaseWidget*>(w->widget())->updateWidget(change);
    }
    for(auto& w: toolWidgets){
        static_cast<BaseWidget*>(w->widget())->updateWidget(change);
    }
}

void MainWindow::setFmt(int i, bool apply, bool scale)
{
    fmt = static_cast<AtomFmt>(i);
    if(apply){
        curStep->setFmt(fmt, scale);
        if(curSel){
            curSel->setFmt(fmt);
        }
        updateWidgets(guiStepChanged);
    }else{
        updateWidgets(GuiChange::fmt);
    }
}

AtomFmt MainWindow::getFmt()
{
    return fmt;
}

void MainWindow::setMol(int i)
{
    curMol = &*std::next(molecules.begin(), i);
    int nstep = static_cast<int>(curMol->getNstep());
    if(moldata[curMol].curStep < 0){
        moldata[curMol].curStep = nstep;
    }
    //Step-control
    ui->stepLabel->setText(QString::number(nstep));
    QSignalBlocker boxBlocker(ui->stepEdit);
    QSignalBlocker slideBlocker(ui->stepSlider);
    ui->stepEdit->setMaximum(nstep);
    ui->stepSlider->setMaximum(nstep);
    if(nstep == 1){
        ui->stepEdit->setDisabled(true);
        ui->stepSlider->setDisabled(true);
    }else{
        ui->stepEdit->setEnabled(true);
        ui->stepSlider->setEnabled(true);
    }
    setStep(moldata[curMol].curStep);
    updateWidgets(guiMolChanged);
}

void MainWindow::setStep(int i)
{
    moldata[curMol].curStep = i;
    curStep = &curMol->getStep(static_cast<size_t>(i-1));
    fmt = curStep->getFmt();
    // if no previous selection exists, create one, afterwards assign it
    auto& tmpSel = stepdata[curStep].sel;
    if(!tmpSel && curStep){
        tmpSel = std::make_unique<StepSelection>(*curStep);
    }
    curSel = tmpSel.get();
    //Handle control-elements
    if(playTimer.isActive() && (i == static_cast<int>(curMol->getNstep()))){
        playTimer.stop();
        ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    }
    QSignalBlocker boxBlocker(ui->stepEdit);
    QSignalBlocker slideBlocker(ui->stepSlider);
    ui->stepEdit->setValue(i);
    ui->stepSlider->setValue(i);
    if(i == 1){
        ui->preStepButton->setDisabled(true);
        ui->firstStepButton->setDisabled(true);
    }else{
        ui->preStepButton->setEnabled(true);
        ui->firstStepButton->setEnabled(true);
    }
    if(i == static_cast<int>(curMol->getNstep())){
        ui->nextStepButton->setDisabled(true);
        ui->lastStepButton->setDisabled(true);
    }else{
        ui->nextStepButton->setEnabled(true);
        ui->lastStepButton->setEnabled(true);
    }
    //Update child widgets
    updateWidgets(guiStepChanged);
}

void MainWindow::stepBut(QAbstractButton* but)
{
    if(but == ui->firstStepButton){
        setStep(1);
    }else if(but == ui->lastStepButton){
        setStep(static_cast<int>(curMol->getNstep()));
    }else if(but == ui->playButton){
        if(playTimer.isActive()){
            playTimer.stop();
            ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
        }else{
            playTimer.start(1000);
            ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
        }
    }
}

void MainWindow::editAtoms(QAction* sender)
{
    if ( sender == ui->actionNew_Atom){
        curStep->newAtom();
    }else if ( sender == ui->actionDelete_Atom_s){
        curSel->delAtoms();
    }else if ( sender == ui->actionHide_Atom_s){
        for(auto& at: *curSel){
            at.properties->flags[AtomFlag::Hidden] = 1;
        }
    }else if ( sender == ui->actionShow_Atom_s){
        for(auto& at: *curSel){
            at.properties->flags[AtomFlag::Hidden] = 0;
        }
    }
    updateWidgets(GuiChange::atoms);
}

void MainWindow::newMol()
{
    molecules.emplace_back();
    ui->molWidget->registerMol(molecules.back().getName());
}

void MainWindow::newData(IO::Data &&d)
{
    molecules.push_back(std::move(d.mol));
    ui->molWidget->registerMol(molecules.back().getName());
    if(d.param){
        ui->paramWidget->registerParam(d.fmt, std::move(d.param));
    }
    for(auto& dat: d.data){
        data.push_back(std::move(dat));
        ui->dataWidget->registerData(data.back()->name);
    }
}

void MainWindow::loadMol()
{
    // File dialog
    QStringList files;
    QFileDialog fileDiag{this};
    fileDiag.setDirectory(path);
    fileDiag.setFileMode(QFileDialog::ExistingFiles);
    // Format dialog
    QStringList formats{};
    for(auto &iop: IOPlugins){
        formats << QString::fromStdString(iop.second->name);
    }
    QString fmt_s;
    IOFmt fmt;
    bool got_fmt{false};
    if(fileDiag.exec() != 0){
        files = fileDiag.selectedFiles();
        path = fileDiag.directory();
        if(files.count() != 0){
            fmt_s = QInputDialog::getItem(this, "Select format", "Format:",
                                          formats, 0, false, &got_fmt);
            if(got_fmt){
                fmt = static_cast<IOFmt>(formats.indexOf(fmt_s));
                for(auto &file: files){
                    newData(readFile(file.toStdString(), fmt));
                }
            }
        }
    }
}

void MainWindow::saveMol()
{
    QFileDialog fileDiag{this};
    fileDiag.setDirectory(path);
    fileDiag.setAcceptMode(QFileDialog::AcceptSave);
    if(fileDiag.exec() == QDialog::Accepted){
        auto target = fileDiag.selectedFiles()[0].toStdString();
        path = fileDiag.directory();
        SaveFmtDialog sfd{this};
        if(sfd.exec() == QDialog::Accepted){
            writeFile(target, sfd.fmt, *curMol,
                      sfd.getParam(), sfd.getConfig(),
                      IO::State{static_cast<size_t>(ui->stepSlider->value()-1),
                                this->fmt,
                                ui->molWidget->getCellFmt()});
        }
    }
}

const decltype (ParamWidget::params)& MainWindow::getParams() const noexcept
{
    return ui->paramWidget->params;
}

const decltype (ConfigWidget::configs)& MainWindow::getConfigs() const noexcept
{
    return ui->configWidget->configs;
}

void MainWindow::addExtraData(GUI::Data* dat)
{
    ui->openGLWidget->addExtraData(dat);
    updateWidgets(GuiChange::extra);
}

void MainWindow::delExtraData(GUI::Data* dat)
{
    ui->openGLWidget->delExtraData(dat);
    updateWidgets(GuiChange::extra);
}

const GUI::GlobalData& MainWindow::getGLGlobals()
{
    return ui->openGLWidget->globals;
}

void MainWindow::loadParam()
{
    auto* s = static_cast<QAction*>(sender());
    auto* p = static_cast<QMenu*>(s->parent());
    IOFmt fmt = [](QString name){
        for(const auto& pair:IOPlugins){
            if(name == pair.second->name.c_str()){
                return pair.first;
            }
        }
        throw Error("Invalid parameter set");
    }(p->title());
    auto pos = Vipster::params[fmt].find(s->text().toStdString());
    if(pos != Vipster::params[fmt].end()){
        ui->paramWidget->registerParam(fmt, pos->second->copy());
    }else{
        throw Error("Invalid parameter set");
    }
}

void MainWindow::loadConfig()
{
    auto* s = static_cast<QAction*>(sender());
    auto* p = static_cast<QMenu*>(s->parent());
    IOFmt fmt = [](QString name){
        for(const auto& pair:IOPlugins){
            if(name == pair.second->name.c_str()){
                return pair.first;
            }
        }
        throw Error("Invalid IO-config");
    }(p->title());
    auto pos = Vipster::configs[fmt].find(s->text().toStdString());
    if(pos != Vipster::configs[fmt].end()){
        ui->configWidget->registerConfig(fmt, pos->second->copy());
    }else{
        throw Error("Invalid IO-config");
    }
}

void MainWindow::saveParam()
{
    if(!ui->paramWidget->curParam){
        return;
    }
    bool ok;
    auto name = QInputDialog::getText(this, "Save parameter set", "Name of preset",
                                      QLineEdit::Normal, QString(), &ok);
    if(ok){
        Vipster::params[ui->paramWidget->curFmt][name.toStdString()] =
                ui->paramWidget->curParam->copy();
    }
}

void MainWindow::saveConfig()
{
    if(!ui->configWidget->curConfig){
        return;
    }
    bool ok;
    auto name = QInputDialog::getText(this, "Save IO-Config", "Name of preset",
                                      QLineEdit::Normal, QString(), &ok);
    if(ok){
        Vipster::configs[ui->configWidget->curFmt][name.toStdString()] =
                ui->configWidget->curConfig->copy();
    }
}

void MainWindow::about()
{
    QMessageBox::about(this,QString("About Vipster"),
    QString("
Vipster
"
            "
"
            "©Sebastian Gsänger, 2018"
            "
"
            "Homepage"
            "
"
            "Source"
            "
"
            "
"
            "This program is provided under the GPLv3."
            "
"
            "It uses"
            "JSON for Modern C++, "
            "CLI11,"
            "Catch2 and "
            "pybind11."
            "
"));
}

void MainWindow::saveScreenshot()
{
    QFileDialog diag{this};
    diag.setDirectory(path);
    diag.setAcceptMode(QFileDialog::AcceptSave);
    diag.setMimeTypeFilters({"image/png"});
    if(diag.exec() == QDialog::Accepted){
        auto target = diag.selectedFiles()[0];
        if(!target.endsWith(".png", Qt::CaseInsensitive)){
            target += ".png";
        }
        path = diag.directory();

        auto aa = settings.antialias.val;
        settings.antialias.val = false;
        auto img = ui->openGLWidget->grabFramebuffer();
        img.save(target);
        settings.antialias.val = aa;
        updateWidgets(0);
    }
}
<commit_msg>set names when saving param/config<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "savefmtdialog.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QInputDialog>
#include <QApplication>
#include <QStyle>

using namespace Vipster;

MainWindow::MainWindow(QString path, QWidget *parent):
    QMainWindow{parent},
    ui{new Ui::MainWindow},
    path{path}
{
    ui->setupUi(this);
    connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);
    connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);
    setupUI();
    newMol();
}

MainWindow::MainWindow(QString path, std::vector<IO::Data> &&d, QWidget *parent):
    QMainWindow{parent},
    ui{new Ui::MainWindow},
    path{path}
{
    ui->setupUi(this);
    setupUI();
    connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);
    connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);
    for(auto&& mol: d){
        newData(std::move(mol));
    }
}

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

void MainWindow::setupUI()
{
    ui->firstStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));
    ui->preStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));
    ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    ui->nextStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekForward));
    ui->lastStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));
    // setup left dock-area
    baseWidgets = {
        ui->paramDock,
        ui->configDock,
        ui->settingsDock,
        ui->mpseDock,
        ui->pseDock,
        ui->dataDock,
    };
    for(auto& w: baseWidgets){
        tabifyDockWidget(ui->molDock, w);
    }
    ui->molDock->raise();
    // setup right dock-area
    toolWidgets = {
        ui->scriptDock,
        ui->pickDock,
        ui->cellModDock,
        ui->millerDock,
    };
    for(auto& w: toolWidgets){
        auto action = ui->toolBar->addAction(w->windowTitle());
        action->setCheckable(true);
        connect(action, &QAction::toggled, w, &QWidget::setVisible);
        w->hide();
    }
#ifdef Q_OS_MACOS
    setDockOptions(dockOptions()^VerticalTabs);
#endif
    // fill in global PSE
    ui->pseWidget->setPSE(&Vipster::pse);
    // fill in menu-options
    for(const auto& pair:IOPlugins){
        const auto& param_map = Vipster::params[pair.first];
        if(!param_map.empty()){
            auto* param_menu = ui->menuLoad_Parameter_set->addMenu(
                        QString::fromStdString(pair.second->name));
            for(const auto& p: param_map){
                param_menu->addAction(QString::fromStdString(p.first),
                                      this, &MainWindow::loadParam);
            }
        }
        const auto& conf_map = Vipster::configs[pair.first];
        if(!conf_map.empty()){
            auto* conf_menu = ui->menuLoad_IO_Config->addMenu(
                        QString::fromStdString(pair.second->name));
            for(const auto& p: conf_map){
                conf_menu->addAction(QString::fromStdString(p.first),
                                     this, &MainWindow::loadConfig);
            }
        }
    }
}

void MainWindow::updateWidgets(uint8_t change)
{
    ui->openGLWidget->updateWidget(change);
    ui->molWidget->updateWidget(change);
    for(auto& w: baseWidgets){
        static_cast<BaseWidget*>(w->widget())->updateWidget(change);
    }
    for(auto& w: toolWidgets){
        static_cast<BaseWidget*>(w->widget())->updateWidget(change);
    }
}

void MainWindow::setFmt(int i, bool apply, bool scale)
{
    fmt = static_cast<AtomFmt>(i);
    if(apply){
        curStep->setFmt(fmt, scale);
        if(curSel){
            curSel->setFmt(fmt);
        }
        updateWidgets(guiStepChanged);
    }else{
        updateWidgets(GuiChange::fmt);
    }
}

AtomFmt MainWindow::getFmt()
{
    return fmt;
}

void MainWindow::setMol(int i)
{
    curMol = &*std::next(molecules.begin(), i);
    int nstep = static_cast<int>(curMol->getNstep());
    if(moldata[curMol].curStep < 0){
        moldata[curMol].curStep = nstep;
    }
    //Step-control
    ui->stepLabel->setText(QString::number(nstep));
    QSignalBlocker boxBlocker(ui->stepEdit);
    QSignalBlocker slideBlocker(ui->stepSlider);
    ui->stepEdit->setMaximum(nstep);
    ui->stepSlider->setMaximum(nstep);
    if(nstep == 1){
        ui->stepEdit->setDisabled(true);
        ui->stepSlider->setDisabled(true);
    }else{
        ui->stepEdit->setEnabled(true);
        ui->stepSlider->setEnabled(true);
    }
    setStep(moldata[curMol].curStep);
    updateWidgets(guiMolChanged);
}

void MainWindow::setStep(int i)
{
    moldata[curMol].curStep = i;
    curStep = &curMol->getStep(static_cast<size_t>(i-1));
    fmt = curStep->getFmt();
    // if no previous selection exists, create one, afterwards assign it
    auto& tmpSel = stepdata[curStep].sel;
    if(!tmpSel && curStep){
        tmpSel = std::make_unique<StepSelection>(*curStep);
    }
    curSel = tmpSel.get();
    //Handle control-elements
    if(playTimer.isActive() && (i == static_cast<int>(curMol->getNstep()))){
        playTimer.stop();
        ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    }
    QSignalBlocker boxBlocker(ui->stepEdit);
    QSignalBlocker slideBlocker(ui->stepSlider);
    ui->stepEdit->setValue(i);
    ui->stepSlider->setValue(i);
    if(i == 1){
        ui->preStepButton->setDisabled(true);
        ui->firstStepButton->setDisabled(true);
    }else{
        ui->preStepButton->setEnabled(true);
        ui->firstStepButton->setEnabled(true);
    }
    if(i == static_cast<int>(curMol->getNstep())){
        ui->nextStepButton->setDisabled(true);
        ui->lastStepButton->setDisabled(true);
    }else{
        ui->nextStepButton->setEnabled(true);
        ui->lastStepButton->setEnabled(true);
    }
    //Update child widgets
    updateWidgets(guiStepChanged);
}

void MainWindow::stepBut(QAbstractButton* but)
{
    if(but == ui->firstStepButton){
        setStep(1);
    }else if(but == ui->lastStepButton){
        setStep(static_cast<int>(curMol->getNstep()));
    }else if(but == ui->playButton){
        if(playTimer.isActive()){
            playTimer.stop();
            ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
        }else{
            playTimer.start(1000);
            ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
        }
    }
}

void MainWindow::editAtoms(QAction* sender)
{
    if ( sender == ui->actionNew_Atom){
        curStep->newAtom();
    }else if ( sender == ui->actionDelete_Atom_s){
        curSel->delAtoms();
    }else if ( sender == ui->actionHide_Atom_s){
        for(auto& at: *curSel){
            at.properties->flags[AtomFlag::Hidden] = 1;
        }
    }else if ( sender == ui->actionShow_Atom_s){
        for(auto& at: *curSel){
            at.properties->flags[AtomFlag::Hidden] = 0;
        }
    }
    updateWidgets(GuiChange::atoms);
}

void MainWindow::newMol()
{
    molecules.emplace_back();
    ui->molWidget->registerMol(molecules.back().getName());
}

void MainWindow::newData(IO::Data &&d)
{
    molecules.push_back(std::move(d.mol));
    ui->molWidget->registerMol(molecules.back().getName());
    if(d.param){
        ui->paramWidget->registerParam(d.fmt, std::move(d.param));
    }
    for(auto& dat: d.data){
        data.push_back(std::move(dat));
        ui->dataWidget->registerData(data.back()->name);
    }
}

void MainWindow::loadMol()
{
    // File dialog
    QStringList files;
    QFileDialog fileDiag{this};
    fileDiag.setDirectory(path);
    fileDiag.setFileMode(QFileDialog::ExistingFiles);
    // Format dialog
    QStringList formats{};
    for(auto &iop: IOPlugins){
        formats << QString::fromStdString(iop.second->name);
    }
    QString fmt_s;
    IOFmt fmt;
    bool got_fmt{false};
    if(fileDiag.exec() != 0){
        files = fileDiag.selectedFiles();
        path = fileDiag.directory();
        if(files.count() != 0){
            fmt_s = QInputDialog::getItem(this, "Select format", "Format:",
                                          formats, 0, false, &got_fmt);
            if(got_fmt){
                fmt = static_cast<IOFmt>(formats.indexOf(fmt_s));
                for(auto &file: files){
                    newData(readFile(file.toStdString(), fmt));
                }
            }
        }
    }
}

void MainWindow::saveMol()
{
    QFileDialog fileDiag{this};
    fileDiag.setDirectory(path);
    fileDiag.setAcceptMode(QFileDialog::AcceptSave);
    if(fileDiag.exec() == QDialog::Accepted){
        auto target = fileDiag.selectedFiles()[0].toStdString();
        path = fileDiag.directory();
        SaveFmtDialog sfd{this};
        if(sfd.exec() == QDialog::Accepted){
            writeFile(target, sfd.fmt, *curMol,
                      sfd.getParam(), sfd.getConfig(),
                      IO::State{static_cast<size_t>(ui->stepSlider->value()-1),
                                this->fmt,
                                ui->molWidget->getCellFmt()});
        }
    }
}

const decltype (ParamWidget::params)& MainWindow::getParams() const noexcept
{
    return ui->paramWidget->params;
}

const decltype (ConfigWidget::configs)& MainWindow::getConfigs() const noexcept
{
    return ui->configWidget->configs;
}

void MainWindow::addExtraData(GUI::Data* dat)
{
    ui->openGLWidget->addExtraData(dat);
    updateWidgets(GuiChange::extra);
}

void MainWindow::delExtraData(GUI::Data* dat)
{
    ui->openGLWidget->delExtraData(dat);
    updateWidgets(GuiChange::extra);
}

const GUI::GlobalData& MainWindow::getGLGlobals()
{
    return ui->openGLWidget->globals;
}

void MainWindow::loadParam()
{
    auto* s = static_cast<QAction*>(sender());
    auto* p = static_cast<QMenu*>(s->parent());
    IOFmt fmt = [](QString name){
        for(const auto& pair:IOPlugins){
            if(name == pair.second->name.c_str()){
                return pair.first;
            }
        }
        throw Error("Invalid parameter set");
    }(p->title());
    auto pos = Vipster::params[fmt].find(s->text().toStdString());
    if(pos != Vipster::params[fmt].end()){
        ui->paramWidget->registerParam(fmt, pos->second->copy());
    }else{
        throw Error("Invalid parameter set");
    }
}

void MainWindow::loadConfig()
{
    auto* s = static_cast<QAction*>(sender());
    auto* p = static_cast<QMenu*>(s->parent());
    IOFmt fmt = [](QString name){
        for(const auto& pair:IOPlugins){
            if(name == pair.second->name.c_str()){
                return pair.first;
            }
        }
        throw Error("Invalid IO-config");
    }(p->title());
    auto pos = Vipster::configs[fmt].find(s->text().toStdString());
    if(pos != Vipster::configs[fmt].end()){
        ui->configWidget->registerConfig(fmt, pos->second->copy());
    }else{
        throw Error("Invalid IO-config");
    }
}

void MainWindow::saveParam()
{
    if(!ui->paramWidget->curParam){
        return;
    }
    bool ok;
    auto name = QInputDialog::getText(this, "Save parameter set", "Name of preset",
                                      QLineEdit::Normal, QString(), &ok).toStdString();
    if(ok){
        Vipster::params[ui->paramWidget->curFmt][name] =
                ui->paramWidget->curParam->copy();
        Vipster::params[ui->paramWidget->curFmt][name]->name = name;
    }
}

void MainWindow::saveConfig()
{
    if(!ui->configWidget->curConfig){
        return;
    }
    bool ok;
    auto name = QInputDialog::getText(this, "Save IO-Config", "Name of preset",
                                      QLineEdit::Normal, QString(), &ok).toStdString();
    if(ok){
        Vipster::configs[ui->configWidget->curFmt][name] =
                ui->configWidget->curConfig->copy();
        Vipster::configs[ui->configWidget->curFmt][name]->name = name;
    }
}

void MainWindow::about()
{
    QMessageBox::about(this,QString("About Vipster"),
    QString("
Vipster
"
            "
"
            "©Sebastian Gsänger, 2018"
            "
"
            "Homepage"
            "
"
            "Source"
            "
"
            "
"
            "This program is provided under the GPLv3."
            "
"
            "It uses"
            "JSON for Modern C++, "
            "CLI11,"
            "Catch2 and "
            "pybind11."
            "
"));
}

void MainWindow::saveScreenshot()
{
    QFileDialog diag{this};
    diag.setDirectory(path);
    diag.setAcceptMode(QFileDialog::AcceptSave);
    diag.setMimeTypeFilters({"image/png"});
    if(diag.exec() == QDialog::Accepted){
        auto target = diag.selectedFiles()[0];
        if(!target.endsWith(".png", Qt::CaseInsensitive)){
            target += ".png";
        }
        path = diag.directory();

        auto aa = settings.antialias.val;
        settings.antialias.val = false;
        auto img = ui->openGLWidget->grabFramebuffer();
        img.save(target);
        settings.antialias.val = aa;
        updateWidgets(0);
    }
}
<|endoftext|>


<commit_before><commit_msg>:sparkles: feat(echo-server-stackful): add an example of echo-serevr using boost.asio with stackful corotine<commit_after><|endoftext|>


<commit_before>#include "polygon_triangulation.hpp"
#include "cpp/ylikuutio/common/globals.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <vector>   // std::vector

namespace geometry
{
    bool triangulate_simple_polygon(
            TriangulatePolygonsStruct triangulate_polygons_struct,
            std::vector<glm::vec3> &out_vertices,
            std::vector<glm::vec2> &out_UVs,
            std::vector<glm::vec3> &out_normals)
    {
        // TODO: implement this function!
    }

    bool triangulate_polygons(
            TriangulatePolygonsStruct triangulate_polygons_struct,
            std::vector<glm::vec3> &out_vertices,
            std::vector<glm::vec2> &out_UVs,
            std::vector<glm::vec3> &out_normals)
    {
        // TODO: implement this function!

        // Find hidden vertices using `get_intersection_point(geometry::LineSegment2D* line_segment1, geometry::LineSegment2D* line_segment2)`.
        std::vector<std::vector<glm::vec2>>* vertex_data = triangulate_polygons_struct.input_vertices;

        // Each edge may have intersections with any other intersections
        // except immediately previous and immediately next intersections.
        // TODO: write the code!

        for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)
        {
        }

        // All vertices (3D, explicitly defined and hidden) should be known now.

        // Divide complex polygons into simple polygons. Each vertex belongs to 1 or more simple polygons.
        // TODO: write the code!
        std::vector<std::vector<glm::vec3>> simple_polygons;

        for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)
        {
        }

        // Loop through simple polygons and triangulate them.
        // TODO: write the code!

        return false;
    }
}
<commit_msg>Bugfix: Added `return false` to `bool triangulate_simple_polygon`.<commit_after>#include "polygon_triangulation.hpp"
#include "cpp/ylikuutio/common/globals.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <vector>   // std::vector

namespace geometry
{
    bool triangulate_simple_polygon(
            TriangulatePolygonsStruct triangulate_polygons_struct,
            std::vector<glm::vec3> &out_vertices,
            std::vector<glm::vec2> &out_UVs,
            std::vector<glm::vec3> &out_normals)
    {
        // TODO: implement this function!
        return false;
    }

    bool triangulate_polygons(
            TriangulatePolygonsStruct triangulate_polygons_struct,
            std::vector<glm::vec3> &out_vertices,
            std::vector<glm::vec2> &out_UVs,
            std::vector<glm::vec3> &out_normals)
    {
        // TODO: implement this function!

        // Find hidden vertices using `get_intersection_point(geometry::LineSegment2D* line_segment1, geometry::LineSegment2D* line_segment2)`.
        std::vector<std::vector<glm::vec2>>* vertex_data = triangulate_polygons_struct.input_vertices;

        // Each edge may have intersections with any other intersections
        // except immediately previous and immediately next intersections.
        // TODO: write the code!

        for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)
        {
        }

        // All vertices (3D, explicitly defined and hidden) should be known now.

        // Divide complex polygons into simple polygons. Each vertex belongs to 1 or more simple polygons.
        // TODO: write the code!
        std::vector<std::vector<glm::vec3>> simple_polygons;

        for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)
        {
        }

        // Loop through simple polygons and triangulate them.
        // TODO: write the code!

        return false;
    }
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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 "cyber/scheduler/policy/scheduler_choreography.h"

#include <memory>

#include "cyber/scheduler/processor.h"
#include "cyber/scheduler/policy/choreography.h"
#include "cyber/scheduler/policy/classic.h"

namespace apollo {
namespace cyber {
namespace scheduler {

using apollo::cyber::common::GlobalData;

SchedulerChoreography::SchedulerChoreography() {
  sched_policy_ = SchedPolicy::CHOREO;

  auto gconf = GlobalData::Instance()->Config();
  for (auto& conf : gconf.scheduler_conf().confs()) {
    sched_confs_[conf.name()] = conf;
  }

  auto desc = SchedName_descriptor()->
      FindValueByName(GlobalData::Instance()->SchedName());
  int sname;
  if (desc) {
    sname = desc->number();

    SchedConf sconf;
    auto itr = sched_confs_.find(sname);
    if (itr != sched_confs_.end()) {
      proc_num_ = itr->second.proc_num();
      task_pool_size_ = itr->second.task_pool_size();
      cpu_binding_start_index_ = itr->second.cpu_binding_start_index();
    }
  }

  for (auto& conf : gconf.choreo_conf()) {
    if (conf.sched_name() == sname) {
      for (auto& choreo : conf.choreos()) {
        cr_confs_[choreo.name()] = choreo;
      }
    }
  }

  // default val for case w/o config:
  if (proc_num_ == 0) {
    proc_num_ = std::thread::hardware_concurrency() / 4 * 3;
    // FIXME: other vals ... ?
  }
  // Currently for compatible with task/task_manager.cc,
  // will be deleted at last:
  // auto pool_size = scheduler::Scheduler::Instance()->TaskPoolSize();
  task_pool_size_ = std::thread::hardware_concurrency() / 4;

  CreateProcessor();
}

void SchedulerChoreography::CreateProcessor() {
  for (uint32_t i = 0; i < proc_num_; i++) {
    auto proc = std::make_shared<Processor>();
    auto ctx = std::make_shared<ChoreoGraphyContext>();

    proc->BindContext(ctx);
    proc->SetBindCpuIndex(cpu_binding_start_index_ + i);
    ctx->BindProc(proc);
    proc_ctxs_.emplace_back(ctx);

    proc->Start();
  }

  // For choreography policy: put tasks w/o processor assigned
  // to a classic pool.
  for (uint32_t i = 0; i < task_pool_size_; i++) {
    auto proc = std::make_shared<Processor>();
    auto ctx = std::make_shared<ClassicContext>();

    proc->BindContext(ctx);
    proc->SetBindCpuIndex(cpu_binding_start_index_ + proc_num_ + i);
    ctx->BindProc(proc);
    proc_ctxs_.emplace_back(ctx);

    classic_4_choreo_ = ctx.get();

    proc->Start();
  }
}

}  // namespace scheduler
}  // namespace cyber
}  // namespace apollo

<commit_msg>framework: make task_pool_size configurable again<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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 "cyber/scheduler/policy/scheduler_choreography.h"

#include <memory>

#include "cyber/scheduler/processor.h"
#include "cyber/scheduler/policy/choreography.h"
#include "cyber/scheduler/policy/classic.h"

namespace apollo {
namespace cyber {
namespace scheduler {

using apollo::cyber::common::GlobalData;

SchedulerChoreography::SchedulerChoreography() {
  sched_policy_ = SchedPolicy::CHOREO;

  auto gconf = GlobalData::Instance()->Config();
  for (auto& conf : gconf.scheduler_conf().confs()) {
    sched_confs_[conf.name()] = conf;
  }

  auto desc = SchedName_descriptor()->
      FindValueByName(GlobalData::Instance()->SchedName());
  int sname;
  if (desc) {
    sname = desc->number();

    SchedConf sconf;
    auto itr = sched_confs_.find(sname);
    if (itr != sched_confs_.end()) {
      proc_num_ = itr->second.proc_num();
      task_pool_size_ = itr->second.task_pool_size();
      cpu_binding_start_index_ = itr->second.cpu_binding_start_index();
    }
  }

  for (auto& conf : gconf.choreo_conf()) {
    if (conf.sched_name() == sname) {
      for (auto& choreo : conf.choreos()) {
        cr_confs_[choreo.name()] = choreo;
      }
    }
  }

  // default val for case w/o config:
  if (proc_num_ == 0) {
    proc_num_ = std::thread::hardware_concurrency() / 4 * 3;
    // FIXME: other vals ... ?
  }
  // Currently for compatible with task/task_manager.cc,
  // will be deleted at last:
  // auto pool_size = scheduler::Scheduler::Instance()->TaskPoolSize();
  // task_pool_size_ = std::thread::hardware_concurrency() / 4;

  CreateProcessor();
}

void SchedulerChoreography::CreateProcessor() {
  for (uint32_t i = 0; i < proc_num_; i++) {
    auto proc = std::make_shared<Processor>();
    auto ctx = std::make_shared<ChoreoGraphyContext>();

    proc->BindContext(ctx);
    proc->SetBindCpuIndex(cpu_binding_start_index_ + i);
    ctx->BindProc(proc);
    proc_ctxs_.emplace_back(ctx);

    proc->Start();
  }

  // For choreography policy: put tasks w/o processor assigned
  // to a classic pool.
  for (uint32_t i = 0; i < task_pool_size_; i++) {
    auto proc = std::make_shared<Processor>();
    auto ctx = std::make_shared<ClassicContext>();

    proc->BindContext(ctx);
    proc->SetBindCpuIndex(cpu_binding_start_index_ + proc_num_ + i);
    ctx->BindProc(proc);
    proc_ctxs_.emplace_back(ctx);

    classic_4_choreo_ = ctx.get();

    proc->Start();
  }
}

}  // namespace scheduler
}  // namespace cyber
}  // namespace apollo

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2014.  All rights reserved
 */
//  TEST    Foundation::Configuration
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Configuration/Enumeration.h"
#include    "Stroika/Foundation/Configuration/Version.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;

namespace   {
    void    Test1_Version_ ()
    {
        const   Configuration::Version  kTestVersion_ =
            Configuration::Version (1, 0, Configuration::VersionStage::Alpha, 1, false
                                   )
            ;
        VerifyTestResult (kTestVersion_.AsPrettyVersionString () == L"1.0a1x");
    }
}

namespace {
    void    Test2_EnumNames_ ()
    {
        using   namespace Configuration;
        enum class fooEnum {
            eOne,
            eTwo,
        };
        const EnumNames<fooEnum>   Stroika_Enum_Names(fooEnum) = {
            { fooEnum::eOne, L"eOne" },
            { fooEnum::eTwo, L"eTwo" },
        };
        Verify (wstring (L"eOne") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eOne));
        Verify (wstring (L"eTwo") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eTwo));
    }
}

namespace   {
    void    DoRegressionTests_ ()
    {
        Test1_Version_ ();
        Test2_EnumNames_ ();
    }
}

int main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<commit_msg>enhance Stroika_Enum_Names() regtest<commit_after>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2014.  All rights reserved
 */
//  TEST    Foundation::Configuration
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Configuration/Enumeration.h"
#include    "Stroika/Foundation/Configuration/Version.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;

namespace   {
    void    Test1_Version_ ()
    {
        const   Configuration::Version  kTestVersion_ =
            Configuration::Version (1, 0, Configuration::VersionStage::Alpha, 1, false
                                   )
            ;
        VerifyTestResult (kTestVersion_.AsPrettyVersionString () == L"1.0a1x");
    }
}

namespace {
    void    Test2_EnumNames_ ()
    {
        using   namespace Configuration;
        enum class fooEnum {
            eOne,
            eTwo,
        };
        {
            const EnumNames<fooEnum>   Stroika_Enum_Names(fooEnum) = {
                { fooEnum::eOne, L"eOne" },
                { fooEnum::eTwo, L"eTwo" },
            };
            Verify (wstring (L"eOne") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eOne));
            Verify (wstring (L"eTwo") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eTwo));
        }
        {
            static  const EnumNames<fooEnum>   Stroika_Enum_Names(fooEnum) = {
                { fooEnum::eOne, L"eOne" },
                { fooEnum::eTwo, L"eTwo" },
            };
            Verify (wstring (L"eOne") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eOne));
            Verify (wstring (L"eTwo") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eTwo));
        }
    }
}

namespace   {
    void    DoRegressionTests_ ()
    {
        Test1_Version_ ();
        Test2_EnumNames_ ();
    }
}

int main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2014.  All rights reserved
 */
//  TEST    Foundation::Containers::Mapping
//      STATUS  Alpha-Late
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    <iostream>
#include    <sstream>

#include    "Stroika/Foundation/Containers/Mapping.h"
#include    "Stroika/Foundation/Containers/Concrete/Mapping_Array.h"
#include    "Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.h"
#include    "Stroika/Foundation/Containers/Concrete/Mapping_stdmap.h"
#include    "Stroika/Foundation/Containers/Concrete/SortedMapping_stdmap.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "../TestCommon/CommonTests_Mapping.h"
#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;

using   Concrete::Mapping_Array;
using   Concrete::Mapping_LinkedList;
using   Concrete::Mapping_stdmap;

namespace {
    template    <typename   CONCRETE_CONTAINER>
    void    DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_ ()
    {
        auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {
            // only work todo on sorted mappings
        };
        CommonTests::MappingTests::SimpleMappingTest_AllTestsWhichDontRequireComparer_For_Type_<CONCRETE_CONTAINER> (extraChecksFunction);
    }
    template    <typename   CONCRETE_CONTAINER>
    void    DoTestForConcreteContainer_ ()
    {
        auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {
            // only work todo on sorted mappings
        };
        CommonTests::MappingTests::SimpleMappingTest_All_For_Type<CONCRETE_CONTAINER> (extraChecksFunction);
    }
}

namespace {
    void    Test2_SimpleBaseClassConversionTraitsConfusion_ ()
    {
        SortedMapping<int, float> xxxyy = Concrete::SortedMapping_stdmap<int, float> ();
        Mapping<int, float> xxxyy1 = Concrete::Mapping_stdmap<int, float> ();
    }
}

namespace {
    template <typename CONTAINER, typename COMPARER>
    void    doIt_t3_()
    {
        CommonTests::MappingTests::SimpleMappingTest_WhichRequiresExplcitValueComparer<CONTAINER, COMPARER> ([] (const CONTAINER & c) {});
    }
    void    Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ()
    {
        doIt_t3_<Mapping_LinkedList<size_t, size_t>, Common::ComparerWithEquals<size_t>> ();
    }
}

namespace {
    namespace Test4_MappingCTOROverloads_ {
        namespace xPrivate_ {
            struct A;
            struct B;
            struct A {
                A() {}
                A(const A&) {}
                A(const B&) {}
            };
            struct B {
                B() {}
                B(const A&) {}
                B(const B&) {}
            };

            using Common::KeyValuePair;
            using KEY_TYPE = int;
            using VALUE_TYPE = B;
            using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;

            struct aaaaaa {
//              template    <typename X>
                using X = T;
                static auto check(const X& x) ->
                std::conditional <
                Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and
                std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,
                    Configuration::substitution_succeeded <T>,
                    Configuration::substitution_failure
                    >::type
                    ;
//                  static Configuration::substitution_failure check (...);
                using type = decltype(check(declval<T>()));
            };

        }
        void DoIt ()
        {
            using namespace xPrivate_;
            Mapping<int, A> from;

            using Common::KeyValuePair;
            using KEY_TYPE = int;
            using VALUE_TYPE = B;
            using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            bool n1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;
            //bool n2 = Configuration::IsIterableOfT2<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;

            using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;
            using ttt =
                std::conditional <
                Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and
                std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,
                Configuration::substitution_succeeded <T>,
                Configuration::substitution_failure
                >::type;
            const bool n3 = is_same<ttt, Configuration::substitution_failure>::value;

            using aaaa3 = Configuration::Private_::IsIterableOfT_Impl2_<CONTAINER_OF_PAIR_KEY_T, T>::type;
            const bool n4 = is_same<aaaa3, Configuration::substitution_failure>::value;

            const bool n5 = is_same<aaaaaa::type, Configuration::substitution_failure>::value;

#if 0
            bool xxx1 = std::is_convertible<const Mapping<int, A>*, const Mapping<int, B>*>::value;
            bool xxx2 = Configuration::IsIterableOfT<Mapping<int, A>, KeyValuePair<int, B>>::value;
            using Common::KeyValuePair;
            using KEY_TYPE = int;
            using VALUE_TYPE = B;
            using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            bool xxxxx1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;
            bool xxxxx2 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;
            //bool xxxxx3 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value);
            //bool xxxxx = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value or Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;
#endif
            Mapping<int, B> to1;
            for (auto i : from) {
                to1.Add (i);
            }
            Mapping<int, B> to2 = from;
        }
    }
}

namespace   {
    void    DoRegressionTests_ ()
    {
        struct  MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {
            using   ElementType =   SimpleClassWithoutComparisonOperators;
            static  bool    Equals (ElementType v1, ElementType v2)
            {
                return v1.GetValue () == v2.GetValue ();
            }
        };
        using   SimpleClassWithoutComparisonOperators_MappingTRAITS =   DefaultTraits::Mapping <
                SimpleClassWithoutComparisonOperators,
                SimpleClassWithoutComparisonOperators,
                MySimpleClassWithoutComparisonOperators_ComparerWithEquals_
                >   ;

        DoTestForConcreteContainer_<Mapping<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();

        DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();

        DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();

        DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> ();
        {
            struct  MySimpleClassWithoutComparisonOperators_ComparerWithCompare_ : MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {
                using   ElementType =   SimpleClassWithoutComparisonOperators;
                static  int    Compare (ElementType v1, ElementType v2)
                {
                    return Common::CompareNormalizer (v1.GetValue (), v2.GetValue ());
                }
            };
            using   SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS =
                Concrete::Mapping_stdmap_DefaultTraits <
                SimpleClassWithoutComparisonOperators,
                SimpleClassWithoutComparisonOperators,
                MySimpleClassWithoutComparisonOperators_ComparerWithEquals_,
                MySimpleClassWithoutComparisonOperators_ComparerWithCompare_
                >;
            DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS>> ();
        }

        Test2_SimpleBaseClassConversionTraitsConfusion_ ();

        Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ();

        Test4_MappingCTOROverloads_::DoIt ();
    }
}

int     main (int argc, const char* argv[])
{
	struct foo {
	 const Mapping<int,int> cx;
	};
	foo bar;
	foo ddd = bar;
	if (auto i = ddd.cx.Lookup (1)) {
		int j = *i;
	}

    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}
<commit_msg>undid accidental 'foo' checkin<commit_after>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2014.  All rights reserved
 */
//  TEST    Foundation::Containers::Mapping
//      STATUS  Alpha-Late
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    <iostream>
#include    <sstream>

#include    "Stroika/Foundation/Containers/Mapping.h"
#include    "Stroika/Foundation/Containers/Concrete/Mapping_Array.h"
#include    "Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.h"
#include    "Stroika/Foundation/Containers/Concrete/Mapping_stdmap.h"
#include    "Stroika/Foundation/Containers/Concrete/SortedMapping_stdmap.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "../TestCommon/CommonTests_Mapping.h"
#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;

using   Concrete::Mapping_Array;
using   Concrete::Mapping_LinkedList;
using   Concrete::Mapping_stdmap;

namespace {
    template    <typename   CONCRETE_CONTAINER>
    void    DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_ ()
    {
        auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {
            // only work todo on sorted mappings
        };
        CommonTests::MappingTests::SimpleMappingTest_AllTestsWhichDontRequireComparer_For_Type_<CONCRETE_CONTAINER> (extraChecksFunction);
    }
    template    <typename   CONCRETE_CONTAINER>
    void    DoTestForConcreteContainer_ ()
    {
        auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {
            // only work todo on sorted mappings
        };
        CommonTests::MappingTests::SimpleMappingTest_All_For_Type<CONCRETE_CONTAINER> (extraChecksFunction);
    }
}

namespace {
    void    Test2_SimpleBaseClassConversionTraitsConfusion_ ()
    {
        SortedMapping<int, float> xxxyy = Concrete::SortedMapping_stdmap<int, float> ();
        Mapping<int, float> xxxyy1 = Concrete::Mapping_stdmap<int, float> ();
    }
}

namespace {
    template <typename CONTAINER, typename COMPARER>
    void    doIt_t3_()
    {
        CommonTests::MappingTests::SimpleMappingTest_WhichRequiresExplcitValueComparer<CONTAINER, COMPARER> ([] (const CONTAINER & c) {});
    }
    void    Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ()
    {
        doIt_t3_<Mapping_LinkedList<size_t, size_t>, Common::ComparerWithEquals<size_t>> ();
    }
}

namespace {
    namespace Test4_MappingCTOROverloads_ {
        namespace xPrivate_ {
            struct A;
            struct B;
            struct A {
                A() {}
                A(const A&) {}
                A(const B&) {}
            };
            struct B {
                B() {}
                B(const A&) {}
                B(const B&) {}
            };

            using Common::KeyValuePair;
            using KEY_TYPE = int;
            using VALUE_TYPE = B;
            using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;

            struct aaaaaa {
//              template    <typename X>
                using X = T;
                static auto check(const X& x) ->
                std::conditional <
                Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and
                std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,
                    Configuration::substitution_succeeded <T>,
                    Configuration::substitution_failure
                    >::type
                    ;
//                  static Configuration::substitution_failure check (...);
                using type = decltype(check(declval<T>()));
            };

        }
        void DoIt ()
        {
            using namespace xPrivate_;
            Mapping<int, A> from;

            using Common::KeyValuePair;
            using KEY_TYPE = int;
            using VALUE_TYPE = B;
            using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            bool n1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;
            //bool n2 = Configuration::IsIterableOfT2<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;

            using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;
            using ttt =
                std::conditional <
                Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and
                std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,
                Configuration::substitution_succeeded <T>,
                Configuration::substitution_failure
                >::type;
            const bool n3 = is_same<ttt, Configuration::substitution_failure>::value;

            using aaaa3 = Configuration::Private_::IsIterableOfT_Impl2_<CONTAINER_OF_PAIR_KEY_T, T>::type;
            const bool n4 = is_same<aaaa3, Configuration::substitution_failure>::value;

            const bool n5 = is_same<aaaaaa::type, Configuration::substitution_failure>::value;

#if 0
            bool xxx1 = std::is_convertible<const Mapping<int, A>*, const Mapping<int, B>*>::value;
            bool xxx2 = Configuration::IsIterableOfT<Mapping<int, A>, KeyValuePair<int, B>>::value;
            using Common::KeyValuePair;
            using KEY_TYPE = int;
            using VALUE_TYPE = B;
            using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            bool xxxxx1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;
            bool xxxxx2 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;
            //bool xxxxx3 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value);
            //bool xxxxx = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value or Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;
#endif
            Mapping<int, B> to1;
            for (auto i : from) {
                to1.Add (i);
            }
            Mapping<int, B> to2 = from;
        }
    }
}

namespace   {
    void    DoRegressionTests_ ()
    {
        struct  MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {
            using   ElementType =   SimpleClassWithoutComparisonOperators;
            static  bool    Equals (ElementType v1, ElementType v2)
            {
                return v1.GetValue () == v2.GetValue ();
            }
        };
        using   SimpleClassWithoutComparisonOperators_MappingTRAITS =   DefaultTraits::Mapping <
                SimpleClassWithoutComparisonOperators,
                SimpleClassWithoutComparisonOperators,
                MySimpleClassWithoutComparisonOperators_ComparerWithEquals_
                >   ;

        DoTestForConcreteContainer_<Mapping<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();

        DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();

        DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();

        DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> ();
        {
            struct  MySimpleClassWithoutComparisonOperators_ComparerWithCompare_ : MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {
                using   ElementType =   SimpleClassWithoutComparisonOperators;
                static  int    Compare (ElementType v1, ElementType v2)
                {
                    return Common::CompareNormalizer (v1.GetValue (), v2.GetValue ());
                }
            };
            using   SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS =
                Concrete::Mapping_stdmap_DefaultTraits <
                SimpleClassWithoutComparisonOperators,
                SimpleClassWithoutComparisonOperators,
                MySimpleClassWithoutComparisonOperators_ComparerWithEquals_,
                MySimpleClassWithoutComparisonOperators_ComparerWithCompare_
                >;
            DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS>> ();
        }

        Test2_SimpleBaseClassConversionTraitsConfusion_ ();

        Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ();

        Test4_MappingCTOROverloads_::DoIt ();
    }
}

int     main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
//  TEST    Foundation::Execution::Signals
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Sanitizer.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#include "Stroika/Foundation/Execution/Sleep.h"

#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"

using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;

using Containers::Set;

namespace {
    void Test1_Basic_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE ("thread") void Test2_Direct_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::Type::eDirect));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    void Test3_Safe_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {

    void DoRegressionTests_ ()
    {
        Test1_Basic_ ();
        Test2_Direct_ ();
        Test3_Safe_ ();
    }
}

int main (int argc, const char* argv[])
{
    SignalHandlerRegistry::SafeSignalsManager safeSignals;
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>Enhanced Test1_Basic_ regtest to hopfully workaround/fix TSAN reported error about race writing to variable<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
//  TEST    Foundation::Execution::Signals
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Sanitizer.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#include "Stroika/Foundation/Execution/Sleep.h"

#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"

using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;

using Containers::Set;

namespace {
    void Test1_Basic_ ()
    {
        {
            Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
            {
                // atomic CAN be used with SAFE signal handlers
                atomic<bool> called = false;
                SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::eSafe));
                ::raise (SIGINT);
                Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
                VerifyTestResult (called);
            }
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
        }
        {
            Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
            {
                // atomic CAN be used with direct signal handlers
                atomic<bool> called = false;
                SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::eDirect));
                ::raise (SIGINT);
                Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
                VerifyTestResult (called);
            }
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
        }
        {
            Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
            {
                // Synchronized CAN be used with SAFE signal handlers
                Synchronized<bool> called = false;
                SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::eSafe));
                ::raise (SIGINT);
                Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
                VerifyTestResult (called);
            }
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
        }
    }
}

namespace {
    Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE ("thread") void Test2_Direct_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::Type::eDirect));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    void Test3_Safe_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {

    void DoRegressionTests_ ()
    {
        Test1_Basic_ ();
        Test2_Direct_ ();
        Test3_Safe_ ();
    }
}

int main (int argc, const char* argv[])
{
    SignalHandlerRegistry::SafeSignalsManager safeSignals;
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|>


<commit_before>// SSSSCpp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>

#include <assert.h>
#define UINT unsigned int

using std::vector; using std::pair;
using std::make_pair;

int _tmain(int argc, _TCHAR* argv[])
{
	GF256init();
	PGF256 hi = generateRandomPolynomial(5, 0x08);
	vector<pair<UINT, UINT>> lol = encodeByte(15, 5, 3);
	vector<pair<UINT, UINT>> lol2;
	lol2.push_back(make_pair(225, 113));
	lol2.push_back(make_pair(32, 247));
	lol2.push_back(make_pair(249, 248));
	UINT result = decodeByte(lol2);
	return 0;
}

<commit_msg>added trivial test case.<commit_after>// SSSSCpp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>

#include <assert.h>
#define UINT unsigned int

using std::vector; using std::pair;
using std::make_pair;

int _tmain(int argc, _TCHAR* argv[])
{
	GF256init();
	PGF256 hi = generateRandomPolynomial(5, 0x08);
	vector<pair<UINT, UINT>> lol = encodeByte(15, 5, 3);
	vector<pair<UINT, UINT>> lol2;
	lol2.push_back(make_pair(1, 17));
	lol2.push_back(make_pair(2, 34));
	lol2.push_back(make_pair(3, 61));
	//lol2.push_back(make_pair(225, 113));
	//lol2.push_back(make_pair(32, 247));
	//lol2.push_back(make_pair(249, 248));
	UINT result = decodeByte(lol2);
	return 0;
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "Interpret\SmartView\SmartView.h"
#include "Interpret\SmartView\SmartViewParser.h"
#include "MFCMAPI.h"
#include "resource.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace SmartViewTest
{
	TEST_CLASS(SmartViewTest)
	{
	private:
		struct SmartViewTestResource {
			__ParsingTypeEnum structType;
			bool parseAll;
			DWORD hex;
			DWORD expected;
		};

		struct SmartViewTestData {
			__ParsingTypeEnum structType;
			bool parseAll;
			wstring testName;
			wstring hex;
			wstring expected;
		};

		const bool parseAll = false;
		wstring ParseString(wstring hexString, __ParsingTypeEnum iStructType)
		{
			auto bin = HexStringToBin(hexString);
			return InterpretBinaryAsString({ bin.size(), bin.data() }, iStructType, nullptr);
		}

		void test(vector<SmartViewTestData> testData)
		{
			for (auto data : testData)
			{
				AreEqualEx(data.expected, ParseString(data.hex, data.structType), data.testName.c_str());

				if (data.parseAll) {
					for (ULONG i = IDS_STNOPARSING; i < IDS_STEND; i++) {
						//Logger::WriteMessage(format(L"Testing %ws\n", AddInStructTypeToString(static_cast<__ParsingTypeEnum>(i)).c_str()).c_str());
						Assert::IsTrue(ParseString(data.hex, data.structType).length() != 0);
					}
				}
			}
		}

		// Resource files saved in unicode have a byte order mark of 0xfeff
		// We load these in and strip the BOM.
		// Otherwise we load as ansi and convert to unicode
		wstring loadfile(HMODULE handle, int name)
		{
			auto rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(TEXTFILE));
			auto rcData = ::LoadResource(handle, rc);
			auto cb = ::SizeofResource(handle, rc);
			auto bytes = ::LockResource(rcData);
			auto data = static_cast<const BYTE*>(bytes);
			if (cb >= 2 && data[0] == 0xfe && data[1] == 0xff)
			{
				// Skip the byte order mark
				auto wstr = static_cast<const wchar_t*>(bytes);
				auto cch = cb / sizeof(wchar_t);
				return std::wstring(wstr + 1, cch - 1);
			}

			auto str = std::string(static_cast<const char*>(bytes), cb);
			return stringTowstring(str);
		}

		vector<SmartViewTestData> loadTestData(HMODULE handle, std::initializer_list<SmartViewTestResource> resources)
		{
			vector<SmartViewTestData> testData;
			for (auto resource : resources)
			{
				testData.push_back(SmartViewTestData
					{
						resource.structType, resource.parseAll,
						format(L"%d/%d", resource.hex, resource.expected),
						loadfile(handle, resource.hex),
						loadfile(handle, resource.expected)
					});
			}

			return testData;
		}

	public:
		TEST_CLASS_INITIALIZE(Initialize_smartview)
		{
			// Set up our property arrays or nothing works
			MergeAddInArrays();

			RegKeys[regkeyDO_SMART_VIEW].ulCurDWORD = 1;
			RegKeys[regkeyUSE_GETPROPLIST].ulCurDWORD = 1;
			RegKeys[regkeyPARSED_NAMED_PROPS].ulCurDWORD = 1;
			RegKeys[regkeyCACHE_NAME_DPROPS].ulCurDWORD = 1;

			setTestInstance(::GetModuleHandleW(L"UnitTest.dll"));
		}

		TEST_METHOD(Test_STADDITIONALRENENTRYIDSEX)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI1IN, IDR_SV1AEI1OUT },
					SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI2IN, IDR_SV1AEI2OUT },
				}));
		}

		TEST_METHOD(Test_STAPPOINTMENTRECURRENCEPATTERN)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP1IN, IDR_SV2ARP1OUT },
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP2IN, IDR_SV2ARP2OUT },
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP3IN, IDR_SV2ARP3OUT },
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP4IN, IDR_SV2ARP4OUT },
				}));
		}

		TEST_METHOD(Test_STCONVERSATIONINDEX)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI1IN, IDR_SV3CI1OUT },
					SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI2IN, IDR_SV3CI2OUT },
					SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI3IN, IDR_SV3CI3OUT },
				}));
		}

		TEST_METHOD(Test_STENTRYID)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID1IN, IDR_SV4EID1OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID2IN, IDR_SV4EID2OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID3IN, IDR_SV4EID3OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID4IN, IDR_SV4EID4OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID5IN, IDR_SV4EID5OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID6IN, IDR_SV4EID6OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID7IN, IDR_SV4EID7OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID8IN, IDR_SV4EID8OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID9IN, IDR_SV4EID9OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID10IN, IDR_SV4EID10OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID11IN, IDR_SV4EID11OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID12IN, IDR_SV4EID12OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID13IN, IDR_SV4EID13OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID14IN, IDR_SV4EID14OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID15IN, IDR_SV4EID15OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID16IN, IDR_SV4EID16OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID17IN, IDR_SV4EID17OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID18IN, IDR_SV4EID18OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID19IN, IDR_SV4EID19OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID20IN, IDR_SV4EID20OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID21IN, IDR_SV4EID21OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID22IN, IDR_SV4EID22OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID23IN, IDR_SV4EID23OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID24IN, IDR_SV4EID24OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID25IN, IDR_SV4EID25OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID26IN, IDR_SV4EID26OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID27IN, IDR_SV4EID27OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID28IN, IDR_SV4EID28OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID29IN, IDR_SV4EID29OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID30IN, IDR_SV4EID30OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID31IN, IDR_SV4EID31OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID32IN, IDR_SV4EID32OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID33IN, IDR_SV4EID33OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID34IN, IDR_SV4EID34OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID35IN, IDR_SV4EID35OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID36IN, IDR_SV4EID36OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID37IN, IDR_SV4EID37OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID38IN, IDR_SV4EID38OUT }
				}));
		}
	};
}<commit_msg>Do HexStringToBin on load<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "Interpret\SmartView\SmartView.h"
#include "Interpret\SmartView\SmartViewParser.h"
#include "MFCMAPI.h"
#include "resource.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace SmartViewTest
{
	TEST_CLASS(SmartViewTest)
	{
	private:
		struct SmartViewTestResource {
			__ParsingTypeEnum structType;
			bool parseAll;
			DWORD hex;
			DWORD expected;
		};

		struct SmartViewTestData {
			__ParsingTypeEnum structType;
			bool parseAll;
			wstring testName;
			vector<BYTE> hex;
			wstring expected;
		};

		const bool parseAll = false;
		wstring ParseString(vector<BYTE> hex, __ParsingTypeEnum iStructType)
		{
			return InterpretBinaryAsString({ hex.size(), hex.data() }, iStructType, nullptr);
		}

		void test(vector<SmartViewTestData> testData)
		{
			for (auto data : testData)
			{
				AreEqualEx(data.expected, ParseString(data.hex, data.structType), data.testName.c_str());

				if (data.parseAll) {
					for (ULONG i = IDS_STNOPARSING; i < IDS_STEND; i++) {
						//Logger::WriteMessage(format(L"Testing %ws\n", AddInStructTypeToString(static_cast<__ParsingTypeEnum>(i)).c_str()).c_str());
						Assert::IsTrue(ParseString(data.hex, data.structType).length() != 0);
					}
				}
			}
		}

		// Resource files saved in unicode have a byte order mark of 0xfeff
		// We load these in and strip the BOM.
		// Otherwise we load as ansi and convert to unicode
		wstring loadfile(HMODULE handle, int name)
		{
			auto rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(TEXTFILE));
			auto rcData = ::LoadResource(handle, rc);
			auto cb = ::SizeofResource(handle, rc);
			auto bytes = ::LockResource(rcData);
			auto data = static_cast<const BYTE*>(bytes);
			if (cb >= 2 && data[0] == 0xfe && data[1] == 0xff)
			{
				// Skip the byte order mark
				auto wstr = static_cast<const wchar_t*>(bytes);
				auto cch = cb / sizeof(wchar_t);
				return std::wstring(wstr + 1, cch - 1);
			}

			auto str = std::string(static_cast<const char*>(bytes), cb);
			return stringTowstring(str);
		}

		vector<SmartViewTestData> loadTestData(HMODULE handle, std::initializer_list<SmartViewTestResource> resources)
		{
			vector<SmartViewTestData> testData;
			for (auto resource : resources)
			{
				testData.push_back(SmartViewTestData
					{
						resource.structType, resource.parseAll,
						format(L"%d/%d", resource.hex, resource.expected),
						HexStringToBin(loadfile(handle, resource.hex)),
						loadfile(handle, resource.expected)
					});
			}

			return testData;
		}

	public:
		TEST_CLASS_INITIALIZE(Initialize_smartview)
		{
			// Set up our property arrays or nothing works
			MergeAddInArrays();

			RegKeys[regkeyDO_SMART_VIEW].ulCurDWORD = 1;
			RegKeys[regkeyUSE_GETPROPLIST].ulCurDWORD = 1;
			RegKeys[regkeyPARSED_NAMED_PROPS].ulCurDWORD = 1;
			RegKeys[regkeyCACHE_NAME_DPROPS].ulCurDWORD = 1;

			setTestInstance(::GetModuleHandleW(L"UnitTest.dll"));
		}

		TEST_METHOD(Test_STADDITIONALRENENTRYIDSEX)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI1IN, IDR_SV1AEI1OUT },
					SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI2IN, IDR_SV1AEI2OUT },
				}));
		}

		TEST_METHOD(Test_STAPPOINTMENTRECURRENCEPATTERN)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP1IN, IDR_SV2ARP1OUT },
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP2IN, IDR_SV2ARP2OUT },
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP3IN, IDR_SV2ARP3OUT },
					SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP4IN, IDR_SV2ARP4OUT },
				}));
		}

		TEST_METHOD(Test_STCONVERSATIONINDEX)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI1IN, IDR_SV3CI1OUT },
					SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI2IN, IDR_SV3CI2OUT },
					SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI3IN, IDR_SV3CI3OUT },
				}));
		}

		TEST_METHOD(Test_STENTRYID)
		{
			test(loadTestData(::GetModuleHandleW(L"UnitTest.dll"),
				{
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID1IN, IDR_SV4EID1OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID2IN, IDR_SV4EID2OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID3IN, IDR_SV4EID3OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID4IN, IDR_SV4EID4OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID5IN, IDR_SV4EID5OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID6IN, IDR_SV4EID6OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID7IN, IDR_SV4EID7OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID8IN, IDR_SV4EID8OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID9IN, IDR_SV4EID9OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID10IN, IDR_SV4EID10OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID11IN, IDR_SV4EID11OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID12IN, IDR_SV4EID12OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID13IN, IDR_SV4EID13OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID14IN, IDR_SV4EID14OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID15IN, IDR_SV4EID15OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID16IN, IDR_SV4EID16OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID17IN, IDR_SV4EID17OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID18IN, IDR_SV4EID18OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID19IN, IDR_SV4EID19OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID20IN, IDR_SV4EID20OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID21IN, IDR_SV4EID21OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID22IN, IDR_SV4EID22OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID23IN, IDR_SV4EID23OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID24IN, IDR_SV4EID24OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID25IN, IDR_SV4EID25OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID26IN, IDR_SV4EID26OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID27IN, IDR_SV4EID27OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID28IN, IDR_SV4EID28OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID29IN, IDR_SV4EID29OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID30IN, IDR_SV4EID30OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID31IN, IDR_SV4EID31OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID32IN, IDR_SV4EID32OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID33IN, IDR_SV4EID33OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID34IN, IDR_SV4EID34OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID35IN, IDR_SV4EID35OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID36IN, IDR_SV4EID36OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID37IN, IDR_SV4EID37OUT },
					SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID38IN, IDR_SV4EID38OUT }
				}));
		}
	};
}<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  WebSocketConn.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  06/23/16 09:59:19
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (),
 *   Organization:
 *
 * =====================================================================================
 */
#include <WebSocketConn.h>

void WebSocketConn::OnRead()
{
    for (;;)
    {
        uint32_t free_buf_len = m_in_buf.GetAllocSize() - m_in_buf.GetWriteOffset();
        if (free_buf_len < READ_BUF_SIZE)
            m_in_buf.Extend(READ_BUF_SIZE);
        int ret = netlib_recv(m_handle, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);
        if (ret <= 0)
            break;
        m_recv_bytes += ret;
        m_in_buf.IncWriteOffset(ret);
        m_last_recv_tick = get_tick_count();
    }
/*
    if(m_websocket == NULL)
    {
        m_websocket = new WebSocket;
    }
*/

    WebSocket websocket;
    if(m_websocket_inited)
    {
        CImPdu *pPdu = NULL;

        int data_size = m_in_buf.GetWriteOffset();
        unsigned char *dataBuffer = (unsigned char*)malloc(data_size);
        try{
            int data_length = 0;
            int use_length = 0;
            int read_count = 0;
            WebSocketFrameType frameType = websocket.getFrame(m_in_buf.GetBuffer() ,m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);
            //log("len:%d use:%d",m_in_buf.GetWriteOffset(),use_length);
            while(frameType == BINARY_FRAME || frameType == TEXT_FRAME)
            {
                read_count = read_count + use_length;
                while((pPdu = CImPdu::ReadPdu((uchar_t*)dataBuffer,data_length)))
                {
                    uint32_t pdu_len = pPdu->GetLength();
                    HandlePdu(pPdu);
                    delete pPdu;
                    pPdu = NULL;
                    break;
                }
                m_in_buf.Read(NULL, use_length);
                if(read_count >= data_size) {
                    break;
                }
                data_length = 0;
                use_length = 0;
                frameType = websocket.getFrame(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);
            }

            //m_in_buf.~CSimpleBuffer();
        }catch(CPduException& ex)
        {

        }
        free(dataBuffer);

    }else
    {
        WebSocketFrameType type = websocket.parseHandshake(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset());
        if(type == OPENING_FRAME) {
            string answer = websocket.answerHandshake();
            CMsgConn::Send((void *)answer.c_str(), answer.size());
            m_in_buf.Read(NULL, m_in_buf.GetWriteOffset());
          //  m_in_buf.~CSimpleBuffer();
            m_websocket_inited = true;
        }else {
            //OnClose();
        }
    }
}

int WebSocketConn::Send(void *data, int len)
{
    WebSocket websocket;
    unsigned char* outData = (unsigned char*)malloc(len + 14);
    int out_len = websocket.makeFrame(BINARY_FRAME, (unsigned char*)data,len,outData ,len + 14);
    int result =  CMsgConn::Send(outData ,out_len);
    free(outData);
    return result;
}
<commit_msg>update code<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  WebSocketConn.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  06/23/16 09:59:19
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (),
 *   Organization:
 *
 * =====================================================================================
 */
#include <WebSocketConn.h>

void WebSocketConn::OnRead()
{
    for (;;)
    {
        uint32_t free_buf_len = m_in_buf.GetAllocSize() - m_in_buf.GetWriteOffset();
        if (free_buf_len < READ_BUF_SIZE)
            m_in_buf.Extend(READ_BUF_SIZE);
        int ret = 0;
        if(m_socket) {
            ret = netlib_socket_recv(m_socket, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);
        }else {
            ret = netlib_recv(m_handle, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);
        }
        if (ret <= 0)
            break;
        m_recv_bytes += ret;
        m_in_buf.IncWriteOffset(ret);
        m_last_recv_tick = get_tick_count();
    }
/*
    if(m_websocket == NULL)
    {
        m_websocket = new WebSocket;
    }
*/

    WebSocket websocket;
    if(m_websocket_inited)
    {
        CImPdu *pPdu = NULL;

        int data_size = m_in_buf.GetWriteOffset();
        unsigned char *dataBuffer = (unsigned char*)malloc(data_size);
        try{
            int data_length = 0;
            int use_length = 0;
            int read_count = 0;
            WebSocketFrameType frameType = websocket.getFrame(m_in_buf.GetBuffer() ,m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);
            //log("len:%d use:%d",m_in_buf.GetWriteOffset(),use_length);
            while(frameType == BINARY_FRAME || frameType == TEXT_FRAME)
            {
                read_count = read_count + use_length;
                while((pPdu = CImPdu::ReadPdu((uchar_t*)dataBuffer,data_length)))
                {
                    uint32_t pdu_len = pPdu->GetLength();
                    HandlePdu(pPdu);
                    delete pPdu;
                    pPdu = NULL;
                    break;
                }
                m_in_buf.Read(NULL, use_length);
                if(read_count >= data_size) {
                    break;
                }
                data_length = 0;
                use_length = 0;
                frameType = websocket.getFrame(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);
            }

            //m_in_buf.~CSimpleBuffer();
        }catch(CPduException& ex)
        {

        }
        free(dataBuffer);

    }else
    {
        WebSocketFrameType type = websocket.parseHandshake(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset());
        if(type == OPENING_FRAME) {
            string answer = websocket.answerHandshake();
            CMsgConn::Send((void *)answer.c_str(), answer.size());
            m_in_buf.Read(NULL, m_in_buf.GetWriteOffset());
          //  m_in_buf.~CSimpleBuffer();
            m_websocket_inited = true;
        }else {
            //OnClose();
        }
    }
}

int WebSocketConn::Send(void *data, int len)
{
    WebSocket websocket;
    unsigned char* outData = (unsigned char*)malloc(len + 14);
    int out_len = websocket.makeFrame(BINARY_FRAME, (unsigned char*)data,len,outData ,len + 14);
    int result =  CMsgConn::Send(outData ,out_len);
    free(outData);
    return result;
}
<|endoftext|>


<commit_before><commit_msg>getClosestBall fix<commit_after><|endoftext|>


<commit_before>#include "src/graphics.h"
#include "src/math.h"

#include <sys/timeb.h>

// Bresenham line drawing test
void testBresenham(int ox, int oy, int r)
{
    float l;
    unsigned int elapsed, numLines = 0;
    struct timeb startTime, endTime;
    printf("Bresenham drawing:");

    ftime(&startTime);
    for(l = 0.0f; l < 2.0f*M_PI; l += 0.001f, numLines++)
    {
        int color = (int)((l * 10.f) + 1) % 256;
        drawLine(ox, oy, ox + r * cos(l), oy + r * sin(l), color);
    }
    ftime(&endTime);

    elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;
    printf(" %u lines in %ums", numLines, elapsed);
}
<commit_msg>Minor test update<commit_after>#include "src/graphics.h"
#include "src/math.h"

#include <sys/timeb.h>

// Bresenham line drawing test
void testBresenham(int ox, int oy, int r)
{
    float l;
    unsigned int elapsed, numLines = 0;
    struct timeb startTime, endTime;

    printf("Bresenham drawing: please wait...\r");

    ftime(&startTime);
    for(l = 0.0f; l < 2.0f*M_PI; l += 0.001f, numLines++)
    {
        int color = (int)((l * 10.f) + 1) % 256;
        drawLine(ox, oy, ox + r * cos(l), oy + r * sin(l), color);
    }
    ftime(&endTime);

    elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;
    printf("Bresenham drawing: %ums (%u lines)", elapsed, numLines);
}
<|endoftext|>