<commit_before>#include <Common.hpp>
#include <Classes.hpp>
#include <opencv2/ximgproc.hpp>

extern "C"
struct TensorWrapper niBlackThreshold(struct TensorWrapper src, struct TensorWrapper dst, double maxValue, int type, int blockSize, double delta);

// GraphSegmentation
struct GraphSegmentationPtr {
    void *ptr;

    inline cv::ximgproc::segmentation::GraphSegmentation * operator->() { return static_cast<cv::ximgproc::segmentation::GraphSegmentation *>(ptr); }
    inline cv::ximgproc::segmentation::GraphSegmentation * operator*() { return static_cast<cv::ximgproc::segmentation::GraphSegmentation *>(ptr); }
    inline GraphSegmentationPtr(cv::ximgproc::segmentation::GraphSegmentation *ptr) { this->ptr = ptr; }
};

// GraphSegmentation
extern "C"
struct GraphSegmentationPtr GraphSegmentation_ctor(double sigma, float k, int min_size);

extern "C"
struct TensorWrapper GraphSegmentation_processImage(struct GraphSegmentationPtr ptr, struct TensorWrapper);

extern "C"
void GraphSegmentation_setSigma(struct GraphSegmentationPtr ptr, double s);

extern "C"
double GraphSegmentation_getSigma(struct GraphSegmentationPtr ptr);

extern "C"
void GraphSegmentation_setK(struct GraphSegmentationPtr ptr, float k);

extern "C"
float GraphSegmentation_getK(struct GraphSegmentationPtr ptr);

extern "C"
void GraphSegmentation_setMinSize(struct GraphSegmentationPtr ptr, int min_size);

extern "C"
int GraphSegmentation_getMinSize(struct GraphSegmentationPtr ptr);

// SelectiveSearchSegmentationStrategy
struct SelectiveSearchSegmentationStrategyPtr {
    void *ptr;

    inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator->() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *>(ptr); }
    inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator*() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *>(ptr); }
    inline SelectiveSearchSegmentationStrategyPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *ptr) { this->ptr = ptr; }
};
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyColor_ctor();
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategySize_ctor();
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyTexture_ctor();
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyFill_ctor();
//
// extern "C"
// void SelectiveSearchSegmentationStrategy_setImage(struct SelectiveSearchSegmentationStrategyPtr ptr, struct TensorWrapper, struct TensorWrapper, struct TensorWrapper, int);
//
// extern "C"
// float SelectiveSearchSegmentationStrategy_get(int, int);
//
// extern "C"
// void SelectiveSearchSegmentationStrategy_merge(int, int);

// MULTIPLE STRTEGY
//

// See #103
#ifndef APPLE

// SelectiveSearchSegmentation
struct SelectiveSearchSegmentationPtr {
    void *ptr;

    inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator->() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentation *>(ptr); }
    inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator*() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentation *>(ptr); }
    inline SelectiveSearchSegmentationPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentation *ptr) { this->ptr = ptr; }
};

extern "C"
struct SelectiveSearchSegmentationPtr SelectiveSearchSegmentation_ctor();

extern "C"
void SelectiveSearchSegmentation_setBaseImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);

extern "C"
void SelectiveSearchSegmentation_switchToSingleStrategy(struct SelectiveSearchSegmentationPtr ptr, int, float);

extern "C"
void SelectiveSearchSegmentation_switchToSelectiveSearchFast(struct SelectiveSearchSegmentationPtr ptr, int, int, float);

extern "C"
void SelectiveSearchSegmentation_switchToSelectiveSearchQuality(struct SelectiveSearchSegmentationPtr ptr, int, int, float);

extern "C"
void SelectiveSearchSegmentation_addImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);

extern "C"
void SelectiveSearchSegmentation_clearImages(struct SelectiveSearchSegmentationPtr ptr);

extern "C"
void SelectiveSearchSegmentation_addGraphSegmentation(struct SelectiveSearchSegmentationPtr ptr, struct GraphSegmentationPtr);

extern "C"
void SelectiveSearchSegmentation_clearGraphSegmentations(struct SelectiveSearchSegmentationPtr ptr);

extern "C"
void SelectiveSearchSegmentation_addStrategy(struct SelectiveSearchSegmentationPtr ptr, struct SelectiveSearchSegmentationStrategyPtr);

extern "C"
void SelectiveSearchSegmentation_clearStrategies(struct SelectiveSearchSegmentationPtr ptr);

extern "C"
struct RectArray SelectiveSearchSegmentation_process(struct SelectiveSearchSegmentationPtr ptr);

#endif
<commit_msg>Very last fix to #103<commit_after>#include <Common.hpp>
#include <Classes.hpp>
#include <opencv2/ximgproc.hpp>

extern "C"
struct TensorWrapper niBlackThreshold(struct TensorWrapper src, struct TensorWrapper dst, double maxValue, int type, int blockSize, double delta);

// GraphSegmentation
struct GraphSegmentationPtr {
    void *ptr;

    inline cv::ximgproc::segmentation::GraphSegmentation * operator->() { return static_cast<cv::ximgproc::segmentation::GraphSegmentation *>(ptr); }
    inline cv::ximgproc::segmentation::GraphSegmentation * operator*() { return static_cast<cv::ximgproc::segmentation::GraphSegmentation *>(ptr); }
    inline GraphSegmentationPtr(cv::ximgproc::segmentation::GraphSegmentation *ptr) { this->ptr = ptr; }
};

// GraphSegmentation
extern "C"
struct GraphSegmentationPtr GraphSegmentation_ctor(double sigma, float k, int min_size);

extern "C"
struct TensorWrapper GraphSegmentation_processImage(struct GraphSegmentationPtr ptr, struct TensorWrapper);

extern "C"
void GraphSegmentation_setSigma(struct GraphSegmentationPtr ptr, double s);

extern "C"
double GraphSegmentation_getSigma(struct GraphSegmentationPtr ptr);

extern "C"
void GraphSegmentation_setK(struct GraphSegmentationPtr ptr, float k);

extern "C"
float GraphSegmentation_getK(struct GraphSegmentationPtr ptr);

extern "C"
void GraphSegmentation_setMinSize(struct GraphSegmentationPtr ptr, int min_size);

extern "C"
int GraphSegmentation_getMinSize(struct GraphSegmentationPtr ptr);

// See #103
#ifndef APPLE

// SelectiveSearchSegmentationStrategy
struct SelectiveSearchSegmentationStrategyPtr {
    void *ptr;

    inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator->() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *>(ptr); }
    inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator*() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *>(ptr); }
    inline SelectiveSearchSegmentationStrategyPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *ptr) { this->ptr = ptr; }
};
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyColor_ctor();
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategySize_ctor();
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyTexture_ctor();
//
// extern "C"
// struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyFill_ctor();
//
// extern "C"
// void SelectiveSearchSegmentationStrategy_setImage(struct SelectiveSearchSegmentationStrategyPtr ptr, struct TensorWrapper, struct TensorWrapper, struct TensorWrapper, int);
//
// extern "C"
// float SelectiveSearchSegmentationStrategy_get(int, int);
//
// extern "C"
// void SelectiveSearchSegmentationStrategy_merge(int, int);

// MULTIPLE STRTEGY
//

// SelectiveSearchSegmentation
struct SelectiveSearchSegmentationPtr {
    void *ptr;

    inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator->() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentation *>(ptr); }
    inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator*() { return static_cast<cv::ximgproc::segmentation::SelectiveSearchSegmentation *>(ptr); }
    inline SelectiveSearchSegmentationPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentation *ptr) { this->ptr = ptr; }
};

extern "C"
struct SelectiveSearchSegmentationPtr SelectiveSearchSegmentation_ctor();

extern "C"
void SelectiveSearchSegmentation_setBaseImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);

extern "C"
void SelectiveSearchSegmentation_switchToSingleStrategy(struct SelectiveSearchSegmentationPtr ptr, int, float);

extern "C"
void SelectiveSearchSegmentation_switchToSelectiveSearchFast(struct SelectiveSearchSegmentationPtr ptr, int, int, float);

extern "C"
void SelectiveSearchSegmentation_switchToSelectiveSearchQuality(struct SelectiveSearchSegmentationPtr ptr, int, int, float);

extern "C"
void SelectiveSearchSegmentation_addImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);

extern "C"
void SelectiveSearchSegmentation_clearImages(struct SelectiveSearchSegmentationPtr ptr);

extern "C"
void SelectiveSearchSegmentation_addGraphSegmentation(struct SelectiveSearchSegmentationPtr ptr, struct GraphSegmentationPtr);

extern "C"
void SelectiveSearchSegmentation_clearGraphSegmentations(struct SelectiveSearchSegmentationPtr ptr);

extern "C"
void SelectiveSearchSegmentation_addStrategy(struct SelectiveSearchSegmentationPtr ptr, struct SelectiveSearchSegmentationStrategyPtr);

extern "C"
void SelectiveSearchSegmentation_clearStrategies(struct SelectiveSearchSegmentationPtr ptr);

extern "C"
struct RectArray SelectiveSearchSegmentation_process(struct SelectiveSearchSegmentationPtr ptr);

#endif
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 51 Franklin Street,      *
 *   Fifth Floor, Boston, MA  02110-1301, USA                              *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QLineEdit>
# include <QFocusEvent>
#endif

#include "QuantitySpinBox.h"
#include <Base/Exception.h>

using namespace Gui;

namespace Gui {
class QuantitySpinBoxPrivate
{
public:
    QuantitySpinBoxPrivate() :
      validInput(true),
      unitValue(0),
      maximum(DOUBLE_MAX),
      minimum(-DOUBLE_MAX),
      singleStep(1.0)
    {
    }
    ~QuantitySpinBoxPrivate()
    {
    }

    QString stripped(const QString &t, int *pos) const
    {
        QString text = t;
        const int s = text.size();
        text = text.trimmed();
        if (pos)
            (*pos) -= (s - text.size());
        return text;
    }

    Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
    {
        Base::Quantity res;
        const double max = this->maximum;
        const double min = this->minimum;

        QString copy = input;

        int len = copy.size();
        const bool plus = max >= 0;
        const bool minus = min <= 0;

        switch (len) {
        case 0:
            state = max != min ? QValidator::Intermediate : QValidator::Invalid;
            goto end;
        case 1:
            if (copy.at(0) == locale.decimalPoint()) {
                state = QValidator::Intermediate;
                copy.prepend(QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('+')) {
                // the quantity parser doesn't allow numbers of the form '+1.0'
                state = QValidator::Invalid;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('-')) {
                if (minus)
                    state = QValidator::Intermediate;
                else
                    state = QValidator::Invalid;
                goto end;
            }
            break;
        case 2:
            if (copy.at(1) == locale.decimalPoint()
                && (plus && copy.at(0) == QLatin1Char('+'))) {
                state = QValidator::Intermediate;
                goto end;
            }
            if (copy.at(1) == locale.decimalPoint()
                && (minus && copy.at(0) == QLatin1Char('-'))) {
                state = QValidator::Intermediate;
                copy.insert(1, QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            break;
        default: break;
        }

        if (copy.at(0) == locale.groupSeparator()) {
            state = QValidator::Invalid;
            goto end;
        }
        else if (len > 1) {
            const int dec = copy.indexOf(locale.decimalPoint());
            if (dec != -1) {
                if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) {
                    copy.remove(dec + 1, 1);
                }
                else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) {
                    // trying to add a second decimal point is not allowed
                    state = QValidator::Invalid;
                    goto end;
                }
            }
            for (int i=dec + 1; i<copy.size(); ++i) {
                // a group separator after the decimal point is not allowed
                if (copy.at(i) == locale.groupSeparator()) {
                    state = QValidator::Invalid;
                    goto end;
                }
            }
        }

        bool ok = false;
        double value = min;

        if (locale.negativeSign() != QLatin1Char('-'))
            copy.replace(locale.negativeSign(), QLatin1Char('-'));
        if (locale.positiveSign() != QLatin1Char('+'))
            copy.replace(locale.positiveSign(), QLatin1Char('+'));

        try {
            QString copy2 = copy;
            copy2.remove(locale.groupSeparator());

            res = Base::Quantity::parse(copy2);
            value = res.getValue();
            ok = true;
        }
        catch (Base::Exception&) {
        }

        if (!ok) {
            // input may not be finished
            state = QValidator::Intermediate;
        }
        else if (value >= min && value <= max) {
            if (copy.endsWith(locale.decimalPoint())) {
                // input shouldn't end with a decimal point
                state = QValidator::Intermediate;
            }
            else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {
                // if not dimensionless the input should have a dimension
                state = QValidator::Intermediate;
            }
            else if (res.getUnit() != this->unit) {
                state = QValidator::Invalid;
            }
            else {
                state = QValidator::Acceptable;
            }
        }
        else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
            state = QValidator::Invalid;
        }
        else {
            if ((value >= 0 && value > max) || (value < 0 && value < min)) {
                state = QValidator::Invalid;
            }
            else {
                state = QValidator::Intermediate;
            }
        }
end:
        if (state != QValidator::Acceptable) {
            res.setValue(max > 0 ? min : max);
        }

        input = copy;
        return res;
    }

    QLocale locale;
    bool validInput;
    QString validStr;
    Base::Quantity quantity;
    Base::Unit unit;
    double unitValue;
    QString unitStr;
    double maximum;
    double minimum;
    double singleStep;
};
}

QuantitySpinBox::QuantitySpinBox(QWidget *parent)
    : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate())
{
    d_ptr->locale = locale();
    this->setContextMenuPolicy(Qt::DefaultContextMenu);
    QObject::connect(lineEdit(), SIGNAL(textChanged(QString)),
                     this, SLOT(userInput(QString)));
}

QuantitySpinBox::~QuantitySpinBox()
{
}

void QuantitySpinBox::updateText(const Base::Quantity& quant)
{
    Q_D(QuantitySpinBox);

    double dFactor;
    QString txt = quant.getUserString(dFactor,d->unitStr);
    d->unitValue = quant.getValue()/dFactor;
    lineEdit()->setText(txt);
}

Base::Quantity QuantitySpinBox::value() const
{
    Q_D(const QuantitySpinBox);
    return d->quantity;
}

void QuantitySpinBox::setValue(const Base::Quantity& value)
{
    Q_D(QuantitySpinBox);
    d->quantity = value;
    // check limits
    if (d->quantity.getValue() > d->maximum)
        d->quantity.setValue(d->maximum);
    if (d->quantity.getValue() < d->minimum)
        d->quantity.setValue(d->minimum);

    d->unit = value.getUnit();

    updateText(value);
}

void QuantitySpinBox::setValue(double value)
{
    Q_D(QuantitySpinBox);
    setValue(Base::Quantity(value, d->unit));
}

bool QuantitySpinBox::hasValidInput() const
{
    Q_D(const QuantitySpinBox);
    return d->validInput;
}

// Gets called after call of 'validateAndInterpret'
void QuantitySpinBox::userInput(const QString & text)
{
    Q_D(QuantitySpinBox);

    QString tmp = text;
    int pos;
    QValidator::State state;
    Base::Quantity res = d->validateAndInterpret(tmp, pos, state);
    if (state == QValidator::Acceptable) {
        d->validInput = true;
        d->validStr = text;
    }
    else if (state == QValidator::Intermediate) {
        tmp = tmp.trimmed();
        tmp += QLatin1Char(' ');
        tmp += d->unitStr;
        Base::Quantity res2 = d->validateAndInterpret(tmp, pos, state);
        if (state == QValidator::Acceptable) {
            d->validInput = true;
            d->validStr = tmp;
            res = res2;
        }
        else {
            d->validInput = false;
            return;
        }
    }
    else {
        d->validInput = false;
        return;
    }

    double factor;
    res.getUserString(factor,d->unitStr);
    d->unitValue = res.getValue()/factor;
    d->quantity = res;

    // signaling
    valueChanged(res);
    valueChanged(res.getValue());
}

Base::Unit QuantitySpinBox::unit() const
{
    Q_D(const QuantitySpinBox);
    return d->unit;
}

void QuantitySpinBox::setUnit(const Base::Unit &unit)
{
    Q_D(QuantitySpinBox);

    d->unit = unit;
    d->quantity.setUnit(unit);
    updateText(d->quantity);
}

void QuantitySpinBox::setUnitText(const QString& str)
{
    Base::Quantity quant = Base::Quantity::parse(str);
    setUnit(quant.getUnit());
}

QString QuantitySpinBox::unitText(void)
{
    Q_D(QuantitySpinBox);
    return d->unitStr;
}

double QuantitySpinBox::singleStep() const
{
    Q_D(const QuantitySpinBox);
    return d->singleStep;
}

void QuantitySpinBox::setSingleStep(double value)
{
    Q_D(QuantitySpinBox);

    if (value >= 0) {
        d->singleStep = value;
    }
}

double QuantitySpinBox::minimum() const
{
    Q_D(const QuantitySpinBox);
    return d->minimum;
}

void QuantitySpinBox::setMinimum(double minimum)
{
    Q_D(QuantitySpinBox);
    d->minimum = minimum;
}

double QuantitySpinBox::maximum() const
{
    Q_D(const QuantitySpinBox);
    return d->maximum;
}

void QuantitySpinBox::setMaximum(double maximum)
{
    Q_D(QuantitySpinBox);
    d->maximum = maximum;
}

void QuantitySpinBox::setRange(double minimum, double maximum)
{
    Q_D(QuantitySpinBox);
    d->minimum = minimum;
    d->maximum = maximum;
}

QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const
{
    Q_D(const QuantitySpinBox);
    if (isReadOnly()/* || !d->validInput*/)
        return StepNone;
    if (wrapping())
        return StepEnabled(StepUpEnabled | StepDownEnabled);
    StepEnabled ret = StepNone;
    if (d->quantity.getValue() < d->maximum) {
        ret |= StepUpEnabled;
    }
    if (d->quantity.getValue() > d->minimum) {
        ret |= StepDownEnabled;
    }
    return ret;
}

void QuantitySpinBox::stepBy(int steps)
{
    Q_D(QuantitySpinBox);

    double step = d->singleStep * steps;
    double val = d->unitValue + step;
    if (val > d->maximum)
        val = d->maximum;
    else if (val < d->minimum)
        val = d->minimum;

    lineEdit()->setText(QString::fromUtf8("%L1 %2").arg(val).arg(d->unitStr));
    update();
    selectNumber();
}

void QuantitySpinBox::showEvent(QShowEvent * event)
{
    Q_D(QuantitySpinBox);

    QAbstractSpinBox::showEvent(event);

    bool selected = lineEdit()->hasSelectedText();
    updateText(d->quantity);
    if (selected)
        selectNumber();
}

void QuantitySpinBox::focusInEvent(QFocusEvent * event)
{
    bool hasSel = lineEdit()->hasSelectedText();
    QAbstractSpinBox::focusInEvent(event);

    if (event->reason() == Qt::TabFocusReason ||
        event->reason() == Qt::BacktabFocusReason  ||
        event->reason() == Qt::ShortcutFocusReason) {
        if (!hasSel)
            selectNumber();
    }
}

void QuantitySpinBox::focusOutEvent(QFocusEvent * event)
{
    Q_D(QuantitySpinBox);

    int pos;
    QString text = lineEdit()->text();
    QValidator::State state;
    d->validateAndInterpret(text, pos, state);
    if (state != QValidator::Acceptable) {
        lineEdit()->setText(d->validStr);
    }
    QAbstractSpinBox::focusOutEvent(event);
}

void QuantitySpinBox::clear()
{
    QAbstractSpinBox::clear();
}

void QuantitySpinBox::selectNumber()
{
    QString str = lineEdit()->text();
    unsigned int i = 0;

    QChar d = locale().decimalPoint();
    QChar g = locale().groupSeparator();
    QChar n = locale().negativeSign();

    for (QString::iterator it = str.begin(); it != str.end(); ++it) {
        if (it->isDigit())
            i++;
        else if (*it == d)
            i++;
        else if (*it == g)
            i++;
        else if (*it == n)
            i++;
        else // any non-number character
            break;
    }

    lineEdit()->setSelection(0, i);
}

QString QuantitySpinBox::textFromValue(const Base::Quantity& value) const
{
    double factor;
    QString unitStr;
    QString str = value.getUserString(factor, unitStr);
    if (qAbs(value.getValue()) >= 1000.0) {
        str.remove(locale().groupSeparator());
    }
    return str;
}

Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const
{
    Q_D(const QuantitySpinBox);

    QString copy = text;
    int pos = lineEdit()->cursorPosition();
    QValidator::State state = QValidator::Acceptable;
    Base::Quantity quant = d->validateAndInterpret(copy, pos, state);
    if (state != QValidator::Acceptable) {
        fixup(copy);
        quant = d->validateAndInterpret(copy, pos, state);
    }

    return quant;
}

QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const
{
    Q_D(const QuantitySpinBox);

    QValidator::State state;
    d->validateAndInterpret(text, pos, state);
    return state;
}

void QuantitySpinBox::fixup(QString &input) const
{
    input.remove(locale().groupSeparator());
}

#include "moc_QuantitySpinBox.cpp"
<commit_msg>+ fix gcc build failure<commit_after>/***************************************************************************
 *   Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 51 Franklin Street,      *
 *   Fifth Floor, Boston, MA  02110-1301, USA                              *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QLineEdit>
# include <QFocusEvent>
#endif

#include "QuantitySpinBox.h"
#include <Base/Exception.h>

using namespace Gui;

namespace Gui {
class QuantitySpinBoxPrivate
{
public:
    QuantitySpinBoxPrivate() :
      validInput(true),
      unitValue(0),
      maximum(DOUBLE_MAX),
      minimum(-DOUBLE_MAX),
      singleStep(1.0)
    {
    }
    ~QuantitySpinBoxPrivate()
    {
    }

    QString stripped(const QString &t, int *pos) const
    {
        QString text = t;
        const int s = text.size();
        text = text.trimmed();
        if (pos)
            (*pos) -= (s - text.size());
        return text;
    }

    Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
    {
        Base::Quantity res;
        const double max = this->maximum;
        const double min = this->minimum;

        QString copy = input;

        int len = copy.size();
        const bool plus = max >= 0;
        const bool minus = min <= 0;

        switch (len) {
        case 0:
            state = max != min ? QValidator::Intermediate : QValidator::Invalid;
            goto end;
        case 1:
            if (copy.at(0) == locale.decimalPoint()) {
                state = QValidator::Intermediate;
                copy.prepend(QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('+')) {
                // the quantity parser doesn't allow numbers of the form '+1.0'
                state = QValidator::Invalid;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('-')) {
                if (minus)
                    state = QValidator::Intermediate;
                else
                    state = QValidator::Invalid;
                goto end;
            }
            break;
        case 2:
            if (copy.at(1) == locale.decimalPoint()
                && (plus && copy.at(0) == QLatin1Char('+'))) {
                state = QValidator::Intermediate;
                goto end;
            }
            if (copy.at(1) == locale.decimalPoint()
                && (minus && copy.at(0) == QLatin1Char('-'))) {
                state = QValidator::Intermediate;
                copy.insert(1, QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            break;
        default: break;
        }

        {
            if (copy.at(0) == locale.groupSeparator()) {
                state = QValidator::Invalid;
                goto end;
            }
            else if (len > 1) {
                const int dec = copy.indexOf(locale.decimalPoint());
                if (dec != -1) {
                    if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) {
                        copy.remove(dec + 1, 1);
                    }
                    else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) {
                        // trying to add a second decimal point is not allowed
                        state = QValidator::Invalid;
                        goto end;
                    }
                }
                for (int i=dec + 1; i<copy.size(); ++i) {
                    // a group separator after the decimal point is not allowed
                    if (copy.at(i) == locale.groupSeparator()) {
                        state = QValidator::Invalid;
                        goto end;
                    }
                }
            }

            bool ok = false;
            double value = min;

            if (locale.negativeSign() != QLatin1Char('-'))
                copy.replace(locale.negativeSign(), QLatin1Char('-'));
            if (locale.positiveSign() != QLatin1Char('+'))
                copy.replace(locale.positiveSign(), QLatin1Char('+'));

            try {
                QString copy2 = copy;
                copy2.remove(locale.groupSeparator());

                res = Base::Quantity::parse(copy2);
                value = res.getValue();
                ok = true;
            }
            catch (Base::Exception&) {
            }

            if (!ok) {
                // input may not be finished
                state = QValidator::Intermediate;
            }
            else if (value >= min && value <= max) {
                if (copy.endsWith(locale.decimalPoint())) {
                    // input shouldn't end with a decimal point
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {
                    // if not dimensionless the input should have a dimension
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit() != this->unit) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Acceptable;
                }
            }
            else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
                state = QValidator::Invalid;
            }
            else {
                if ((value >= 0 && value > max) || (value < 0 && value < min)) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Intermediate;
                }
            }
        }
end:
        if (state != QValidator::Acceptable) {
            res.setValue(max > 0 ? min : max);
        }

        input = copy;
        return res;
    }

    QLocale locale;
    bool validInput;
    QString validStr;
    Base::Quantity quantity;
    Base::Unit unit;
    double unitValue;
    QString unitStr;
    double maximum;
    double minimum;
    double singleStep;
};
}

QuantitySpinBox::QuantitySpinBox(QWidget *parent)
    : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate())
{
    d_ptr->locale = locale();
    this->setContextMenuPolicy(Qt::DefaultContextMenu);
    QObject::connect(lineEdit(), SIGNAL(textChanged(QString)),
                     this, SLOT(userInput(QString)));
}

QuantitySpinBox::~QuantitySpinBox()
{
}

void QuantitySpinBox::updateText(const Base::Quantity& quant)
{
    Q_D(QuantitySpinBox);

    double dFactor;
    QString txt = quant.getUserString(dFactor,d->unitStr);
    d->unitValue = quant.getValue()/dFactor;
    lineEdit()->setText(txt);
}

Base::Quantity QuantitySpinBox::value() const
{
    Q_D(const QuantitySpinBox);
    return d->quantity;
}

void QuantitySpinBox::setValue(const Base::Quantity& value)
{
    Q_D(QuantitySpinBox);
    d->quantity = value;
    // check limits
    if (d->quantity.getValue() > d->maximum)
        d->quantity.setValue(d->maximum);
    if (d->quantity.getValue() < d->minimum)
        d->quantity.setValue(d->minimum);

    d->unit = value.getUnit();

    updateText(value);
}

void QuantitySpinBox::setValue(double value)
{
    Q_D(QuantitySpinBox);
    setValue(Base::Quantity(value, d->unit));
}

bool QuantitySpinBox::hasValidInput() const
{
    Q_D(const QuantitySpinBox);
    return d->validInput;
}

// Gets called after call of 'validateAndInterpret'
void QuantitySpinBox::userInput(const QString & text)
{
    Q_D(QuantitySpinBox);

    QString tmp = text;
    int pos;
    QValidator::State state;
    Base::Quantity res = d->validateAndInterpret(tmp, pos, state);
    if (state == QValidator::Acceptable) {
        d->validInput = true;
        d->validStr = text;
    }
    else if (state == QValidator::Intermediate) {
        tmp = tmp.trimmed();
        tmp += QLatin1Char(' ');
        tmp += d->unitStr;
        Base::Quantity res2 = d->validateAndInterpret(tmp, pos, state);
        if (state == QValidator::Acceptable) {
            d->validInput = true;
            d->validStr = tmp;
            res = res2;
        }
        else {
            d->validInput = false;
            return;
        }
    }
    else {
        d->validInput = false;
        return;
    }

    double factor;
    res.getUserString(factor,d->unitStr);
    d->unitValue = res.getValue()/factor;
    d->quantity = res;

    // signaling
    valueChanged(res);
    valueChanged(res.getValue());
}

Base::Unit QuantitySpinBox::unit() const
{
    Q_D(const QuantitySpinBox);
    return d->unit;
}

void QuantitySpinBox::setUnit(const Base::Unit &unit)
{
    Q_D(QuantitySpinBox);

    d->unit = unit;
    d->quantity.setUnit(unit);
    updateText(d->quantity);
}

void QuantitySpinBox::setUnitText(const QString& str)
{
    Base::Quantity quant = Base::Quantity::parse(str);
    setUnit(quant.getUnit());
}

QString QuantitySpinBox::unitText(void)
{
    Q_D(QuantitySpinBox);
    return d->unitStr;
}

double QuantitySpinBox::singleStep() const
{
    Q_D(const QuantitySpinBox);
    return d->singleStep;
}

void QuantitySpinBox::setSingleStep(double value)
{
    Q_D(QuantitySpinBox);

    if (value >= 0) {
        d->singleStep = value;
    }
}

double QuantitySpinBox::minimum() const
{
    Q_D(const QuantitySpinBox);
    return d->minimum;
}

void QuantitySpinBox::setMinimum(double minimum)
{
    Q_D(QuantitySpinBox);
    d->minimum = minimum;
}

double QuantitySpinBox::maximum() const
{
    Q_D(const QuantitySpinBox);
    return d->maximum;
}

void QuantitySpinBox::setMaximum(double maximum)
{
    Q_D(QuantitySpinBox);
    d->maximum = maximum;
}

void QuantitySpinBox::setRange(double minimum, double maximum)
{
    Q_D(QuantitySpinBox);
    d->minimum = minimum;
    d->maximum = maximum;
}

QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const
{
    Q_D(const QuantitySpinBox);
    if (isReadOnly()/* || !d->validInput*/)
        return StepNone;
    if (wrapping())
        return StepEnabled(StepUpEnabled | StepDownEnabled);
    StepEnabled ret = StepNone;
    if (d->quantity.getValue() < d->maximum) {
        ret |= StepUpEnabled;
    }
    if (d->quantity.getValue() > d->minimum) {
        ret |= StepDownEnabled;
    }
    return ret;
}

void QuantitySpinBox::stepBy(int steps)
{
    Q_D(QuantitySpinBox);

    double step = d->singleStep * steps;
    double val = d->unitValue + step;
    if (val > d->maximum)
        val = d->maximum;
    else if (val < d->minimum)
        val = d->minimum;

    lineEdit()->setText(QString::fromUtf8("%L1 %2").arg(val).arg(d->unitStr));
    update();
    selectNumber();
}

void QuantitySpinBox::showEvent(QShowEvent * event)
{
    Q_D(QuantitySpinBox);

    QAbstractSpinBox::showEvent(event);

    bool selected = lineEdit()->hasSelectedText();
    updateText(d->quantity);
    if (selected)
        selectNumber();
}

void QuantitySpinBox::focusInEvent(QFocusEvent * event)
{
    bool hasSel = lineEdit()->hasSelectedText();
    QAbstractSpinBox::focusInEvent(event);

    if (event->reason() == Qt::TabFocusReason ||
        event->reason() == Qt::BacktabFocusReason  ||
        event->reason() == Qt::ShortcutFocusReason) {
        if (!hasSel)
            selectNumber();
    }
}

void QuantitySpinBox::focusOutEvent(QFocusEvent * event)
{
    Q_D(QuantitySpinBox);

    int pos;
    QString text = lineEdit()->text();
    QValidator::State state;
    d->validateAndInterpret(text, pos, state);
    if (state != QValidator::Acceptable) {
        lineEdit()->setText(d->validStr);
    }
    QAbstractSpinBox::focusOutEvent(event);
}

void QuantitySpinBox::clear()
{
    QAbstractSpinBox::clear();
}

void QuantitySpinBox::selectNumber()
{
    QString str = lineEdit()->text();
    unsigned int i = 0;

    QChar d = locale().decimalPoint();
    QChar g = locale().groupSeparator();
    QChar n = locale().negativeSign();

    for (QString::iterator it = str.begin(); it != str.end(); ++it) {
        if (it->isDigit())
            i++;
        else if (*it == d)
            i++;
        else if (*it == g)
            i++;
        else if (*it == n)
            i++;
        else // any non-number character
            break;
    }

    lineEdit()->setSelection(0, i);
}

QString QuantitySpinBox::textFromValue(const Base::Quantity& value) const
{
    double factor;
    QString unitStr;
    QString str = value.getUserString(factor, unitStr);
    if (qAbs(value.getValue()) >= 1000.0) {
        str.remove(locale().groupSeparator());
    }
    return str;
}

Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const
{
    Q_D(const QuantitySpinBox);

    QString copy = text;
    int pos = lineEdit()->cursorPosition();
    QValidator::State state = QValidator::Acceptable;
    Base::Quantity quant = d->validateAndInterpret(copy, pos, state);
    if (state != QValidator::Acceptable) {
        fixup(copy);
        quant = d->validateAndInterpret(copy, pos, state);
    }

    return quant;
}

QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const
{
    Q_D(const QuantitySpinBox);

    QValidator::State state;
    d->validateAndInterpret(text, pos, state);
    return state;
}

void QuantitySpinBox::fixup(QString &input) const
{
    input.remove(locale().groupSeparator());
}

#include "moc_QuantitySpinBox.cpp"
<|endoftext|>


<commit_before>void loadlibs ()
{
  gSystem->Load("libMC");

  // libraries required by EVGEN
  // (commented libraries are already loaded in prevoius sequence)

  gSystem->Load("libmicrocern");
  gSystem->Load("libEG");
  gSystem->Load("libSTEER");
  gSystem->Load("libEGPythia6");
  gSystem->Load("libdummypythia6");
  gSystem->Load("libdummyhijing");
  gSystem->Load("libTHijing");
  gSystem->Load("libdummyHBTP");
  gSystem->Load("libTHbtp");
  gSystem->Load("libdummymevsim");
  gSystem->Load("libTMEVSIM");
  gSystem->Load("libdummyepemgen");
  gSystem->Load("libTEPEMGEN");
  gSystem->Load("libEVGEN");

  gSystem->Load("libPhysics");

  gSystem->Load("libCONTAINERS");
  gSystem->Load("libFMD");
  gSystem->Load("libMUON");
  gSystem->Load("libPHOS");
  gSystem->Load("libPMD");
  gSystem->Load("libRICH");
  gSystem->Load("libSTRUCT");
  gSystem->Load("libTPC");
  gSystem->Load("libTRD");
  gSystem->Load("libTOF");
  gSystem->Load("libZDC");
  gSystem->Load("libITS");
  gSystem->Load("libCRT");
  gSystem->Load("libSTART");
  gSystem->Load("libEMCAL");
  gSystem->Load("libVZERO");
  gSystem->Load("libdummyherwig");
  gSystem->Load("libTHerwig");
}
<commit_msg>Load EVGEN before external generators.<commit_after>void loadlibs ()
{
  gSystem->Load("libMC");

  // libraries required by EVGEN
  // (commented libraries are already loaded in prevoius sequence)

  gSystem->Load("libmicrocern");
  gSystem->Load("libEG");
  gSystem->Load("libSTEER");
  gSystem->Load("libEVGEN");
  gSystem->Load("libEGPythia6");
  gSystem->Load("libdummypythia6");
  gSystem->Load("libdummyhijing");
  gSystem->Load("libTHijing");
  gSystem->Load("libdummyHBTP");
  gSystem->Load("libTHbtp");
  gSystem->Load("libdummymevsim");
  gSystem->Load("libTMEVSIM");
  gSystem->Load("libdummyepemgen");
  gSystem->Load("libTEPEMGEN");

  gSystem->Load("libPhysics");

  gSystem->Load("libCONTAINERS");
  gSystem->Load("libFMD");
  gSystem->Load("libMUON");
  gSystem->Load("libPHOS");
  gSystem->Load("libPMD");
  gSystem->Load("libRICH");
  gSystem->Load("libSTRUCT");
  gSystem->Load("libTPC");
  gSystem->Load("libTRD");
  gSystem->Load("libTOF");
  gSystem->Load("libZDC");
  gSystem->Load("libITS");
  gSystem->Load("libCRT");
  gSystem->Load("libSTART");
  gSystem->Load("libEMCAL");
  gSystem->Load("libVZERO");
  gSystem->Load("libdummyherwig");
  gSystem->Load("libTHerwig");
}
<|endoftext|>


<commit_before>/*
 * IndexListIndexColor.cpp
 *
 * Copyright (C) 2016 by MegaMol Team
 * Alle Rechte vorbehalten.
 */
#include "stdafx.h"
#include "IndexListIndexColor.h"
#include "mmstd_datatools/MultiParticleDataAdaptor.h"
#include "mmstd_datatools/MultiIndexListDataCall.h"
#include <algorithm>

using namespace megamol;
using namespace megamol::stdplugin::datatools;

IndexListIndexColor::IndexListIndexColor() : stdplugin::datatools::AbstractParticleManipulator("outData", "inData"),
        inIndexListDataSlot("inIndexListData", "Fetches the second ICol value stream"),
        inPartsHash(0), inIndexHash(0), outHash(0),
        frameID(0), colors(), minCol(0.0f), maxCol(1.0f) {

    inIndexListDataSlot.SetCompatibleCall<MultiIndexListDataCallDescription>();
    MakeSlotAvailable(&inIndexListDataSlot);

}

IndexListIndexColor::~IndexListIndexColor() {
    Release();
}

bool IndexListIndexColor::manipulateData(
        core::moldyn::MultiParticleDataCall& outData,
        core::moldyn::MultiParticleDataCall& inData) {

    MultiIndexListDataCall *inListsPtr = inIndexListDataSlot.CallAs<MultiIndexListDataCall>();
    if (inListsPtr == nullptr) return false;

    inListsPtr->SetFrameID(inData.FrameID());
    if (!(*inListsPtr)(MultiIndexListDataCall::GET_HASH)) return false;

    if ( (inPartsHash != inData.DataHash()) || (inData.DataHash() == 0)
            || (inIndexHash != inListsPtr->DataHash()) || (inListsPtr->DataHash() == 0)
            || (frameID != inData.FrameID()) ) {
        // Update data
        inPartsHash = inData.DataHash();
        inIndexHash = inListsPtr->DataHash();
        outHash++;
        frameID = inData.FrameID();

        stdplugin::datatools::MultiParticleDataAdaptor p(inData);
        size_t pCnt = p.get_count();
        colors.resize(pCnt);

        if (pCnt == 0) {
            minCol = maxCol = 0.0f;

        } else {
            // initialize as "unreferenced"
            std::fill(colors.begin(), colors.end(), -1.0f);
            size_t ptsSet = 0; // numbers of point-references set
            bool warnIndex = false; // should warn about illegal indices?

            maxCol = -1.0f; // if no particle color is ever set, this will be max

            // iterate through all references
            size_t listCnt = inListsPtr->Count();
            for (size_t listI = 0; listI < listCnt; ++listI) {
                MultiIndexListDataCall::index_list_t const& list = inListsPtr->Lists()[listI];
                size_t oldPtsSet = ptsSet;
                for (MultiIndexListDataCall::index_t const index : list) {
                    if (index >= pCnt) {
                        warnIndex = true;
                        continue;
                    }
                    if (colors[index] < -0.9f) {
                        ptsSet++;
                        colors[index] = static_cast<float>(listI);
                    }
                }
                // if at least one point was set, listI exists as color, thus is the current max value.
                if (oldPtsSet < ptsSet) maxCol = static_cast<float>(listI);
            }

            // set min, based if all points have been referenced
            assert(ptsSet <= pCnt);
            minCol = (ptsSet == pCnt) ? 0.0f : -1.0f;

        }

    }

    inListsPtr->Unlock();

    outData = inData;
    outData.SetDataHash(outHash);
    outData.SetFrameID(frameID);
    inData.SetUnlocker(nullptr, false);

    const float *data = colors.data();
    for (unsigned int list = 0; list < outData.GetParticleListCount(); ++list) {
        auto &plist = outData.AccessParticles(list);
        plist.SetColourData(core::moldyn::SimpleSphericalParticles::COLDATA_FLOAT_I, data, 0);
        plist.SetColourMapIndexValues(minCol, maxCol);
        data += plist.GetCount();
    }

    return true;
}
<commit_msg>Bug in IndexListIndexColor fixed, now fetches the actual data correctly.<commit_after>/*
 * IndexListIndexColor.cpp
 *
 * Copyright (C) 2016 by MegaMol Team
 * Alle Rechte vorbehalten.
 */
#include "stdafx.h"
#include "IndexListIndexColor.h"
#include "mmstd_datatools/MultiParticleDataAdaptor.h"
#include "mmstd_datatools/MultiIndexListDataCall.h"
#include <algorithm>

using namespace megamol;
using namespace megamol::stdplugin::datatools;

IndexListIndexColor::IndexListIndexColor() : stdplugin::datatools::AbstractParticleManipulator("outData", "inData"),
        inIndexListDataSlot("inIndexListData", "Fetches the second ICol value stream"),
        inPartsHash(0), inIndexHash(0), outHash(0),
        frameID(0), colors(), minCol(0.0f), maxCol(1.0f) {

    inIndexListDataSlot.SetCompatibleCall<MultiIndexListDataCallDescription>();
    MakeSlotAvailable(&inIndexListDataSlot);

}

IndexListIndexColor::~IndexListIndexColor() {
    Release();
}

bool IndexListIndexColor::manipulateData(
        core::moldyn::MultiParticleDataCall& outData,
        core::moldyn::MultiParticleDataCall& inData) {

    MultiIndexListDataCall *inListsPtr = inIndexListDataSlot.CallAs<MultiIndexListDataCall>();
    if (inListsPtr == nullptr) return false;

    inListsPtr->SetFrameID(inData.FrameID());
    if (!(*inListsPtr)(MultiIndexListDataCall::GET_HASH)) return false;

    if ( (inPartsHash != inData.DataHash()) || (inData.DataHash() == 0)
            || (inIndexHash != inListsPtr->DataHash()) || (inListsPtr->DataHash() == 0)
            || (frameID != inData.FrameID()) ) {
        // Update data
        inPartsHash = inData.DataHash();
        inIndexHash = inListsPtr->DataHash();
        outHash++;
        frameID = inData.FrameID();

        inListsPtr->Unlock();
        inListsPtr->SetFrameID(inData.FrameID());
        if (!(*inListsPtr)(MultiIndexListDataCall::GET_DATA)) return false;

        stdplugin::datatools::MultiParticleDataAdaptor p(inData);
        size_t pCnt = p.get_count();
        colors.resize(pCnt);

        if (pCnt == 0) {
            minCol = maxCol = 0.0f;

        } else {
            // initialize as "unreferenced"
            std::fill(colors.begin(), colors.end(), -1.0f);
            size_t ptsSet = 0; // numbers of point-references set
            bool warnIndex = false; // should warn about illegal indices?

            maxCol = -1.0f; // if no particle color is ever set, this will be max

            // iterate through all references
            size_t listCnt = inListsPtr->Count();
            for (size_t listI = 0; listI < listCnt; ++listI) {
                MultiIndexListDataCall::index_list_t const& list = inListsPtr->Lists()[listI];
                size_t oldPtsSet = ptsSet;
                for (MultiIndexListDataCall::index_t const index : list) {
                    if (index >= pCnt) {
                        warnIndex = true;
                        continue;
                    }
                    if (colors[index] < -0.9f) {
                        ptsSet++;
                        colors[index] = static_cast<float>(listI);
                    }
                }
                // if at least one point was set, listI exists as color, thus is the current max value.
                if (oldPtsSet < ptsSet) maxCol = static_cast<float>(listI);
            }

            // set min, based if all points have been referenced
            assert(ptsSet <= pCnt);
            minCol = (ptsSet == pCnt) ? 0.0f : -1.0f;

        }

    }

    inListsPtr->Unlock();

    outData = inData;
    outData.SetDataHash(outHash);
    outData.SetFrameID(frameID);
    inData.SetUnlocker(nullptr, false);

    const float *data = colors.data();
    for (unsigned int list = 0; list < outData.GetParticleListCount(); ++list) {
        auto &plist = outData.AccessParticles(list);
        plist.SetColourData(core::moldyn::SimpleSphericalParticles::COLDATA_FLOAT_I, data, 0);
        plist.SetColourMapIndexValues(minCol, maxCol);
        data += plist.GetCount();
    }

    return true;
}
<|endoftext|>


<commit_before>
#include "TestWindow.h"

#include "ConsoleView.h"
#include "Label.h"
#include "Image.h"
#include "ListView.h"
#include "../Model/Font.h"
#include "../Controller/ResourceController.h"
#include "../Controller/RenderController.h"

using namespace RetroEnd::View;
using namespace RetroEnd::Model;
using namespace RetroEnd::Controller;

ListView* myList;

TestWindow::TestWindow()
{
	float H = (float)RenderController::getInstance().getScreenHeight();
	float W = (float)RenderController::getInstance().getScreenWidth();

	this->setSize( W, H );

	Image* background = new Image();
	background->setSize( W, H );
	background->setPath("data/images/bg_bn.png");
	background->setTiled(true);
	addChild(background);

	Label* title = new Label();
	title->setText("TEST WINDOW");
	title->setPosition(550,100);
	title->setColor(0x000000FF);

	this->addChild(title);

	mConsoleView = new ConsoleView(); //pre load images

	Image* logo = new Image();
	logo->setSize((float)RenderController::getInstance().getScreenWidth()/2, (float)RenderController::getInstance().getScreenHeight() / 2);
	logo->setPosition((float)RenderController::getInstance().getScreenWidth()/4, (float)RenderController::getInstance().getScreenHeight() / 4);
	logo->setPath("data/logo black.png");
	logo->setOpacity(0);
	addChild(logo);

	Animation* a = new Animation();

	a->millisDuration = 2000;
	a->endCallback = [this, logo] ()
	{
		Animation* a = new Animation();

		a->millisDuration = 2000;
		a->newOpacity = new unsigned char(255);
		a->endCallback = [this, logo] ()
		{
			Animation* a = new Animation();
			a->millisDuration = 1000;
			a->newSize = new Eigen::Vector2f((float)RenderController::getInstance().getScreenWidth()/5, (float)RenderController::getInstance().getScreenHeight() / 5);
			a->moveOffset = new Eigen::Vector3f((float)RenderController::getInstance().getScreenWidth()/2, (float)-RenderController::getInstance().getScreenHeight() / 4, 0);
			a->endCallback =  [this] ()
			{
				//Show Consoles
				mConsoleView->setSize((float)RenderController::getInstance().getScreenWidth(), (float)RenderController::getInstance().getScreenHeight());
				mConsoleView->setPosition(0,0);
				addChild(mConsoleView);
			};

			logo->animate(a);
		};

		logo->animate(a);
	};

	logo->animate(a);

}

bool TestWindow::input(Model::InputConfig* config, Model::Input input)
{
	if(input.id == SDLK_p && input.value != 0 )
	{
		RenderController::getInstance().pushPopupMessage("Miao testo lungo lungo lungo lungo lungo lungo lungo lungo lungo!", PopupMessageIcon::Info);
		return true;
	}

	//set input only to the last view added
	if(mChildren.size() > 0)
	{
		mChildren.at(mChildren.size() - 1)->input(config, input);
	}
	return true;
}
<commit_msg>Going to Raspberry PI -> Back to SDL (1)<commit_after>
#include "TestWindow.h"

#include "ConsoleView.h"
#include "Label.h"
#include "Image.h"
#include "ListView.h"
#include "../Model/Font.h"
#include "../Controller/ResourceController.h"
#include "../Controller/RenderController.h"

using namespace RetroEnd::View;
using namespace RetroEnd::Model;
using namespace RetroEnd::Controller;

ListView* myList;

TestWindow::TestWindow()
{
	float H = (float)RenderController::getInstance().getScreenHeight();
	float W = (float)RenderController::getInstance().getScreenWidth();

	this->setSize( W, H );

	Image* background = new Image();
	background->setSize( W, H );
	background->setPath("data/images/bg_bn.png");
	background->setTiled(true);
	addChild(background);

	Label* title = new Label();
	title->setText("TEST WINDOW");
	title->setPosition(550,100);
	title->setColor(0x000000FF);

	this->addChild(title);

	//mConsoleView = new ConsoleView(); //pre load images

	Image* logo = new Image();
	logo->setSize((float)RenderController::getInstance().getScreenWidth()/2, (float)RenderController::getInstance().getScreenHeight() / 2);
	logo->setPosition((float)RenderController::getInstance().getScreenWidth()/4, (float)RenderController::getInstance().getScreenHeight() / 4);
	logo->setPath("data/logo black.png");
	logo->setOpacity(0);
	addChild(logo);

	Animation* a = new Animation();

	a->millisDuration = 2000;
	a->endCallback = [this, logo] ()
	{
		Animation* a = new Animation();

		a->millisDuration = 2000;
		a->newOpacity = new unsigned char(255);
		a->endCallback = [this, logo] ()
		{
			Animation* a = new Animation();
			a->millisDuration = 1000;
			a->newSize = new Eigen::Vector2f((float)RenderController::getInstance().getScreenWidth()/5, (float)RenderController::getInstance().getScreenHeight() / 5);
			a->moveOffset = new Eigen::Vector3f((float)RenderController::getInstance().getScreenWidth()/2, (float)-RenderController::getInstance().getScreenHeight() / 4, 0);
			a->endCallback =  [this] ()
			{
				//Show Consoles
				mConsoleView->setSize((float)RenderController::getInstance().getScreenWidth(), (float)RenderController::getInstance().getScreenHeight());
				mConsoleView->setPosition(0,0);
				addChild(mConsoleView);
			};

			logo->animate(a);
		};

		logo->animate(a);
	};

	logo->animate(a);

}

bool TestWindow::input(Model::InputConfig* config, Model::Input input)
{
	if(input.id == SDLK_p && input.value != 0 )
	{
		RenderController::getInstance().pushPopupMessage("Miao testo lungo lungo lungo lungo lungo lungo lungo lungo lungo!", PopupMessageIcon::Info);
		return true;
	}

	//set input only to the last view added
	if(mChildren.size() > 0)
	{
		mChildren.at(mChildren.size() - 1)->input(config, input);
	}
	return true;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2008 Jürgen Riegel (juergen.riegel@web.de)              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
#endif

#include <Gui/Application.h>
#include <Gui/Command.h>
#include <Gui/MainWindow.h>
#include <Gui/FileDialog.h>

#include "BrowserView.h"

using namespace std;
using namespace Gui;
using namespace WebGui;

//===========================================================================
// CmdWebOpenWebsite
//===========================================================================

DEF_STD_CMD(CmdWebOpenWebsite);

CmdWebOpenWebsite::CmdWebOpenWebsite()
  : Command("Web_OpenWebsite")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Open website...");
    sToolTipText    = QT_TR_NOOP("Opens a website in FreeCAD");
    sWhatsThis      = "Web_OpenWebsite";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-browser";
}

void CmdWebOpenWebsite::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Doc,"import WebGui");
    doCommand(Command::Gui,"WebGui.openBrowser('http://www.freecadweb.org/')");
}

//===========================================================================
// CmdWebBrowserBack
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserBack);

CmdWebBrowserBack::CmdWebBrowserBack()
  : Command("Web_BrowserBack")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Previous page");
    sToolTipText    = QT_TR_NOOP("Go back to the previous page");
    sWhatsThis      = "Web_BrowserBack";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-previous";
}

void CmdWebBrowserBack::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Back')");
}

bool CmdWebBrowserBack::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Back");
}

//===========================================================================
// CmdWebBrowserNext
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserNext);

CmdWebBrowserNext::CmdWebBrowserNext()
  : Command("Web_BrowserNext")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Next page");
    sToolTipText    = QT_TR_NOOP("Go to the next page");
    sWhatsThis      = "Web_BrowserNext";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-next";
}

void CmdWebBrowserNext::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Next')");
}

bool CmdWebBrowserNext::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Next");
}

//===========================================================================
// CmdWebBrowserRefresh
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserRefresh);

CmdWebBrowserRefresh::CmdWebBrowserRefresh()
  : Command("Web_BrowserRefresh")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Refresh web page");
    sToolTipText    = QT_TR_NOOP("Refresh web page");
    sWhatsThis      = "Web_BrowserRefresh";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-refresh";
}

void CmdWebBrowserRefresh::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Refresh')");
}

bool CmdWebBrowserRefresh::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Refresh");
}
//===========================================================================
// CmdWebBrowserStop
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserStop);

CmdWebBrowserStop::CmdWebBrowserStop()
	:Command("Web_BrowserStop")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Stop loading");
    sToolTipText    = QT_TR_NOOP("Stop the current loading");
    sWhatsThis      = "Web_BrowserStop";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-stop";
}

void CmdWebBrowserStop::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Stop')");
}

bool CmdWebBrowserStop::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Stop");
}

//===========================================================================
// CmdWebBrowserZoomIn
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserZoomIn);

CmdWebBrowserZoomIn::CmdWebBrowserZoomIn()
  : Command("Web_BrowserZoomIn")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Zoom in");
    sToolTipText    = QT_TR_NOOP("Zoom into the page");
    sWhatsThis      = "Web_BrowserZoomIn";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-zoom-in";
}

void CmdWebBrowserZoomIn::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('ZoomIn')");
}

bool CmdWebBrowserZoomIn::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("ZoomIn");
}

//===========================================================================
// CmdWebBrowserZoomOut
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserZoomOut);

CmdWebBrowserZoomOut::CmdWebBrowserZoomOut()
  : Command("Web_BrowserZoomOut")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Zoom out");
    sToolTipText    = QT_TR_NOOP("Zoom out of the page");
    sWhatsThis      = "Web_BrowserZoomOut";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-zoom-out";
}

void CmdWebBrowserZoomOut::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('ZoomOut')");
}

bool CmdWebBrowserZoomOut::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("ZoomOut");
}

void CreateWebCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();

    rcCmdMgr.addCommand(new CmdWebOpenWebsite());
    rcCmdMgr.addCommand(new CmdWebBrowserBack());
    rcCmdMgr.addCommand(new CmdWebBrowserNext());
    rcCmdMgr.addCommand(new CmdWebBrowserRefresh());
    rcCmdMgr.addCommand(new CmdWebBrowserStop());
    rcCmdMgr.addCommand(new CmdWebBrowserZoomIn());
    rcCmdMgr.addCommand(new CmdWebBrowserZoomOut());
 }
<commit_msg>Crowdin: more fixes<commit_after>/***************************************************************************
 *   Copyright (c) 2008 Jürgen Riegel (juergen.riegel@web.de)              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
#endif

#include <Gui/Application.h>
#include <Gui/Command.h>
#include <Gui/MainWindow.h>
#include <Gui/FileDialog.h>

#include "BrowserView.h"

using namespace std;
using namespace Gui;
using namespace WebGui;

//===========================================================================
// CmdWebOpenWebsite
//===========================================================================

DEF_STD_CMD(CmdWebOpenWebsite);

CmdWebOpenWebsite::CmdWebOpenWebsite()
  : Command("Web_OpenWebsite")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Open website...");
    sToolTipText    = QT_TR_NOOP("Opens a website in FreeCAD");
    sWhatsThis      = "Web_OpenWebsite";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-browser";
}

void CmdWebOpenWebsite::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Doc,"import WebGui");
    doCommand(Command::Gui,"WebGui.openBrowser('http://www.freecadweb.org/')");
}

//===========================================================================
// CmdWebBrowserBack
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserBack);

CmdWebBrowserBack::CmdWebBrowserBack()
  : Command("Web_BrowserBack")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Previous page");
    sToolTipText    = QT_TR_NOOP("Go back to the previous page");
    sWhatsThis      = "Web_BrowserBack";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-previous";
}

void CmdWebBrowserBack::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Back')");
}

bool CmdWebBrowserBack::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Back");
}

//===========================================================================
// CmdWebBrowserNext
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserNext);

CmdWebBrowserNext::CmdWebBrowserNext()
  : Command("Web_BrowserNext")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Next page");
    sToolTipText    = QT_TR_NOOP("Go to the next page");
    sWhatsThis      = "Web_BrowserNext";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-next";
}

void CmdWebBrowserNext::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Next')");
}

bool CmdWebBrowserNext::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Next");
}

//===========================================================================
// CmdWebBrowserRefresh
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserRefresh);

CmdWebBrowserRefresh::CmdWebBrowserRefresh()
  : Command("Web_BrowserRefresh")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Refresh web page");
    sToolTipText    = QT_TR_NOOP("Refresh web page");
    sWhatsThis      = "Web_BrowserRefresh";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-refresh";
}

void CmdWebBrowserRefresh::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Refresh')");
}

bool CmdWebBrowserRefresh::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Refresh");
}
//===========================================================================
// CmdWebBrowserStop
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserStop);

CmdWebBrowserStop::CmdWebBrowserStop()
	:Command("Web_BrowserStop")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Stop loading");
    sToolTipText    = QT_TR_NOOP("Stop loading");
    sWhatsThis      = "Web_BrowserStop";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-stop";
}

void CmdWebBrowserStop::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('Stop')");
}

bool CmdWebBrowserStop::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("Stop");
}

//===========================================================================
// CmdWebBrowserZoomIn
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserZoomIn);

CmdWebBrowserZoomIn::CmdWebBrowserZoomIn()
  : Command("Web_BrowserZoomIn")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Zoom in");
    sToolTipText    = QT_TR_NOOP("Zoom in");
    sWhatsThis      = "Web_BrowserZoomIn";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-zoom-in";
}

void CmdWebBrowserZoomIn::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('ZoomIn')");
}

bool CmdWebBrowserZoomIn::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("ZoomIn");
}

//===========================================================================
// CmdWebBrowserZoomOut
//===========================================================================

DEF_STD_CMD_A(CmdWebBrowserZoomOut);

CmdWebBrowserZoomOut::CmdWebBrowserZoomOut()
  : Command("Web_BrowserZoomOut")
{
    sAppModule      = "Web";
    sGroup          = QT_TR_NOOP("Web");
    sMenuText       = QT_TR_NOOP("Zoom out");
    sToolTipText    = QT_TR_NOOP("Zoom out");
    sWhatsThis      = "Web_BrowserZoomOut";
    sStatusTip      = sToolTipText;
    sPixmap         = "actions/web-zoom-out";
}

void CmdWebBrowserZoomOut::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    doCommand(Command::Gui,"Gui.SendMsgToActiveView('ZoomOut')");
}

bool CmdWebBrowserZoomOut::isActive(void)
{
    return getGuiApplication()->sendHasMsgToActiveView("ZoomOut");
}

void CreateWebCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();

    rcCmdMgr.addCommand(new CmdWebOpenWebsite());
    rcCmdMgr.addCommand(new CmdWebBrowserBack());
    rcCmdMgr.addCommand(new CmdWebBrowserNext());
    rcCmdMgr.addCommand(new CmdWebBrowserRefresh());
    rcCmdMgr.addCommand(new CmdWebBrowserStop());
    rcCmdMgr.addCommand(new CmdWebBrowserZoomIn());
    rcCmdMgr.addCommand(new CmdWebBrowserZoomOut());
 }
<|endoftext|>


<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>RDBUFF is nice<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c), Recep Aslantas.
 *
 * MIT License (MIT), http://opensource.org/licenses/MIT
 * Full license can be found in the LICENSE file
 */

#include "sig.h"

#include <vector>
#include <map>
#include <string.h>

namespace sig {

#define SIG_REQ_TYPE_INT 0
#define SIG_REQ_TYPE_STR 1

#define sig_def_ctx const_cast<sig_context_t *>(sig_ctx_default())

typedef const char * CStringPtr;

struct sig_signal_req;

unsigned int s_last_sig_id = 1;
unsigned int s_sig_context_last_id = 1000;

struct cmp_str {
  bool operator()(char const *a, char const *b) const {
    return strcmp(a, b) < 0;
  }
};

std::vector<sig_signal_req *> signals_reqs;
std::map<CStringPtr, unsigned int, cmp_str> string_map;

struct sig_signal_req {
  typedef sig_observer_cb_t       sig_cb_t;
  typedef sig_mem_observer_base_t sig_mem_cb_t;
  typedef unsigned int            uid_t;
  typedef unsigned int            req_type_t;

  uid_t           uid;
  req_type_t      req_type;
  sig_context_t * ctx;
  sig_cb_t        cb;
  sig_mem_cb_t  * mem_cb;

  sig_signal_req(req_type_t req_type,
                 sig_context_t * ctx,
                 uid_t _uid,
                 sig_cb_t _cb);

  sig_signal_req(req_type_t req_type,
                 sig_context_t * ctx,
                 uid_t _uid,
                 sig_mem_cb_t * _cb);

  ~sig_signal_req();

  bool operator==(const uid_t& r1) const;
  void operator()(sig_signal_t s) const;
};

sig_signal_req::sig_signal_req(req_type_t _req_type,
                               sig_context_t * _ctx,
                               uid_t _uid,
                               sig_cb_t _cb)
  : req_type(_req_type),
    ctx(_ctx),
    uid(_uid),
    cb(_cb),
    mem_cb(NULL) { }

sig_signal_req::sig_signal_req(req_type_t _req_type,
                               sig_context_t * _ctx,
                               uid_t _uid,
                               sig_mem_cb_t * _cb)
  : req_type(_req_type),
    ctx(_ctx),
    uid(_uid),
    cb(NULL),
    mem_cb(_cb) { }

sig_signal_req::~sig_signal_req() {
  if (this->mem_cb)
    delete this->mem_cb;
}

bool
sig::sig_signal_req::operator==(const uid_t &an_uid) const {
  return this->uid == an_uid;
}

void
sig::sig_signal_req::operator()(sig_signal_t s) const {
  // non-member functions
  if (this->cb)
    this->cb(s);

  // Member functions
  if (this->mem_cb)
    this->mem_cb->operator()(s);
}

unsigned int
get_mapped_uid(CStringPtr signal) {
  unsigned int signal_uid = 0;
  std::map<CStringPtr, unsigned int>::iterator it = string_map.find(signal);
  if (it == string_map.end()) {
    signal_uid = ++s_last_sig_id;
    string_map.insert(std::make_pair(signal, signal_uid));
  } else {
    signal_uid = it->second;
  }
  return signal_uid;
}

template <typename _FuncType>
void
perform_attach(int signal,
               _FuncType cb,
               sig_context_t * ctx = sig_def_ctx) {
  sig::sig_signal_req * sig_req =
       new sig::sig_signal_req(SIG_REQ_TYPE_INT, ctx, signal, cb);
  sig::signals_reqs.push_back(sig_req);
}

template <typename _FuncType>
void
perform_attach(CStringPtr signal,
               _FuncType cb,
               sig_context_t * ctx = sig_def_ctx) {
  unsigned int signal_uid = get_mapped_uid(signal);

  sig::sig_signal_req * sig_req =
       new sig::sig_signal_req(SIG_REQ_TYPE_STR, ctx, signal_uid, cb);
  sig::signals_reqs.push_back(sig_req);
}

void
perform_fire(int signal,
             void * object,
             sig_context_t * ctx = sig_def_ctx) {
  std::vector<sig_signal_req *>::iterator it = sig::signals_reqs.begin();
  for (; it != sig::signals_reqs.end(); it++) {
     sig_signal_req sig_req = **it;
     if (sig_req.req_type == SIG_REQ_TYPE_INT
         && sig_req.ctx->ctx_id == ctx->ctx_id
         && sig_req == signal) {
       sig_signal_t signal_object(object,
                                  ctx,
                                  object);
       sig_req(signal_object);
     }
  }
}

void
perform_fire(CStringPtr signal,
             void * object,
             sig_context_t * ctx = sig_def_ctx) {
  unsigned int signal_uid = get_mapped_uid(signal);

  std::vector<sig_signal_req *>::iterator it = sig::signals_reqs.begin();
  for (; it != sig::signals_reqs.end(); it++) {
     sig_signal_req sig_req = **it;
     if (sig_req.req_type == SIG_REQ_TYPE_STR
         && sig_req.ctx->ctx_id == ctx->ctx_id
         && sig_req == signal_uid) {
       sig_signal_t signal_object(object,
                                  ctx,
                                  object);
       sig_req(signal_object);
     }
  }
}

} // namespace sig

sig_context_s::sig_context_s(int id)
  : ctx_id(id) { }

enum sig_reserved_context_id {
  kSigReservedContextId_Default = 0,
  kSigReservedContextId_Sys     = 1
};

const sig_context_t *
sig_ctx_default() {
  static  sig_context_t * __sig_default_ctx;
  if (!__sig_default_ctx) {
    __sig_default_ctx = new sig_context_t(kSigReservedContextId_Default);
  }
  return __sig_default_ctx;
}

const sig_context_t *
sig_ctx_sys() {
  static  sig_context_t * __sig_sys_ctx;
  if (!__sig_sys_ctx) {
    __sig_sys_ctx = new sig_context_t(kSigReservedContextId_Sys);
  }
  return __sig_sys_ctx;
}

const sig_context_t *
sig_ctx_new() {
  int next_id = ++sig::s_sig_context_last_id;
  sig_context_t * new_ctx = new sig_context_t(next_id);
  return new_ctx;
}

// default contexts
__SIG_C_DECL void
sig_attach(int signal, sig_observer_cb_t cb) {
  sig::perform_attach(signal, cb);
}

void
sig_attach(int signal, sig_observer_cb2_t cb) {
  sig::perform_attach(signal, cb);
}

void
sig_attach(const char * signal, sig_observer_cb_t cb) {
  sig::perform_attach(signal, cb);
}

void
sig_attach(const char * signal, sig_observer_cb2_t cb) {
  sig::perform_attach(signal, cb);
}

__SIG_C_DECL void
sig_attach_s(const char * signal, sig_observer_cb_t cb) {
  sig::perform_attach(signal, cb);
}

__SIG_C_DECL void
sig_fire(int signal, void * object) {
  sig::perform_fire(signal, object);
}

void
sig_fire(const char * signal, void * object) {
  sig::perform_fire(signal, object);
}

__SIG_C_DECL void
sig_fire_s(const char * signal, void * object) {
  sig::perform_fire(signal, object);
}

// custom contexts
__SIG_C_DECL void
sig_attachc(int signal,
            sig_observer_cb_t cb,
            const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, const_cast<sig_context_t *>(ctx));
}

void
sig_attach(int signal,
           sig_observer_cb_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, const_cast<sig_context_t *>(ctx));
}

void
sig_attach(int signal,
           sig_observer_cb2_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, const_cast<sig_context_t *>(ctx));
}

void
sig_attach(const char * signal,
           sig_observer_cb_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, const_cast<sig_context_t *>(ctx));
}

void
sig_attach(const char * signal,
           sig_observer_cb2_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, const_cast<sig_context_t *>(ctx));
}

__SIG_C_DECL void
sig_attachc_s(const char * signal,
              sig_observer_cb_t cb,
              const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, const_cast<sig_context_t *>(ctx));
}

__SIG_C_DECL void
sig_firec(int signal,
          void * object,
          const sig_context_t * ctx) {
  sig::perform_fire(signal, object, const_cast<sig_context_t *>(ctx));
}

void
sig_fire(const char * signal,
         void * object,
         const sig_context_t * ctx) {
  sig::perform_fire(signal, object, const_cast<sig_context_t *>(ctx));
}

__SIG_C_DECL void
sig_firec_s(const char * signal,
            void * object,
            const sig_context_t * ctx) {
  sig::perform_fire(signal, object, const_cast<sig_context_t *>(ctx));
}
<commit_msg>remove unnecessary const_cast-ings<commit_after>/*
 * Copyright (c), Recep Aslantas.
 *
 * MIT License (MIT), http://opensource.org/licenses/MIT
 * Full license can be found in the LICENSE file
 */

#include "sig.h"

#include <vector>
#include <map>
#include <string.h>

namespace sig {

#define SIG_REQ_TYPE_INT 0
#define SIG_REQ_TYPE_STR 1

#define sig_def_ctx sig_ctx_default()

typedef const char * CStringPtr;

struct sig_signal_req;

unsigned int s_last_sig_id = 1;
unsigned int s_sig_context_last_id = 1000;

struct cmp_str {
  bool operator()(char const *a, char const *b) const {
    return strcmp(a, b) < 0;
  }
};

std::vector<sig_signal_req *> signals_reqs;
std::map<CStringPtr, unsigned int, cmp_str> string_map;

struct sig_signal_req {
  typedef sig_observer_cb_t       sig_cb_t;
  typedef sig_mem_observer_base_t sig_mem_cb_t;
  typedef unsigned int            uid_t;
  typedef unsigned int            req_type_t;

  uid_t                 uid;
  req_type_t            req_type;
  sig_cb_t              cb;
  sig_mem_cb_t        * mem_cb;
  const sig_context_t * ctx;

  sig_signal_req(req_type_t req_type,
                 const sig_context_t * ctx,
                 uid_t _uid,
                 sig_cb_t _cb);

  sig_signal_req(req_type_t req_type,
                 const sig_context_t * ctx,
                 uid_t _uid,
                 sig_mem_cb_t * _cb);

  ~sig_signal_req();

  bool operator==(const uid_t& r1) const;
  void operator()(sig_signal_t s) const;
};

sig_signal_req::sig_signal_req(req_type_t _req_type,
                               const sig_context_t * _ctx,
                               uid_t _uid,
                               sig_cb_t _cb)
  : req_type(_req_type),
    ctx(_ctx),
    uid(_uid),
    cb(_cb),
    mem_cb(NULL) { }

sig_signal_req::sig_signal_req(req_type_t _req_type,
                               const sig_context_t * _ctx,
                               uid_t _uid,
                               sig_mem_cb_t * _cb)
  : req_type(_req_type),
    ctx(_ctx),
    uid(_uid),
    cb(NULL),
    mem_cb(_cb) { }

sig_signal_req::~sig_signal_req() {
  if (this->mem_cb)
    delete this->mem_cb;
}

bool
sig::sig_signal_req::operator==(const uid_t &an_uid) const {
  return this->uid == an_uid;
}

void
sig::sig_signal_req::operator()(sig_signal_t s) const {
  // non-member functions
  if (this->cb)
    this->cb(s);

  // Member functions
  if (this->mem_cb)
    this->mem_cb->operator()(s);
}

unsigned int
get_mapped_uid(CStringPtr signal) {
  unsigned int signal_uid = 0;
  std::map<CStringPtr, unsigned int>::iterator it = string_map.find(signal);
  if (it == string_map.end()) {
    signal_uid = ++s_last_sig_id;
    string_map.insert(std::make_pair(signal, signal_uid));
  } else {
    signal_uid = it->second;
  }
  return signal_uid;
}

template <typename _FuncType>
void
perform_attach(int signal,
               _FuncType cb,
               const sig_context_t * ctx = sig_def_ctx) {
  sig::sig_signal_req * sig_req =
       new sig::sig_signal_req(SIG_REQ_TYPE_INT, ctx, signal, cb);
  sig::signals_reqs.push_back(sig_req);
}

template <typename _FuncType>
void
perform_attach(CStringPtr signal,
               _FuncType cb,
               const sig_context_t * ctx = sig_def_ctx) {
  unsigned int signal_uid = get_mapped_uid(signal);

  sig::sig_signal_req * sig_req =
       new sig::sig_signal_req(SIG_REQ_TYPE_STR, ctx, signal_uid, cb);
  sig::signals_reqs.push_back(sig_req);
}

void
perform_fire(int signal,
             void * object,
             const sig_context_t * ctx = sig_def_ctx) {
  std::vector<sig_signal_req *>::iterator it = sig::signals_reqs.begin();
  for (; it != sig::signals_reqs.end(); it++) {
     sig_signal_req sig_req = **it;
     if (sig_req.req_type == SIG_REQ_TYPE_INT
         && sig_req.ctx->ctx_id == ctx->ctx_id
         && sig_req == signal) {
       sig_signal_t signal_object(object,
                                  ctx,
                                  object);
       sig_req(signal_object);
     }
  }
}

void
perform_fire(CStringPtr signal,
             void * object,
             const sig_context_t * ctx = sig_def_ctx) {
  unsigned int signal_uid = get_mapped_uid(signal);

  std::vector<sig_signal_req *>::iterator it = sig::signals_reqs.begin();
  for (; it != sig::signals_reqs.end(); it++) {
     sig_signal_req sig_req = **it;
     if (sig_req.req_type == SIG_REQ_TYPE_STR
         && sig_req.ctx->ctx_id == ctx->ctx_id
         && sig_req == signal_uid) {
       sig_signal_t signal_object(object,
                                  ctx,
                                  object);
       sig_req(signal_object);
     }
  }
}

} // namespace sig

sig_context_s::sig_context_s(int id)
  : ctx_id(id) { }

enum sig_reserved_context_id {
  kSigReservedContextId_Default = 0,
  kSigReservedContextId_Sys     = 1
};

const sig_context_t *
sig_ctx_default() {
  static  sig_context_t * __sig_default_ctx;
  if (!__sig_default_ctx) {
    __sig_default_ctx = new sig_context_t(kSigReservedContextId_Default);
  }
  return __sig_default_ctx;
}

const sig_context_t *
sig_ctx_sys() {
  static  sig_context_t * __sig_sys_ctx;
  if (!__sig_sys_ctx) {
    __sig_sys_ctx = new sig_context_t(kSigReservedContextId_Sys);
  }
  return __sig_sys_ctx;
}

const sig_context_t *
sig_ctx_new() {
  int next_id = ++sig::s_sig_context_last_id;
  sig_context_t * new_ctx = new sig_context_t(next_id);
  return new_ctx;
}

// default contexts
__SIG_C_DECL void
sig_attach(int signal, sig_observer_cb_t cb) {
  sig::perform_attach(signal, cb);
}

void
sig_attach(int signal, sig_observer_cb2_t cb) {
  sig::perform_attach(signal, cb);
}

void
sig_attach(const char * signal, sig_observer_cb_t cb) {
  sig::perform_attach(signal, cb);
}

void
sig_attach(const char * signal, sig_observer_cb2_t cb) {
  sig::perform_attach(signal, cb);
}

__SIG_C_DECL void
sig_attach_s(const char * signal, sig_observer_cb_t cb) {
  sig::perform_attach(signal, cb);
}

__SIG_C_DECL void
sig_fire(int signal, void * object) {
  sig::perform_fire(signal, object);
}

void
sig_fire(const char * signal, void * object) {
  sig::perform_fire(signal, object);
}

__SIG_C_DECL void
sig_fire_s(const char * signal, void * object) {
  sig::perform_fire(signal, object);
}

// custom contexts
__SIG_C_DECL void
sig_attachc(int signal,
            sig_observer_cb_t cb,
            const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, ctx);
}

void
sig_attach(int signal,
           sig_observer_cb_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, ctx);
}

void
sig_attach(int signal,
           sig_observer_cb2_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, ctx);
}

void
sig_attach(const char * signal,
           sig_observer_cb_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, ctx);
}

void
sig_attach(const char * signal,
           sig_observer_cb2_t cb,
           const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, ctx);
}

__SIG_C_DECL void
sig_attachc_s(const char * signal,
              sig_observer_cb_t cb,
              const sig_context_t * ctx) {
  sig::perform_attach(signal, cb, ctx);
}

__SIG_C_DECL void
sig_firec(int signal,
          void * object,
          const sig_context_t * ctx) {
  sig::perform_fire(signal, object, ctx);
}

void
sig_fire(const char * signal,
         void * object,
         const sig_context_t * ctx) {
  sig::perform_fire(signal, object, ctx);
}

__SIG_C_DECL void
sig_firec_s(const char * signal,
            void * object,
            const sig_context_t * ctx) {
  sig::perform_fire(signal, object, ctx);
}
<|endoftext|>