<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "environment.h"

#include <QDir>
#include <QProcess>
#include <QString>
#include <QCoreApplication>

class SystemEnvironment : public Utils::Environment
{
public:
    SystemEnvironment()
        : Environment(QProcess::systemEnvironment())
    {
#ifdef Q_OS_LINUX
        QString ldLibraryPath = value(QLatin1String("LD_LIBRARY_PATH"));
        QDir lib(QCoreApplication::applicationDirPath());
        lib.cd("../lib");
        QString toReplace = lib.path();
        lib.cd("qtcreator");
        toReplace.append(QLatin1String(":"));
        toReplace.append(lib.path());

        if (ldLibraryPath.startsWith(toReplace))
            set(QLatin1String("LD_LIBRARY_PATH"), ldLibraryPath.remove(0, toReplace.length()));
#endif
    }
};

Q_GLOBAL_STATIC(SystemEnvironment, staticSystemEnvironment)

namespace Utils {

static bool sortEnvironmentItem(const EnvironmentItem &a, const EnvironmentItem &b)
{
    return a.name < b.name;
}

void EnvironmentItem::sort(QList<EnvironmentItem> *list)
{
    qSort(list->begin(), list->end(), &sortEnvironmentItem);
}

QList<EnvironmentItem> EnvironmentItem::fromStringList(const QStringList &list)
{
    QList<EnvironmentItem> result;
    foreach (const QString &string, list) {
        int pos = string.indexOf(QLatin1Char('='));
        if (pos == -1) {
            EnvironmentItem item(string, QString());
            item.unset = true;
            result.append(item);
        } else {
            EnvironmentItem item(string.left(pos), string.mid(pos+1));
            result.append(item);
        }
    }
    return result;
}

QStringList EnvironmentItem::toStringList(const QList<EnvironmentItem> &list)
{
    QStringList result;
    foreach (const EnvironmentItem &item, list) {
        if (item.unset)
            result << QString(item.name);
        else
            result << QString(item.name + QLatin1Char('=') + item.value);
    }
    return result;
}

Environment::Environment(const QStringList &env)
{
    foreach (const QString &s, env) {
        int i = s.indexOf(QLatin1Char('='));
        if (i >= 0) {
#ifdef Q_OS_WIN
            m_values.insert(s.left(i).toUpper(), s.mid(i+1));
#else
            m_values.insert(s.left(i), s.mid(i+1));
#endif
        }
    }
}

QStringList Environment::toStringList() const
{
    QStringList result;
    const QMap<QString, QString>::const_iterator end = m_values.constEnd();
    for (QMap<QString, QString>::const_iterator it = m_values.constBegin(); it != end; ++it) {
        QString entry = it.key();
        entry += QLatin1Char('=');
        entry += it.value();
        result.push_back(entry);
    }
    return result;
}

void Environment::set(const QString &key, const QString &value)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    m_values.insert(_key, value);
}

void Environment::unset(const QString &key)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    m_values.remove(_key);
}

void Environment::appendOrSet(const QString &key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    QMap<QString, QString>::iterator it = m_values.find(key);
    if (it == m_values.end()) {
        m_values.insert(_key, value);
    } else {
        // Append unless it is already there
        const QString toAppend = sep + value;
        if (!it.value().endsWith(toAppend))
            it.value().append(toAppend);
    }
}

void Environment::prependOrSet(const QString&key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    QMap<QString, QString>::iterator it = m_values.find(key);
    if (it == m_values.end()) {
        m_values.insert(_key, value);
    } else {
        // Prepend unless it is already there
        const QString toPrepend = value + sep;
        if (!it.value().startsWith(toPrepend))
            it.value().prepend(toPrepend);
    }
}

void Environment::appendOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
    const QChar sep = QLatin1Char(';');
#else
    const QChar sep = QLatin1Char(':');
#endif
    appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}

void Environment::prependOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
    const QChar sep = QLatin1Char(';');
#else
    const QChar sep = QLatin1Char(':');
#endif
    prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}

void Environment::prependOrSetLibrarySearchPath(const QString &value)
{
#ifdef Q_OS_MAC
    Q_UNUSED(value);
    // we could set DYLD_LIBRARY_PATH on Mac but it is unnecessary in practice
#elif defined(Q_OS_WIN)
    const QChar sep = QLatin1Char(';');
    const QLatin1String path("PATH");
    prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
#elif defined(Q_OS_UNIX)
    const QChar sep = QLatin1Char(':');
    const QLatin1String path("LD_LIBRARY_PATH");
    prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
#endif
}

Environment Environment::systemEnvironment()
{
    return *staticSystemEnvironment();
}

void Environment::clear()
{
    m_values.clear();
}

QString Environment::searchInDirectory(const QStringList &execs, QString directory) const
{
    const QChar slash = QLatin1Char('/');
    if (directory.isEmpty())
        return QString();
    // Avoid turing / into // on windows which triggers windows to check
    // for network drives!
    if (!directory.endsWith(slash))
        directory += slash;

    foreach (const QString &exec, execs) {
        QFileInfo fi(directory + exec);
        if (fi.exists() && fi.isFile() && fi.isExecutable())
            return fi.absoluteFilePath();
    }
    return QString();
}

QString Environment::searchInPath(const QString &executable,
                                  const QStringList &additionalDirs) const
{
    QString exec = QDir::cleanPath(expandVariables(executable));
    QFileInfo fi(exec);
    if (fi.isAbsolute())
        return exec;

    if (executable.isEmpty())
        return QString();

    QStringList execs;
#ifdef Q_OS_WIN
    // Check all the executable extensions on windows:
    // PATHEXT is only used if the executable has no extension
    if (fi.suffix().isEmpty()) {
        QStringList extensions = value(QLatin1String("PATHEXT")).split(QLatin1Char(';'));

        foreach (const QString &ext, extensions)
            execs << executable + ext.toLower();
    }
#endif

    foreach (QString dir, additionalDirs) {
        QString tmp = searchInDirectory(execs, dir);
        if (!tmp.isEmpty())
            return tmp;
    }

    if (executable.indexOf(QLatin1Char('/')) != -1)
        return QString();

    foreach (const QString &p, path()) {
        QString tmp = searchInDirectory(execs, QDir::fromNativeSeparators(p));
        if (!tmp.isEmpty())
            return tmp;
    }
    return QString();
}

QStringList Environment::path() const
{
#ifdef Q_OS_WIN
    const QChar sep = QLatin1Char(';');
#else
    const QChar sep = QLatin1Char(':');
#endif
    return m_values.value(QLatin1String("PATH")).split(sep, QString::SkipEmptyParts);
}

QString Environment::value(const QString &key) const
{
    return m_values.value(key);
}

QString Environment::key(Environment::const_iterator it) const
{
    return it.key();
}

QString Environment::value(Environment::const_iterator it) const
{
    return it.value();
}

Environment::const_iterator Environment::constBegin() const
{
    return m_values.constBegin();
}

Environment::const_iterator Environment::constEnd() const
{
    return m_values.constEnd();
}

Environment::const_iterator Environment::constFind(const QString &name) const
{
    QMap<QString, QString>::const_iterator it = m_values.constFind(name);
    if (it == m_values.constEnd())
        return constEnd();
    else
        return it;
}

int Environment::size() const
{
    return m_values.size();
}

void Environment::modify(const QList<EnvironmentItem> & list)
{
    Environment resultEnvironment = *this;
    foreach (const EnvironmentItem &item, list) {
        if (item.unset) {
            resultEnvironment.unset(item.name);
        } else {
            // TODO use variable expansion
            QString value = item.value;
            for (int i=0; i < value.size(); ++i) {
                if (value.at(i) == QLatin1Char('$')) {
                    if ((i + 1) < value.size()) {
                        const QChar &c = value.at(i+1);
                        int end = -1;
                        if (c == QLatin1Char('('))
                            end = value.indexOf(QLatin1Char(')'), i);
                        else if (c == QLatin1Char('{'))
                            end = value.indexOf(QLatin1Char('}'), i);
                        if (end != -1) {
                            const QString &name = value.mid(i+2, end-i-2);
                            Environment::const_iterator it = constFind(name);
                            if (it != constEnd())
                                value.replace(i, end-i+1, it.value());
                        }
                    }
                }
            }
            resultEnvironment.set(item.name, value);
        }
    }
    *this = resultEnvironment;
}

QList<EnvironmentItem> Environment::diff(const Environment &other) const
{
    QMap<QString, QString>::const_iterator thisIt = constBegin();
    QMap<QString, QString>::const_iterator otherIt = other.constBegin();

    QList<EnvironmentItem> result;
    while (thisIt != constEnd() || otherIt != other.constEnd()) {
        if (thisIt == constEnd()) {
            result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
            ++otherIt;
        } else if (otherIt == constEnd()) {
            Utils::EnvironmentItem item(thisIt.key(), QString());
            item.unset = true;
            result.append(item);
            ++thisIt;
        } else if (thisIt.key() < otherIt.key()) {
            Utils::EnvironmentItem item(thisIt.key(), QString());
            item.unset = true;
            result.append(item);
            ++thisIt;
        } else if (thisIt.key() > otherIt.key()) {
            result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
            ++otherIt;
        } else {
            result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
            ++otherIt;
            ++thisIt;
        }
    }
    return result;
}

bool Environment::hasKey(const QString &key)
{
    return m_values.contains(key);
}

bool Environment::operator!=(const Environment &other) const
{
    return !(*this == other);
}

bool Environment::operator==(const Environment &other) const
{
    return m_values == other.m_values;
}

/** Expand environment variables in a string.
 *
 * Environment variables are accepted in the following forms:
 * $SOMEVAR, ${SOMEVAR} on Unix and %SOMEVAR% on Windows.
 * No escapes and quoting are supported.
 * If a variable is not found, it is not substituted.
 */
QString Environment::expandVariables(const QString &input) const
{
    QString result = input;

#ifdef Q_OS_WIN
    for (int vStart = -1, i = 0; i < result.length(); ) {
        if (result.at(i++) == QLatin1Char('%')) {
            if (vStart > 0) {
                const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1).toUpper());
                if (it != m_values.constEnd()) {
                    result.replace(vStart - 1, i - vStart + 1, *it);
                    i = vStart - 1 + it->length();
                    vStart = -1;
                } else {
                    vStart = i;
                }
            } else {
                vStart = i;
            }
        }
    }
#else
    enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
    int vStart = -1;

    for (int i = 0; i < result.length();) {
        QChar c = result.at(i++);
        if (state == BASE) {
            if (c == QLatin1Char('$'))
                state = OPTIONALVARIABLEBRACE;
        } else if (state == OPTIONALVARIABLEBRACE) {
            if (c == QLatin1Char('{')) {
                state = BRACEDVARIABLE;
                vStart = i;
            } else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
                state = VARIABLE;
                vStart = i - 1;
            } else {
                state = BASE;
            }
        } else if (state == BRACEDVARIABLE) {
            if (c == QLatin1Char('}')) {
                const_iterator it = m_values.constFind(result.mid(vStart, i - 1 - vStart));
                if (it != constEnd()) {
                    result.replace(vStart - 2, i - vStart + 2, *it);
                    i = vStart - 2 + it->length();
                }
                state = BASE;
            }
        } else if (state == VARIABLE) {
            if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
                const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1));
                if (it != constEnd()) {
                    result.replace(vStart - 1, i - vStart, *it);
                    i = vStart - 1 + it->length();
                }
                state = BASE;
            }
        }
    }
    if (state == VARIABLE) {
        const_iterator it = m_values.constFind(result.mid(vStart));
        if (it != constEnd())
            result.replace(vStart - 1, result.length() - vStart + 1, *it);
    }
#endif
    return result;
}

QStringList Environment::expandVariables(const QStringList &variables) const
{
    QStringList results;
    foreach (const QString &i, variables)
        results << expandVariables(i);
    return results;
}

} // namespace Utils
<commit_msg>Fix searchInPath<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "environment.h"

#include <QDir>
#include <QProcess>
#include <QString>
#include <QCoreApplication>

class SystemEnvironment : public Utils::Environment
{
public:
    SystemEnvironment()
        : Environment(QProcess::systemEnvironment())
    {
#ifdef Q_OS_LINUX
        QString ldLibraryPath = value(QLatin1String("LD_LIBRARY_PATH"));
        QDir lib(QCoreApplication::applicationDirPath());
        lib.cd("../lib");
        QString toReplace = lib.path();
        lib.cd("qtcreator");
        toReplace.append(QLatin1String(":"));
        toReplace.append(lib.path());

        if (ldLibraryPath.startsWith(toReplace))
            set(QLatin1String("LD_LIBRARY_PATH"), ldLibraryPath.remove(0, toReplace.length()));
#endif
    }
};

Q_GLOBAL_STATIC(SystemEnvironment, staticSystemEnvironment)

namespace Utils {

static bool sortEnvironmentItem(const EnvironmentItem &a, const EnvironmentItem &b)
{
    return a.name < b.name;
}

void EnvironmentItem::sort(QList<EnvironmentItem> *list)
{
    qSort(list->begin(), list->end(), &sortEnvironmentItem);
}

QList<EnvironmentItem> EnvironmentItem::fromStringList(const QStringList &list)
{
    QList<EnvironmentItem> result;
    foreach (const QString &string, list) {
        int pos = string.indexOf(QLatin1Char('='));
        if (pos == -1) {
            EnvironmentItem item(string, QString());
            item.unset = true;
            result.append(item);
        } else {
            EnvironmentItem item(string.left(pos), string.mid(pos+1));
            result.append(item);
        }
    }
    return result;
}

QStringList EnvironmentItem::toStringList(const QList<EnvironmentItem> &list)
{
    QStringList result;
    foreach (const EnvironmentItem &item, list) {
        if (item.unset)
            result << QString(item.name);
        else
            result << QString(item.name + QLatin1Char('=') + item.value);
    }
    return result;
}

Environment::Environment(const QStringList &env)
{
    foreach (const QString &s, env) {
        int i = s.indexOf(QLatin1Char('='));
        if (i >= 0) {
#ifdef Q_OS_WIN
            m_values.insert(s.left(i).toUpper(), s.mid(i+1));
#else
            m_values.insert(s.left(i), s.mid(i+1));
#endif
        }
    }
}

QStringList Environment::toStringList() const
{
    QStringList result;
    const QMap<QString, QString>::const_iterator end = m_values.constEnd();
    for (QMap<QString, QString>::const_iterator it = m_values.constBegin(); it != end; ++it) {
        QString entry = it.key();
        entry += QLatin1Char('=');
        entry += it.value();
        result.push_back(entry);
    }
    return result;
}

void Environment::set(const QString &key, const QString &value)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    m_values.insert(_key, value);
}

void Environment::unset(const QString &key)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    m_values.remove(_key);
}

void Environment::appendOrSet(const QString &key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    QMap<QString, QString>::iterator it = m_values.find(key);
    if (it == m_values.end()) {
        m_values.insert(_key, value);
    } else {
        // Append unless it is already there
        const QString toAppend = sep + value;
        if (!it.value().endsWith(toAppend))
            it.value().append(toAppend);
    }
}

void Environment::prependOrSet(const QString&key, const QString &value, const QString &sep)
{
#ifdef Q_OS_WIN
    QString _key = key.toUpper();
#else
    const QString &_key = key;
#endif
    QMap<QString, QString>::iterator it = m_values.find(key);
    if (it == m_values.end()) {
        m_values.insert(_key, value);
    } else {
        // Prepend unless it is already there
        const QString toPrepend = value + sep;
        if (!it.value().startsWith(toPrepend))
            it.value().prepend(toPrepend);
    }
}

void Environment::appendOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
    const QChar sep = QLatin1Char(';');
#else
    const QChar sep = QLatin1Char(':');
#endif
    appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}

void Environment::prependOrSetPath(const QString &value)
{
#ifdef Q_OS_WIN
    const QChar sep = QLatin1Char(';');
#else
    const QChar sep = QLatin1Char(':');
#endif
    prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
}

void Environment::prependOrSetLibrarySearchPath(const QString &value)
{
#ifdef Q_OS_MAC
    Q_UNUSED(value);
    // we could set DYLD_LIBRARY_PATH on Mac but it is unnecessary in practice
#elif defined(Q_OS_WIN)
    const QChar sep = QLatin1Char(';');
    const QLatin1String path("PATH");
    prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
#elif defined(Q_OS_UNIX)
    const QChar sep = QLatin1Char(':');
    const QLatin1String path("LD_LIBRARY_PATH");
    prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
#endif
}

Environment Environment::systemEnvironment()
{
    return *staticSystemEnvironment();
}

void Environment::clear()
{
    m_values.clear();
}

QString Environment::searchInDirectory(const QStringList &execs, QString directory) const
{
    const QChar slash = QLatin1Char('/');
    if (directory.isEmpty())
        return QString();
    // Avoid turing / into // on windows which triggers windows to check
    // for network drives!
    if (!directory.endsWith(slash))
        directory += slash;

    foreach (const QString &exec, execs) {
        QFileInfo fi(directory + exec);
        if (fi.exists() && fi.isFile() && fi.isExecutable())
            return fi.absoluteFilePath();
    }
    return QString();
}

QString Environment::searchInPath(const QString &executable,
                                  const QStringList &additionalDirs) const
{
    QString exec = QDir::cleanPath(expandVariables(executable));
    QFileInfo fi(exec);
    if (fi.isAbsolute())
        return exec;

    if (executable.isEmpty())
        return QString();

    QStringList execs(exec);
#ifdef Q_OS_WIN
    // Check all the executable extensions on windows:
    // PATHEXT is only used if the executable has no extension
    if (fi.suffix().isEmpty()) {
        QStringList extensions = value(QLatin1String("PATHEXT")).split(QLatin1Char(';'));

        foreach (const QString &ext, extensions)
            execs << executable + ext.toLower();
    }
#endif

    foreach (QString dir, additionalDirs) {
        QString tmp = searchInDirectory(execs, dir);
        if (!tmp.isEmpty())
            return tmp;
    }

    if (executable.indexOf(QLatin1Char('/')) != -1)
        return QString();

    foreach (const QString &p, path()) {
        QString tmp = searchInDirectory(execs, QDir::fromNativeSeparators(p));
        if (!tmp.isEmpty())
            return tmp;
    }
    return QString();
}

QStringList Environment::path() const
{
#ifdef Q_OS_WIN
    const QChar sep = QLatin1Char(';');
#else
    const QChar sep = QLatin1Char(':');
#endif
    return m_values.value(QLatin1String("PATH")).split(sep, QString::SkipEmptyParts);
}

QString Environment::value(const QString &key) const
{
    return m_values.value(key);
}

QString Environment::key(Environment::const_iterator it) const
{
    return it.key();
}

QString Environment::value(Environment::const_iterator it) const
{
    return it.value();
}

Environment::const_iterator Environment::constBegin() const
{
    return m_values.constBegin();
}

Environment::const_iterator Environment::constEnd() const
{
    return m_values.constEnd();
}

Environment::const_iterator Environment::constFind(const QString &name) const
{
    QMap<QString, QString>::const_iterator it = m_values.constFind(name);
    if (it == m_values.constEnd())
        return constEnd();
    else
        return it;
}

int Environment::size() const
{
    return m_values.size();
}

void Environment::modify(const QList<EnvironmentItem> & list)
{
    Environment resultEnvironment = *this;
    foreach (const EnvironmentItem &item, list) {
        if (item.unset) {
            resultEnvironment.unset(item.name);
        } else {
            // TODO use variable expansion
            QString value = item.value;
            for (int i=0; i < value.size(); ++i) {
                if (value.at(i) == QLatin1Char('$')) {
                    if ((i + 1) < value.size()) {
                        const QChar &c = value.at(i+1);
                        int end = -1;
                        if (c == QLatin1Char('('))
                            end = value.indexOf(QLatin1Char(')'), i);
                        else if (c == QLatin1Char('{'))
                            end = value.indexOf(QLatin1Char('}'), i);
                        if (end != -1) {
                            const QString &name = value.mid(i+2, end-i-2);
                            Environment::const_iterator it = constFind(name);
                            if (it != constEnd())
                                value.replace(i, end-i+1, it.value());
                        }
                    }
                }
            }
            resultEnvironment.set(item.name, value);
        }
    }
    *this = resultEnvironment;
}

QList<EnvironmentItem> Environment::diff(const Environment &other) const
{
    QMap<QString, QString>::const_iterator thisIt = constBegin();
    QMap<QString, QString>::const_iterator otherIt = other.constBegin();

    QList<EnvironmentItem> result;
    while (thisIt != constEnd() || otherIt != other.constEnd()) {
        if (thisIt == constEnd()) {
            result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
            ++otherIt;
        } else if (otherIt == constEnd()) {
            Utils::EnvironmentItem item(thisIt.key(), QString());
            item.unset = true;
            result.append(item);
            ++thisIt;
        } else if (thisIt.key() < otherIt.key()) {
            Utils::EnvironmentItem item(thisIt.key(), QString());
            item.unset = true;
            result.append(item);
            ++thisIt;
        } else if (thisIt.key() > otherIt.key()) {
            result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
            ++otherIt;
        } else {
            result.append(Utils::EnvironmentItem(otherIt.key(), otherIt.value()));
            ++otherIt;
            ++thisIt;
        }
    }
    return result;
}

bool Environment::hasKey(const QString &key)
{
    return m_values.contains(key);
}

bool Environment::operator!=(const Environment &other) const
{
    return !(*this == other);
}

bool Environment::operator==(const Environment &other) const
{
    return m_values == other.m_values;
}

/** Expand environment variables in a string.
 *
 * Environment variables are accepted in the following forms:
 * $SOMEVAR, ${SOMEVAR} on Unix and %SOMEVAR% on Windows.
 * No escapes and quoting are supported.
 * If a variable is not found, it is not substituted.
 */
QString Environment::expandVariables(const QString &input) const
{
    QString result = input;

#ifdef Q_OS_WIN
    for (int vStart = -1, i = 0; i < result.length(); ) {
        if (result.at(i++) == QLatin1Char('%')) {
            if (vStart > 0) {
                const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1).toUpper());
                if (it != m_values.constEnd()) {
                    result.replace(vStart - 1, i - vStart + 1, *it);
                    i = vStart - 1 + it->length();
                    vStart = -1;
                } else {
                    vStart = i;
                }
            } else {
                vStart = i;
            }
        }
    }
#else
    enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
    int vStart = -1;

    for (int i = 0; i < result.length();) {
        QChar c = result.at(i++);
        if (state == BASE) {
            if (c == QLatin1Char('$'))
                state = OPTIONALVARIABLEBRACE;
        } else if (state == OPTIONALVARIABLEBRACE) {
            if (c == QLatin1Char('{')) {
                state = BRACEDVARIABLE;
                vStart = i;
            } else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
                state = VARIABLE;
                vStart = i - 1;
            } else {
                state = BASE;
            }
        } else if (state == BRACEDVARIABLE) {
            if (c == QLatin1Char('}')) {
                const_iterator it = m_values.constFind(result.mid(vStart, i - 1 - vStart));
                if (it != constEnd()) {
                    result.replace(vStart - 2, i - vStart + 2, *it);
                    i = vStart - 2 + it->length();
                }
                state = BASE;
            }
        } else if (state == VARIABLE) {
            if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
                const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1));
                if (it != constEnd()) {
                    result.replace(vStart - 1, i - vStart, *it);
                    i = vStart - 1 + it->length();
                }
                state = BASE;
            }
        }
    }
    if (state == VARIABLE) {
        const_iterator it = m_values.constFind(result.mid(vStart));
        if (it != constEnd())
            result.replace(vStart - 1, result.length() - vStart + 1, *it);
    }
#endif
    return result;
}

QStringList Environment::expandVariables(const QStringList &variables) const
{
    QStringList results;
    foreach (const QString &i, variables)
        results << expandVariables(i);
    return results;
}

} // namespace Utils
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include <utils/savedaction.h>

#include <utils/qtcassert.h>
#include <utils/pathchooser.h>

#include <QtCore/QDebug>
#include <QtCore/QSettings>

#include <QtGui/QAbstractButton>
#include <QtGui/QAction>
#include <QtGui/QActionGroup>
#include <QtGui/QCheckBox>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
#include <QtGui/QSpinBox>

using namespace Core::Utils;

//////////////////////////////////////////////////////////////////////////
//
// SavedAction
//
//////////////////////////////////////////////////////////////////////////

/*!
    \class Core::Utils::SavedAction

    \brief The SavedAction class is a helper class for actions with persistent
    state.

    \ingroup utils

*/

SavedAction::SavedAction(QObject *parent)
  : QAction(parent)
{
    m_widget = 0;
    connect(this, SIGNAL(triggered(bool)), this, SLOT(actionTriggered(bool)));
}

/*!
    Returns the current value of the object.

    \sa setValue()
*/
QVariant SavedAction::value() const
{
    return m_value;
}

/*!
    Sets the current value of the object. If the value changed and
    \a doemit is true, the \c valueChanged() signal will be emitted.

    \sa value()
*/
void SavedAction::setValue(const QVariant &value, bool doemit)
{
    if (value == m_value)
        return;
    m_value = value;
    if (this->isCheckable())
        this->setChecked(m_value.toBool());
    if (doemit)
        emit valueChanged(m_value);
}

/*!
    Returns the default value to be used when the item does not exist yet
    in the settings.

    \sa setDefaultValue()
*/
QVariant SavedAction::defaultValue() const
{
    return m_defaultValue;
}

/*!
    Sets the default value to be used when the item does not exist yet
    in the settings.

    \sa defaultValue()
*/
void SavedAction::setDefaultValue(const QVariant &value)
{
    m_defaultValue = value;
}

/*!
    Returns the key to be used when accessing the settings.

    \sa settingsKey()
*/
QString SavedAction::settingsKey() const
{
    return m_settingsKey;
}

/*!
    Sets the key to be used when accessing the settings.

    \sa settingsKey()
*/
void SavedAction::setSettingsKey(const QString &key)
{
    m_settingsKey = key;
}

/*!
    Sets the key and group to be used when accessing the settings.

    \sa settingsKey()
*/
void SavedAction::setSettingsKey(const QString &group, const QString &key)
{
    m_settingsKey = key;
    m_settingsGroup = group;
}

/*!
    Sets the key to be used when accessing the settings.

    \sa settingsKey()
*/
QString SavedAction::settingsGroup() const
{
    return m_settingsGroup;
}

/*!
    Sets the group to be used when accessing the settings.

    \sa settingsGroup()
*/
void SavedAction::setSettingsGroup(const QString &group)
{
    m_settingsGroup = group;
}

QString SavedAction::textPattern() const
{
    return m_textPattern;
}

void SavedAction::setTextPattern(const QString &value)
{
    m_textPattern = value;
}

QString SavedAction::toString() const
{
    return QLatin1String("value: ") + m_value.toString()
        + QLatin1String("  defaultvalue: ") + m_defaultValue.toString()
        + QLatin1String("  settingskey: ") + m_settingsGroup
        + '/' + m_settingsKey;
}

/*!
    \fn QAction *SavedAction::updatedAction(const QString &text)

    Adjust the \c text() of the underlying action.

    This can be used to update the item shortly before e.g. a menu is shown.

    If the item's \c textPattern() is empty the \a text will be used
    verbatim.

    Otherwise, the behaviour depends on \a text: if it is non-empty,
    \c QString(textPattern()).arg(text), otherwise, \c textPattern()
    with the "%1" placeholder removed will be used.

    \sa textPattern(), setTextPattern()
*/
QAction *SavedAction::updatedAction(const QString &text0)
{
    QString text = text0;
    bool enabled = true;
    if (!m_textPattern.isEmpty()) {
        if (text.isEmpty()) {
            text = m_textPattern;
            text.remove("\"%1\"");
            text.remove("%1");
            enabled = false;
        } else {
            text = m_textPattern.arg(text0);
        }
    }
    this->setEnabled(enabled);
    this->setData(text0);
    this->setText(text);
    return this;
}

/*
    Uses \c settingsGroup() and \c settingsKey() to restore the
    item from \a settings,

    \sa settingsKey(), settingsGroup(), writeSettings()
*/
void SavedAction::readSettings(QSettings *settings)
{
    if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty())
        return;
    settings->beginGroup(m_settingsGroup);
    setValue(settings->value(m_settingsKey, m_defaultValue), false);
    //qDebug() << "READING: " << m_settingsKey << " -> " << m_value;
    settings->endGroup();
}

/*
    Uses \c settingsGroup() and \c settingsKey() to write the
    item to \a settings,

    \sa settingsKey(), settingsGroup(), readSettings()
*/
void SavedAction::writeSettings(QSettings *settings)
{
    if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty())
        return;
    settings->beginGroup(m_settingsGroup);
    settings->setValue(m_settingsKey, m_value);
    //qDebug() << "WRITING: " << m_settingsKey << " -> " << toString();
    settings->endGroup();
}

/*
    A \c SavedAction can be connected to a widget, typically a
    checkbox, radiobutton, or a lineedit in some configuration dialog.

    The widget will retrieve its contents from the SavedAction's
    value, and - depending on the \a ApplyMode - either write
    changes back immediately, or when \s SavedAction::apply()
    is called explicitly.

    \sa apply(), disconnectWidget()
*/
void SavedAction::connectWidget(QWidget *widget, ApplyMode applyMode)
{
    QTC_ASSERT(!m_widget,
        qDebug() << "ALREADY CONNECTED: " << widget << m_widget << toString(); return);
    m_widget = widget;
    m_applyMode = applyMode;

    if (QAbstractButton *button = qobject_cast<QAbstractButton *>(widget)) {
        if (button->isCheckable()) {
            button->setChecked(m_value.toBool());
            connect(button, SIGNAL(clicked(bool)),
                this, SLOT(checkableButtonClicked(bool)));
        } else {
            connect(button, SIGNAL(clicked()),
                this, SLOT(uncheckableButtonClicked()));
        }
    } else if (QSpinBox *spinBox = qobject_cast<QSpinBox *>(widget)) {
        spinBox->setValue(m_value.toInt());
        //qDebug() << "SETTING VALUE" << spinBox->value();
        connect(spinBox, SIGNAL(valueChanged(int)),
            this, SLOT(spinBoxValueChanged(int)));
        connect(spinBox, SIGNAL(valueChanged(QString)),
            this, SLOT(spinBoxValueChanged(QString)));
    } else if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) {
        lineEdit->setText(m_value.toString());
        //qDebug() << "SETTING TEXT" << lineEdit->text();
        connect(lineEdit, SIGNAL(editingFinished()),
            this, SLOT(lineEditEditingFinished()));
    } else if (PathChooser *pathChooser = qobject_cast<PathChooser *>(widget)) {
        pathChooser->setPath(m_value.toString());
        connect(pathChooser, SIGNAL(editingFinished()),
            this, SLOT(pathChooserEditingFinished()));
        connect(pathChooser, SIGNAL(browsingFinished()),
            this, SLOT(pathChooserEditingFinished()));
    } else {
        qDebug() << "Cannot connect widget " << widget << toString();
    }
}

/*
    Disconnects the \c SavedAction from a widget.

    \sa apply(), connectWidget()
*/
void SavedAction::disconnectWidget()
{
    QTC_ASSERT(m_widget,
        qDebug() << "Widget already disconnected: " << m_widget << toString(); return);
    m_widget = 0;
}
void SavedAction::apply(QSettings *s)
{
    if (QAbstractButton *button = qobject_cast<QAbstractButton *>(m_widget))
        setValue(button->isChecked());
    else if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(m_widget))
        setValue(lineEdit->text());
    else if (QSpinBox *spinBox = qobject_cast<QSpinBox *>(m_widget))
        setValue(spinBox->value());
    else if (PathChooser *pathChooser = qobject_cast<PathChooser *>(m_widget))
        setValue(pathChooser->path());
    if (s)
       writeSettings(s);
}

void SavedAction::uncheckableButtonClicked()
{
    QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
    QTC_ASSERT(button, return);
    //qDebug() << "UNCHECKABLE BUTTON: " << sender();
    QAction::trigger();
}

void SavedAction::checkableButtonClicked(bool)
{
    QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
    QTC_ASSERT(button, return);
    //qDebug() << "CHECKABLE BUTTON: " << sender();
    if (m_applyMode == ImmediateApply)
        setValue(button->isChecked());
}

void SavedAction::lineEditEditingFinished()
{
    QLineEdit *lineEdit = qobject_cast<QLineEdit *>(sender());
    QTC_ASSERT(lineEdit, return);
    if (m_applyMode == ImmediateApply)
        setValue(lineEdit->text());
}

void SavedAction::spinBoxValueChanged(int value)
{
    QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
    QTC_ASSERT(spinBox, return);
    if (m_applyMode == ImmediateApply)
        setValue(value);
}

void SavedAction::spinBoxValueChanged(QString value)
{
    QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
    QTC_ASSERT(spinBox, return);
    if (m_applyMode == ImmediateApply)
        setValue(value);
}

void SavedAction::pathChooserEditingFinished()
{
    PathChooser *pathChooser = qobject_cast<PathChooser *>(sender());
    QTC_ASSERT(pathChooser, return);
    if (m_applyMode == ImmediateApply)
        setValue(pathChooser->path());
}

void SavedAction::actionTriggered(bool)
{
    if (isCheckable())
        setValue(isChecked());
    if (actionGroup() && actionGroup()->isExclusive()) {
        // FIXME: should be taken care of more directly
        foreach (QAction *act, actionGroup()->actions())
            if (SavedAction *dact = qobject_cast<SavedAction *>(act))
                dact->setValue(bool(act == this));
    }
}

void SavedAction::trigger(const QVariant &data)
{
    setData(data);
    QAction::trigger();
}

//////////////////////////////////////////////////////////////////////////
//
// SavedActionSet
//
//////////////////////////////////////////////////////////////////////////

void SavedActionSet::insert(SavedAction *action, QWidget *widget)
{
    m_list.append(action);
    action->connectWidget(widget);
}

void SavedActionSet::apply(QSettings *settings)
{
    foreach (SavedAction *action, m_list)
        action->apply(settings);
}

void SavedActionSet::finish()
{
    foreach (SavedAction *action, m_list)
        action->disconnectWidget();
}

<commit_msg>debugger: attempty to work around old ini files containing @Invalid() entries<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include <utils/savedaction.h>

#include <utils/qtcassert.h>
#include <utils/pathchooser.h>

#include <QtCore/QDebug>
#include <QtCore/QSettings>

#include <QtGui/QAbstractButton>
#include <QtGui/QAction>
#include <QtGui/QActionGroup>
#include <QtGui/QCheckBox>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
#include <QtGui/QSpinBox>

using namespace Core::Utils;

//////////////////////////////////////////////////////////////////////////
//
// SavedAction
//
//////////////////////////////////////////////////////////////////////////

/*!
    \class Core::Utils::SavedAction

    \brief The SavedAction class is a helper class for actions with persistent
    state.

    \ingroup utils

*/

SavedAction::SavedAction(QObject *parent)
  : QAction(parent)
{
    m_widget = 0;
    connect(this, SIGNAL(triggered(bool)), this, SLOT(actionTriggered(bool)));
}

/*!
    Returns the current value of the object.

    \sa setValue()
*/
QVariant SavedAction::value() const
{
    return m_value;
}

/*!
    Sets the current value of the object. If the value changed and
    \a doemit is true, the \c valueChanged() signal will be emitted.

    \sa value()
*/
void SavedAction::setValue(const QVariant &value, bool doemit)
{
    if (value == m_value)
        return;
    m_value = value;
    if (this->isCheckable())
        this->setChecked(m_value.toBool());
    if (doemit)
        emit valueChanged(m_value);
}

/*!
    Returns the default value to be used when the item does not exist yet
    in the settings.

    \sa setDefaultValue()
*/
QVariant SavedAction::defaultValue() const
{
    return m_defaultValue;
}

/*!
    Sets the default value to be used when the item does not exist yet
    in the settings.

    \sa defaultValue()
*/
void SavedAction::setDefaultValue(const QVariant &value)
{
    m_defaultValue = value;
}

/*!
    Returns the key to be used when accessing the settings.

    \sa settingsKey()
*/
QString SavedAction::settingsKey() const
{
    return m_settingsKey;
}

/*!
    Sets the key to be used when accessing the settings.

    \sa settingsKey()
*/
void SavedAction::setSettingsKey(const QString &key)
{
    m_settingsKey = key;
}

/*!
    Sets the key and group to be used when accessing the settings.

    \sa settingsKey()
*/
void SavedAction::setSettingsKey(const QString &group, const QString &key)
{
    m_settingsKey = key;
    m_settingsGroup = group;
}

/*!
    Sets the key to be used when accessing the settings.

    \sa settingsKey()
*/
QString SavedAction::settingsGroup() const
{
    return m_settingsGroup;
}

/*!
    Sets the group to be used when accessing the settings.

    \sa settingsGroup()
*/
void SavedAction::setSettingsGroup(const QString &group)
{
    m_settingsGroup = group;
}

QString SavedAction::textPattern() const
{
    return m_textPattern;
}

void SavedAction::setTextPattern(const QString &value)
{
    m_textPattern = value;
}

QString SavedAction::toString() const
{
    return QLatin1String("value: ") + m_value.toString()
        + QLatin1String("  defaultvalue: ") + m_defaultValue.toString()
        + QLatin1String("  settingskey: ") + m_settingsGroup
        + '/' + m_settingsKey;
}

/*!
    \fn QAction *SavedAction::updatedAction(const QString &text)

    Adjust the \c text() of the underlying action.

    This can be used to update the item shortly before e.g. a menu is shown.

    If the item's \c textPattern() is empty the \a text will be used
    verbatim.

    Otherwise, the behaviour depends on \a text: if it is non-empty,
    \c QString(textPattern()).arg(text), otherwise, \c textPattern()
    with the "%1" placeholder removed will be used.

    \sa textPattern(), setTextPattern()
*/
QAction *SavedAction::updatedAction(const QString &text0)
{
    QString text = text0;
    bool enabled = true;
    if (!m_textPattern.isEmpty()) {
        if (text.isEmpty()) {
            text = m_textPattern;
            text.remove("\"%1\"");
            text.remove("%1");
            enabled = false;
        } else {
            text = m_textPattern.arg(text0);
        }
    }
    this->setEnabled(enabled);
    this->setData(text0);
    this->setText(text);
    return this;
}

/*
    Uses \c settingsGroup() and \c settingsKey() to restore the
    item from \a settings,

    \sa settingsKey(), settingsGroup(), writeSettings()
*/
void SavedAction::readSettings(QSettings *settings)
{
    if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty())
        return;
    settings->beginGroup(m_settingsGroup);
    QVariant var = settings->value(m_settingsKey, m_defaultValue);
    // work around old ini files containing @Invalid() entries
    if (isCheckable() && !var.isValid())
        var = false;
    setValue(var);
    //qDebug() << "READING: " << var.isValid() << m_settingsKey << " -> " << m_value
    //    << " (default: " << m_defaultValue << ")" << var;
    settings->endGroup();
}

/*
    Uses \c settingsGroup() and \c settingsKey() to write the
    item to \a settings,

    \sa settingsKey(), settingsGroup(), readSettings()
*/
void SavedAction::writeSettings(QSettings *settings)
{
    if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty())
        return;
    settings->beginGroup(m_settingsGroup);
    settings->setValue(m_settingsKey, m_value);
    //qDebug() << "WRITING: " << m_settingsKey << " -> " << toString();
    settings->endGroup();
}

/*
    A \c SavedAction can be connected to a widget, typically a
    checkbox, radiobutton, or a lineedit in some configuration dialog.

    The widget will retrieve its contents from the SavedAction's
    value, and - depending on the \a ApplyMode - either write
    changes back immediately, or when \s SavedAction::apply()
    is called explicitly.

    \sa apply(), disconnectWidget()
*/
void SavedAction::connectWidget(QWidget *widget, ApplyMode applyMode)
{
    QTC_ASSERT(!m_widget,
        qDebug() << "ALREADY CONNECTED: " << widget << m_widget << toString(); return);
    m_widget = widget;
    m_applyMode = applyMode;

    if (QAbstractButton *button = qobject_cast<QAbstractButton *>(widget)) {
        if (button->isCheckable()) {
            button->setChecked(m_value.toBool());
            connect(button, SIGNAL(clicked(bool)),
                this, SLOT(checkableButtonClicked(bool)));
        } else {
            connect(button, SIGNAL(clicked()),
                this, SLOT(uncheckableButtonClicked()));
        }
    } else if (QSpinBox *spinBox = qobject_cast<QSpinBox *>(widget)) {
        spinBox->setValue(m_value.toInt());
        //qDebug() << "SETTING VALUE" << spinBox->value();
        connect(spinBox, SIGNAL(valueChanged(int)),
            this, SLOT(spinBoxValueChanged(int)));
        connect(spinBox, SIGNAL(valueChanged(QString)),
            this, SLOT(spinBoxValueChanged(QString)));
    } else if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) {
        lineEdit->setText(m_value.toString());
        //qDebug() << "SETTING TEXT" << lineEdit->text();
        connect(lineEdit, SIGNAL(editingFinished()),
            this, SLOT(lineEditEditingFinished()));
    } else if (PathChooser *pathChooser = qobject_cast<PathChooser *>(widget)) {
        pathChooser->setPath(m_value.toString());
        connect(pathChooser, SIGNAL(editingFinished()),
            this, SLOT(pathChooserEditingFinished()));
        connect(pathChooser, SIGNAL(browsingFinished()),
            this, SLOT(pathChooserEditingFinished()));
    } else {
        qDebug() << "Cannot connect widget " << widget << toString();
    }
}

/*
    Disconnects the \c SavedAction from a widget.

    \sa apply(), connectWidget()
*/
void SavedAction::disconnectWidget()
{
    QTC_ASSERT(m_widget,
        qDebug() << "Widget already disconnected: " << m_widget << toString(); return);
    m_widget = 0;
}
void SavedAction::apply(QSettings *s)
{
    if (QAbstractButton *button = qobject_cast<QAbstractButton *>(m_widget))
        setValue(button->isChecked());
    else if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(m_widget))
        setValue(lineEdit->text());
    else if (QSpinBox *spinBox = qobject_cast<QSpinBox *>(m_widget))
        setValue(spinBox->value());
    else if (PathChooser *pathChooser = qobject_cast<PathChooser *>(m_widget))
        setValue(pathChooser->path());
    if (s)
       writeSettings(s);
}

void SavedAction::uncheckableButtonClicked()
{
    QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
    QTC_ASSERT(button, return);
    //qDebug() << "UNCHECKABLE BUTTON: " << sender();
    QAction::trigger();
}

void SavedAction::checkableButtonClicked(bool)
{
    QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
    QTC_ASSERT(button, return);
    //qDebug() << "CHECKABLE BUTTON: " << sender();
    if (m_applyMode == ImmediateApply)
        setValue(button->isChecked());
}

void SavedAction::lineEditEditingFinished()
{
    QLineEdit *lineEdit = qobject_cast<QLineEdit *>(sender());
    QTC_ASSERT(lineEdit, return);
    if (m_applyMode == ImmediateApply)
        setValue(lineEdit->text());
}

void SavedAction::spinBoxValueChanged(int value)
{
    QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
    QTC_ASSERT(spinBox, return);
    if (m_applyMode == ImmediateApply)
        setValue(value);
}

void SavedAction::spinBoxValueChanged(QString value)
{
    QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
    QTC_ASSERT(spinBox, return);
    if (m_applyMode == ImmediateApply)
        setValue(value);
}

void SavedAction::pathChooserEditingFinished()
{
    PathChooser *pathChooser = qobject_cast<PathChooser *>(sender());
    QTC_ASSERT(pathChooser, return);
    if (m_applyMode == ImmediateApply)
        setValue(pathChooser->path());
}

void SavedAction::actionTriggered(bool)
{
    if (isCheckable())
        setValue(isChecked());
    if (actionGroup() && actionGroup()->isExclusive()) {
        // FIXME: should be taken care of more directly
        foreach (QAction *act, actionGroup()->actions())
            if (SavedAction *dact = qobject_cast<SavedAction *>(act))
                dact->setValue(bool(act == this));
    }
}

void SavedAction::trigger(const QVariant &data)
{
    setData(data);
    QAction::trigger();
}

//////////////////////////////////////////////////////////////////////////
//
// SavedActionSet
//
//////////////////////////////////////////////////////////////////////////

void SavedActionSet::insert(SavedAction *action, QWidget *widget)
{
    m_list.append(action);
    action->connectWidget(widget);
}

void SavedActionSet::apply(QSettings *settings)
{
    foreach (SavedAction *action, m_list)
        action->apply(settings);
}

void SavedActionSet::finish()
{
    foreach (SavedAction *action, m_list)
        action->disconnectWidget();
}

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <fnord-base/exception.h>
#include <fnord-base/inspect.h>
#include <fnord-base/stringutil.h>
#include <fnord-base/uri.h>
#include "common.h"
#include "logjoin/TrackedCartItem.h"

namespace cm {

Vector<TrackedCartItem> TrackedCartItem::fromParams(
  const fnord::URI::ParamList& params) {
  Vector<TrackedCartItem> items;

  std::string step_str;
  if (!fnord::URI::getParam(params, "s", &step_str)) {
    RAISE(kParseError, "missing s param");
  }

  auto checkout_step = std::stoul(step_str);

  std::string items_str;
  if (fnord::URI::getParam(params, "is", &items_str)) {
    for (const auto& item_str : fnord::StringUtil::split(items_str, ",")) {
      if (item_str.length() == 0) {
        continue;
      }

      auto item_str_parts = fnord::StringUtil::split(item_str, "~");
      if (item_str_parts.size() != 5) {
        RAISE(kParseError, "invalid is param");
      }

      TrackedCartItem citem;
      citem.item.set_id = item_str_parts[0];
      citem.item.item_id = item_str_parts[1];
      citem.quantity = std::stoul(item_str_parts[2]);
      citem.price_cents = std::stoul(item_str_parts[3]);
      citem.currency = item_str_parts[4];
      citem.checkout_step = checkout_step;

      items.emplace_back(citem);
    }
  }

  return items;
}

}

<commit_msg>TrackedCartItem::merge<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <fnord-base/exception.h>
#include <fnord-base/inspect.h>
#include <fnord-base/stringutil.h>
#include <fnord-base/uri.h>
#include "common.h"
#include "logjoin/TrackedCartItem.h"

namespace cm {

Vector<TrackedCartItem> TrackedCartItem::fromParams(
  const fnord::URI::ParamList& params) {
  Vector<TrackedCartItem> items;

  std::string step_str;
  if (!fnord::URI::getParam(params, "s", &step_str)) {
    RAISE(kParseError, "missing s param");
  }

  auto checkout_step = std::stoul(step_str);

  std::string items_str;
  if (fnord::URI::getParam(params, "is", &items_str)) {
    for (const auto& item_str : fnord::StringUtil::split(items_str, ",")) {
      if (item_str.length() == 0) {
        continue;
      }

      auto item_str_parts = fnord::StringUtil::split(item_str, "~");
      if (item_str_parts.size() != 5) {
        RAISE(kParseError, "invalid is param");
      }

      TrackedCartItem citem;
      citem.item.set_id = item_str_parts[0];
      citem.item.item_id = item_str_parts[1];
      citem.quantity = std::stoul(item_str_parts[2]);
      citem.price_cents = std::stoul(item_str_parts[3]);
      citem.currency = item_str_parts[4];
      citem.checkout_step = checkout_step;

      items.emplace_back(citem);
    }
  }

  return items;
}

void TrackedCartItem::merge(const TrackedCartItem& other) {
  if (other.time > time) {
    quantity = other.quantity;
  }

  if ((other.checkout_step > 0 && other.checkout_step < checkout_step) ||
      checkout_step == 0) {
    checkout_step = other.checkout_step;
  }
}

}

<|endoftext|>


<commit_before>/*
 * Copyright 2016 Krysta M Bouzek
 *
 * 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 <iostream>
#include <cstdlib>
#include <map>
#include "rabit/c_api.h"
#include "xgboost/c_api.h"

// these links were eminently helpful:
// http://stackoverflow.com/questions/36071672/using-xgboost-in-c
// https://stackoverflow.com/questions/38314092/reading-xgboost-model-in-c

class XGBoostWrapper {
    public:
        XGBoostWrapper(unsigned int num_trees, std::map<std::string, std::string> booster_params);
        ~XGBoostWrapper();
        // xgboost expects a flat array
        void fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols);
        void predict(const float Xs[], const float** YHats, unsigned int rows, unsigned int cols);
    private:
        BoosterHandle _h_booster;
        // number of boosting rounds
        unsigned int _num_trees;
        std::map<std::string, std::string> _booster_params;
};

// Create an XGBoost handle
XGBoostWrapper::XGBoostWrapper(unsigned int num_trees, std::map<std::string, std::string> booster_params) {
    _h_booster = new BoosterHandle();
    _num_trees = num_trees;
    _booster_params = booster_params;
}

// Delete the XGBoost handle
XGBoostWrapper::~XGBoostWrapper() {
    if (_h_booster) {
        XGBoosterFree(_h_booster);
    }
}

void XGBoostWrapper::fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols) {
    // convert to DMatrix
    DMatrixHandle h_train[1];
    XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_train[0]);

    // load the labels
    XGDMatrixSetFloatInfo(h_train[0], "label", Ys, rows);

    // read back the labels, just a sanity check
    /*bst_ulong bst_result;
    const float *out_floats;
    XGDMatrixGetFloatInfo(h_train[0], "label" , &bst_result, &out_floats);
    for (unsigned int i=0;i<bst_result;i++)
        std::cout << "label[" << i << "]=" << out_floats[i] << std::endl;
    */

    // create the booster and load some parameters
    XGBoosterCreate(h_train, 1, &_h_booster);

    std::map<std::string, std::string>::iterator it;
    for (it = _booster_params.begin(); it != _booster_params.end(); ++it) {
        std::cout << it->first << ", " << it->second << '\n';
        XGBoosterSetParam(_h_booster, it->first.c_str(), it->second.c_str());
    }

    // perform 200 learning iterations
    for (unsigned int iter = 0; iter < _num_trees; iter++) {
        XGBoosterUpdateOneIter(_h_booster, iter, h_train[0]);
    }

    // free xgboost internal structures
    XGDMatrixFree(h_train[0]);
}

void XGBoostWrapper::predict(const float Xs[], const float** Yhats, unsigned int rows, unsigned int cols) {
    DMatrixHandle h_test;
    XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_test);
    bst_ulong out_len;
    XGBoosterPredict(_h_booster, h_test, 0, 0, &out_len, Yhats);

    // free xgboost internal structures
    XGDMatrixFree(h_test);
}

int main() {
    // create the train data
    const unsigned int cols = 3;
    const unsigned int rows = 5;

    float Xs[rows * cols];
    for(unsigned int i = 0; i < rows; ++i)
    {
        for(unsigned int j = 0; j < cols; ++j)
        {
            Xs[i * cols + j] = (i + 1) * (j + 1);
        }
    }

    float Ys[rows];

    for (unsigned int i = 0; i < rows; i++) {
        Ys[i] = 1 + i * i * i;
    }

    std::map<std::string, std::string> booster_params;
    booster_params["booster"] = "gbtree";
    booster_params["objective"] = "reg:linear";
    booster_params["max_depth"] = "5";
    booster_params["eta"] = "0.1";
    booster_params["min_child_weight"] = "1";
    booster_params["subsample"] = "0.5";
    booster_params["colsample_bytree"] = "1";
    booster_params["num_parallel_tree"] = "1";

    XGBoostWrapper fitter(200, booster_params);
    fitter.fit(Xs, Ys, rows, cols);

    const unsigned int sample_rows = 5;
    float test[sample_rows * cols];
    for (unsigned int i = 0;i < sample_rows; i++) {
        for (unsigned int j = 0;j < cols; j++) {
            test[i * cols + j] = (i + 1) * (j + 1);
        }
    }

    const float* Yhats; //[sample_rows];
    fitter.predict(test, &Yhats, sample_rows, cols);

    for (unsigned int i = 0;i < sample_rows; i++) {
        std::cout << "prediction[" << i << "]=" << Yhats[i] << std::endl;
    }

    free((void *)Yhats);

    return 0;
}
<commit_msg>Comment cleanup<commit_after>/*
 * Copyright 2016 Krysta M Bouzek
 *
 * 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 <iostream>
#include <cstdlib>
#include <map>
#include "rabit/c_api.h"
#include "xgboost/c_api.h"

// these links were eminently helpful:
// http://stackoverflow.com/questions/36071672/using-xgboost-in-c
// https://stackoverflow.com/questions/38314092/reading-xgboost-model-in-c

class XGBoostWrapper {
    public:
        XGBoostWrapper(unsigned int num_trees, std::map<std::string, std::string> booster_params);
        ~XGBoostWrapper();
        // xgboost expects a flat array
        void fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols);
        void predict(const float Xs[], const float** YHats, unsigned int rows, unsigned int cols);
    private:
        BoosterHandle _h_booster;
        // number of boosting rounds
        unsigned int _num_trees;
        std::map<std::string, std::string> _booster_params;
};

// Create an XGBoost handle
XGBoostWrapper::XGBoostWrapper(unsigned int num_trees, std::map<std::string, std::string> booster_params) {
    _h_booster = new BoosterHandle();
    _num_trees = num_trees;
    _booster_params = booster_params;
}

// Delete the XGBoost handle
XGBoostWrapper::~XGBoostWrapper() {
    if (_h_booster) {
        XGBoosterFree(_h_booster);
    }
}

void XGBoostWrapper::fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols) {
    // convert to DMatrix
    DMatrixHandle h_train[1];
    XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_train[0]);

    // load the labels
    XGDMatrixSetFloatInfo(h_train[0], "label", Ys, rows);

    // read back the labels, just a sanity check
    /*bst_ulong bst_result;
    const float *out_floats;
    XGDMatrixGetFloatInfo(h_train[0], "label" , &bst_result, &out_floats);
    for (unsigned int i=0;i<bst_result;i++)
        std::cout << "label[" << i << "]=" << out_floats[i] << std::endl;
    */

    // create the booster and load some parameters
    XGBoosterCreate(h_train, 1, &_h_booster);

    std::map<std::string, std::string>::iterator it;
    for (it = _booster_params.begin(); it != _booster_params.end(); ++it) {
        std::cout << it->first << ", " << it->second << '\n';
        XGBoosterSetParam(_h_booster, it->first.c_str(), it->second.c_str());
    }

    for (unsigned int iter = 0; iter < _num_trees; iter++) {
        XGBoosterUpdateOneIter(_h_booster, iter, h_train[0]);
    }

    // free xgboost internal structures
    XGDMatrixFree(h_train[0]);
}

void XGBoostWrapper::predict(const float Xs[], const float** Yhats, unsigned int rows, unsigned int cols) {
    DMatrixHandle h_test;
    XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_test);
    bst_ulong out_len;
    XGBoosterPredict(_h_booster, h_test, 0, 0, &out_len, Yhats);

    // free xgboost internal structures
    XGDMatrixFree(h_test);
}

int main() {
    const unsigned int cols = 3;
    const unsigned int rows = 5;

    float Xs[rows * cols];
    for(unsigned int i = 0; i < rows; ++i)
    {
        for(unsigned int j = 0; j < cols; ++j)
        {
            Xs[i * cols + j] = (i + 1) * (j + 1);
        }
    }

    float Ys[rows];

    for (unsigned int i = 0; i < rows; i++) {
        Ys[i] = 1 + i * i * i;
    }

    std::map<std::string, std::string> booster_params;
    booster_params["booster"] = "gbtree";
    booster_params["objective"] = "reg:linear";
    booster_params["max_depth"] = "5";
    booster_params["eta"] = "0.1";
    booster_params["min_child_weight"] = "1";
    booster_params["subsample"] = "0.5";
    booster_params["colsample_bytree"] = "1";
    booster_params["num_parallel_tree"] = "1";

    XGBoostWrapper fitter(200, booster_params);
    fitter.fit(Xs, Ys, rows, cols);

    const unsigned int sample_rows = 5;
    float test[sample_rows * cols];
    for (unsigned int i = 0;i < sample_rows; i++) {
        for (unsigned int j = 0;j < cols; j++) {
            test[i * cols + j] = (i + 1) * (j + 1);
        }
    }

    const float* Yhats; //[sample_rows];
    fitter.predict(test, &Yhats, sample_rows, cols);

    for (unsigned int i = 0;i < sample_rows; i++) {
        std::cout << "prediction[" << i << "]=" << Yhats[i] << std::endl;
    }

    free((void *)Yhats);

    return 0;
}
<|endoftext|>


<commit_before>/*
MIT License

Copyright (c) 2019 Bart Bilos

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <onofffsm.hpp>
#include <board.hpp>
#include <stream_uart.hpp>

typedef enum {
    powerOn,
    shuttingDown,
} onoffFsmStates_t;

typedef enum {

} onoffFsmEvent_t;

static onoffFsmStates_t onoffFsmState = powerOn;

void onoffFsmHandlePowerOn(onoffFsmEvent_t event)
{

}

void onoffFsmHandleShuttingDown(onoffFsmEvent_t event)
{

}

void onoffFsmHandleEvent(onoffFsmEvent_t event)
{
    switch(onoffFsmState)
    {
        case powerOn:
            onoffFsmHandlePowerOn(event);
        break;
        case shuttingDown:
            onoffFsmHandleShuttingDown(event);
        break;
        default:
        // todo assert
        break;
    }
}

void onoffFsmRun(void)
{
    static bool prevButtonState = true;
    if(checkButtonState() != prevButtonState)
    {
        prevButtonState = checkButtonState();
        if(prevButtonState)
        {
            dsPuts(&streamUart, "Button True\n");
        }
        else
        {
            dsPuts(&streamUart, "Button False\n");
        }
    }
}
<commit_msg>added events for button presses<commit_after>/*
MIT License

Copyright (c) 2019 Bart Bilos

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <onofffsm.hpp>
#include <board.hpp>
#include <stream_uart.hpp>
#include <print.h>
#include <strings.hpp>

typedef enum {
    powerOn,
    shuttingDown,
} onoffFsmStates_t;

typedef enum {
    buttonDepress,
    buttonPress,
} onoffFsmEvent_t;

static onoffFsmStates_t onoffFsmState = powerOn;

void onoffFsmSwitchState(onoffFsmStates_t state)
{
    dsPuts(&streamUart, "state");
    printDecNzU16(&streamUart, (uint16_t) state);
    dsPuts(&streamUart, strCrLf);
    onoffFsmState = state;
}

void onoffFsmHandlePowerOn(onoffFsmEvent_t event)
{
    switch(event)
    {
        case buttonPress:
            onoffFsmSwitchState(shuttingDown);
        break;
        case buttonDepress:
        break;
        default:
            // todo assert
        break;
    }

}

void onoffFsmHandleShuttingDown(onoffFsmEvent_t event)
{
        switch(event)
    {
        case buttonPress:
        break;
        case buttonDepress:
            onoffFsmSwitchState(powerOn);
        break;
        default:
            // todo assert
        break;
    }
}

void onoffFsmHandleEvent(onoffFsmEvent_t event)
{
    switch(onoffFsmState)
    {
        case powerOn:
            onoffFsmHandlePowerOn(event);
        break;
        case shuttingDown:
            onoffFsmHandleShuttingDown(event);
        break;
        default:
        // todo assert
        break;
    }
}

void onoffFsmRun(void)
{
    static bool prevButtonState = true;
    if(checkButtonState() != prevButtonState)
    {
        prevButtonState = checkButtonState();
        if(prevButtonState)
        {
            onoffFsmHandleEvent(buttonDepress);
        }
        else
        {
            onoffFsmHandleEvent(buttonPress);
        }
    }
}
<|endoftext|>


<commit_before>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h"

namespace tudat
{

namespace propagators
{

//! Function to check whether the propagation is to be be stopped
bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    bool stopPropagation = 0;

    // Check whether stop time has been reached
    if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    return cpuTime >= cpuStopTime_;
}

//! Function to check whether the propagation is to be be stopped
bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime  )
{
    bool stopPropagation = 0;
    double currentVariable = variableRetrievalFuntion_( );
    if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    // Check if single condition is fulfilled.
    bool stopPropagation = -1;
    if( fulFillSingleCondition_ )
    {
        stopPropagation = 0;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 1;
                break;
            }
        }
        return stopPropagation;
    }
    // Check all conditions are fulfilled.
    else
    {
        stopPropagation = 1;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 0;
                break;
            }
        }
    }

    // Save if conditions were met
    if( stopPropagation )
    {
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                isConditionMetWhenStopping_[ i ] = false;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = true;
            }
        }
    }

    return stopPropagation;

}

//! Function to create propagation termination conditions from associated settings
boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions(
        const boost::shared_ptr< PropagationTerminationSettings > terminationSettings,
        const simulation_setup::NamedBodyMap& bodyMap,
        const double initialTimeStep )
{
    boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition;

    // Check termination type.
    switch( terminationSettings->terminationType_ )
    {
    case time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >(
                    timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ),
                    timeTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case cpu_time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >(
                    cpuTimeTerminationSettings->cpuTerminationTime_ );
        break;
    }
    case dependent_variable_stopping_condition:
    {
        boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings =
                boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings );

        // Get dependent variable function
        boost::function< double( ) > dependentVariableFunction;
        if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 )
        {
            dependentVariableFunction =
                    getDoubleDependentVariableFunction(
                        dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap );
        }
        else
        {
            throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" );
        }

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >(
                    dependentVariableTerminationSettings->dependentVariableSettings_,
                    dependentVariableFunction, dependentVariableTerminationSettings->limitValue_,
                    dependentVariableTerminationSettings->useAsLowerLimit_,
                    dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_,
                    dependentVariableTerminationSettings->terminationRootFinderSettings_ );
        break;
    }
    case hybrid_stopping_condition:
    {
        boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings =
                boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings );

        // Recursively create termination condition list.
        std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList;
        for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ )
        {
            propagationTerminationConditionList.push_back(
                        createPropagationTerminationConditions(
                            hybridTerminationSettings->terminationSettings_.at( i ),
                            bodyMap, initialTimeStep ) );
        }
        propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >(
                    propagationTerminationConditionList, hybridTerminationSettings->fulFillSingleCondition_,
                    hybridTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    default:
        std::string errorMessage = "Error, stopping condition type " + std::to_string(
                    terminationSettings->terminationType_ ) + "not recognized when making stopping conditions object";
        throw std::runtime_error( errorMessage );
        break;
    }
    return propagationTerminationCondition;

} // namespace propagators

} // namespace tudat

}
<commit_msg>Fixed another small bug in accurate termination<commit_after>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h"

namespace tudat
{

namespace propagators
{

//! Function to check whether the propagation is to be be stopped
bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    bool stopPropagation = 0;

    // Check whether stop time has been reached
    if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    return cpuTime >= cpuStopTime_;
}

//! Function to check whether the propagation is to be be stopped
bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime  )
{
    bool stopPropagation = 0;
    double currentVariable = variableRetrievalFuntion_( );
    if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    // Check if single condition is fulfilled.
    bool stopPropagation = -1;
    if( fulFillSingleCondition_ )
    {
        stopPropagation = 0;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 1;
                break;
            }
        }
    }
    // Check all conditions are fulfilled.
    else
    {
        stopPropagation = 1;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 0;
                break;
            }
        }
    }

    // Save if conditions were met
    if( stopPropagation )
    {
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                isConditionMetWhenStopping_[ i ] = false;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = true;
            }
        }
    }

    return stopPropagation;

}

//! Function to create propagation termination conditions from associated settings
boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions(
        const boost::shared_ptr< PropagationTerminationSettings > terminationSettings,
        const simulation_setup::NamedBodyMap& bodyMap,
        const double initialTimeStep )
{
    boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition;

    // Check termination type.
    switch( terminationSettings->terminationType_ )
    {
    case time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >(
                    timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ),
                    timeTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case cpu_time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >(
                    cpuTimeTerminationSettings->cpuTerminationTime_ );
        break;
    }
    case dependent_variable_stopping_condition:
    {
        boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings =
                boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings );

        // Get dependent variable function
        boost::function< double( ) > dependentVariableFunction;
        if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 )
        {
            dependentVariableFunction =
                    getDoubleDependentVariableFunction(
                        dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap );
        }
        else
        {
            throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" );
        }

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >(
                    dependentVariableTerminationSettings->dependentVariableSettings_,
                    dependentVariableFunction, dependentVariableTerminationSettings->limitValue_,
                    dependentVariableTerminationSettings->useAsLowerLimit_,
                    dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_,
                    dependentVariableTerminationSettings->terminationRootFinderSettings_ );
        break;
    }
    case hybrid_stopping_condition:
    {
        boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings =
                boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings );

        // Recursively create termination condition list.
        std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList;
        for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ )
        {
            propagationTerminationConditionList.push_back(
                        createPropagationTerminationConditions(
                            hybridTerminationSettings->terminationSettings_.at( i ),
                            bodyMap, initialTimeStep ) );
        }
        propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >(
                    propagationTerminationConditionList, hybridTerminationSettings->fulFillSingleCondition_,
                    hybridTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    default:
        std::string errorMessage = "Error, stopping condition type " + std::to_string(
                    terminationSettings->terminationType_ ) + "not recognized when making stopping conditions object";
        throw std::runtime_error( errorMessage );
        break;
    }
    return propagationTerminationCondition;

} // namespace propagators

} // namespace tudat

}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

#include "RadixSort.hpp"
#include "Timing.hpp"

// #define DEBUG

#ifdef DEBUG
	#include <algorithm>
#endif

typedef int types;
int main (int argc, char *argv[]) {
    const int size = atoi(argv[1]);
    srand(time(NULL));

	std::vector<types> array(size);

	if (sizeof(types) == 1)
		for (int i=0;i<size;i++) {
			uint8_t *temp = (uint8_t *) &array[i];
			*temp = (((double) rand() / (RAND_MAX - 1)) * 0x0f);
			if (rand() % 2) *temp |= 0x80;
		}
	else if (sizeof(types) == 2)
		for (int i=0;i<size;i++) {
			uint16_t *temp = (uint16_t *) &array[i];
			*temp = (((double) rand() / (RAND_MAX - 1)) * 0x0fff);
			if (rand() % 2) *temp |= 0x8000;
		}
	else if (sizeof(types) == 4)
		for (int i=0;i<size;i++) {
			uint32_t *temp = (uint32_t *) &array[i];
			*temp = (((double) rand() / (RAND_MAX - 1)) * 0x0fffffff);
			if (rand() % 2) *temp |= 0x80000000;
		}
	else if (sizeof(types) == 8)
		for (int i=0;i<size;i++) {
			uint64_t *temp = (uint64_t *) &array[i];
			*temp = (((double) rand() / (RAND_MAX - 1)) * 0x0fffffffffffffff);
			if (rand() % 2) *temp |= 0x8000000000000000;
		}

#ifdef DEBUG
	std::vector<types> compare(array);
	std::sort(&compare[0], &compare[0] + size);
#endif

	scottgs::Timing timer;
	timer.start();
	RadixSort::sort(&array[0], size);
	timer.stop();

#ifndef DEBUG
    bool sorted = true;
    for (int i=1;i<size;i++)
        if (array[i] < array[i-1]) {
            sorted = false;
            break;
        }
    if (sorted) std::cout << "Array successfully sorted " << size << " elements in " << timer.getTotalElapsedTime() << " seconds.";
    else std::cout << "Error, unsuccessful at sorting array!";
	std::cout << std::endl;
#else
	for (int i=0;i<size;i++)
		if (array[i] != compare[i])
			std::cout << i << ": " << array[i] << ' ' << compare[i] << std::endl;
#endif
    return 0;
}
<commit_msg>not needed anymore<commit_after><|endoftext|>