<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://qt.nokia.com/contact.
**
**************************************************************************/

#include "qt4projectconfigwidget.h"

#include "makestep.h"
#include "qmakestep.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanager.h"
#include "qt4buildconfiguration.h"
#include "ui_qt4projectconfigwidget.h"

#include <coreplugin/icore.h>
#include <coreplugin/mainwindow.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/buildconfiguration.h>
#include <utils/qtcassert.h>
#include <extensionsystem/pluginmanager.h>

#include <QtGui/QFileDialog>

namespace {
bool debug = false;
}

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using ProjectExplorer::ToolChain;

Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(Qt4Project *project)
    : BuildConfigWidget(),
      m_buildConfiguration(0),
      m_ignoreChange(false)
{
    Q_UNUSED(project);
    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setMargin(0);
    m_detailsContainer = new Utils::DetailsWidget(this);
    m_detailsContainer->setState(Utils::DetailsWidget::NoSummary);
    vbox->addWidget(m_detailsContainer);
    QWidget *details = new QWidget(m_detailsContainer);
    m_detailsContainer->setWidget(details);
    m_ui = new Ui::Qt4ProjectConfigWidget();
    m_ui->setupUi(details);

    m_browseButton = m_ui->shadowBuildDirEdit->buttonAtIndex(0);
    // TODO refix the layout

    m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr("Shadow Build Directory"));
    m_ui->shadowBuildDirEdit->setExpectedKind(Utils::PathChooser::Directory);
    m_ui->invalidQtWarningLabel->setVisible(false);

    connect(m_ui->nameLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(configNameEdited(QString)));

    connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),
            this, SLOT(shadowBuildClicked(bool)));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),
            this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(changed(QString)),
            this, SLOT(shadowBuildEdited()));

    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(qtVersionSelected(QString)));

    connect(m_ui->toolChainComboBox, SIGNAL(activated(int)),
            this, SLOT(toolChainSelected(int)));

    connect(m_ui->importLabel, SIGNAL(linkActivated(QString)),
            this, SLOT(importLabelClicked()));

    connect(m_ui->manageQtVersionPushButtons, SIGNAL(clicked()),
            this, SLOT(manageQtVersions()));

    QtVersionManager *vm = QtVersionManager::instance();
    connect(vm, SIGNAL(qtVersionsChanged(QList<int>)),
            this, SLOT(qtVersionsChanged()));
}

Qt4ProjectConfigWidget::~Qt4ProjectConfigWidget()
{
    delete m_ui;
}

void Qt4ProjectConfigWidget::updateDetails()
{
    QtVersion *version = m_buildConfiguration->qtVersion();

    QString versionString;
    versionString = version->displayName();

    if (!version || !version->isValid()) {
        // Not a valid qt version
        m_detailsContainer->setSummaryText(
                tr("using invalid Qt Version: %1
"
                   "%2")
                .arg(versionString,
                     version ? version->invalidReason() : tr("No Qt Version found.")));
    } else {
        // Qt Version, Build Directory and Toolchain
        m_detailsContainer->setSummaryText(
                tr("using Qt version: %1
"
                   "with tool chain %2
"
                   "building in %3")
                .arg(versionString,
                     ProjectExplorer::ToolChain::toolChainName(m_buildConfiguration->toolChainType()),
                     QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));
    }
}

void Qt4ProjectConfigWidget::manageQtVersions()
{
    Core::ICore *core = Core::ICore::instance();
    core->showOptionsDialog(Constants::QT_SETTINGS_CATEGORY, Constants::QTVERSION_SETTINGS_PAGE_ID);
}

QString Qt4ProjectConfigWidget::displayName() const
{
    return tr("General");
}

void Qt4ProjectConfigWidget::init(ProjectExplorer::BuildConfiguration *bc)
{
    QTC_ASSERT(bc, return);

    if (debug)
        qDebug() << "Qt4ProjectConfigWidget::init() for"<<bc->displayName();

    if (m_buildConfiguration) {
        disconnect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
                   this, SLOT(buildDirectoryChanged()));
        disconnect(m_buildConfiguration, SIGNAL(qtVersionChanged()),
                   this, SLOT(qtVersionChanged()));
        disconnect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
                   this, SLOT(updateImportLabel()));
    }
    m_buildConfiguration = static_cast<Qt4BuildConfiguration *>(bc);

    connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
            this, SLOT(buildDirectoryChanged()));
    connect(m_buildConfiguration, SIGNAL(qtVersionChanged()),
            this, SLOT(qtVersionChanged()));
    connect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
            this, SLOT(updateImportLabel()));

    m_ui->nameLineEdit->setText(m_buildConfiguration->displayName());

    qtVersionsChanged();

    bool shadowBuild = m_buildConfiguration->shadowBuild();
    m_ui->shadowBuildCheckBox->setChecked(shadowBuild);
    m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);
    m_browseButton->setEnabled(shadowBuild);
    m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->buildDirectory());
    updateImportLabel();
    updateToolChainCombo();
    updateDetails();
}

void Qt4ProjectConfigWidget::qtVersionChanged()
{
    updateImportLabel();
    updateToolChainCombo();
    updateDetails();
}

void Qt4ProjectConfigWidget::configNameEdited(const QString &newName)
{
    m_buildConfiguration->setDisplayName(newName);
}

void Qt4ProjectConfigWidget::qtVersionsChanged()
{
    if (!m_buildConfiguration) // not yet initialized
        return;

    disconnect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionSelected(QString)));

    QtVersionManager *vm = QtVersionManager::instance();

    m_ui->qtVersionComboBox->clear();
    QtVersion * qtVersion = m_buildConfiguration->qtVersion();

    const QList<QtVersion *> validVersions(vm->versionsForTargetId(m_buildConfiguration->target()->id()));
    if (validVersions.isEmpty()) {
        m_ui->invalidQtWarningLabel->setVisible(true);
    } else {
        m_ui->invalidQtWarningLabel->setVisible(false);
        for (int i = 0; i < validVersions.size(); ++i) {
            m_ui->qtVersionComboBox->addItem(validVersions.at(i)->displayName(),
                                             validVersions.at(i)->uniqueId());

            if (validVersions.at(i) == qtVersion) {
                m_ui->qtVersionComboBox->setCurrentIndex(i);
                m_ui->invalidQtWarningLabel->setVisible(!validVersions.at(i)->isValid());
            }
        }
        m_ui->qtVersionComboBox->setEnabled(validVersions.count() > 1);
    }

    // And connect again
    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionSelected(QString)));
}

void Qt4ProjectConfigWidget::buildDirectoryChanged()
{
    if (m_ignoreChange)
        return;
    m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->shadowBuildDirectory());
    updateDetails();
    updateImportLabel();
}

void Qt4ProjectConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()
{
    QString initialDirectory = QFileInfo(m_buildConfiguration->target()->project()->file()->fileName()).absolutePath();
    if (!initialDirectory.isEmpty())
        m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);
}

void Qt4ProjectConfigWidget::shadowBuildClicked(bool checked)
{
    m_ui->shadowBuildDirEdit->setEnabled(checked);
    m_browseButton->setEnabled(checked);
    bool b = m_ui->shadowBuildCheckBox->isChecked();

    m_ignoreChange = true;
    m_buildConfiguration->setShadowBuildAndDirectory(b, m_ui->shadowBuildDirEdit->path());
    m_ignoreChange = false;

    updateDetails();
    updateImportLabel();
}

void Qt4ProjectConfigWidget::shadowBuildEdited()
{
    if (m_buildConfiguration->shadowBuildDirectory() == m_ui->shadowBuildDirEdit->path())
        return;
    m_ignoreChange = true;
    m_buildConfiguration->setShadowBuildAndDirectory(true, m_ui->shadowBuildDirEdit->path());
    m_ignoreChange = false;

    // if the directory already exists
    // check if we have a build in there and
    // offer to import it
    updateImportLabel();
    updateDetails();
}

void Qt4ProjectConfigWidget::updateImportLabel()
{
    bool visible = false;
    bool targetMatches = false;

    QtVersionManager *vm = QtVersionManager::instance();
    // we only show if we actually have a qmake and makestep
    if (m_buildConfiguration->qmakeStep() && m_buildConfiguration->makeStep()) {
        QString qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(m_buildConfiguration->buildDirectory());
        QtVersion *version = m_buildConfiguration->qtVersion();
        // check that there's a makefile
        if (!qmakePath.isEmpty()) {
            // and that the qmake path is different from the current version
            if (qmakePath != (version ? version->qmakeCommand() : QString())) {
                // import enable
                visible = true;
                QtVersion *newVersion = vm->qtVersionForQMakeBinary(qmakePath);
                bool mustDelete(false);
                if (!newVersion) {
                    newVersion = new QtVersion(qmakePath);
                    mustDelete = true;
                }
                targetMatches = newVersion->supportsTargetId(m_buildConfiguration->target()->id());
                if (mustDelete)
                    delete newVersion;
            } else {
                // check that the qmake flags, arguments match
                visible = !m_buildConfiguration->compareToImportFrom(m_buildConfiguration->buildDirectory());
            }
        } else {
            visible = false;
        }
    }

    if (targetMatches) {
        m_ui->importProblemLabel->setVisible(false);
        m_ui->importWarningLabel->setVisible(false);
        m_ui->importLabel->setVisible(visible);
    } else {
        m_ui->importWarningLabel->setVisible(visible);
        m_ui->importProblemLabel->setVisible(visible);
        m_ui->importProblemLabel->setText(tr("A incompatible build exists in %1 and will be overwritten!",
                                             "%1 build directory").
                                          arg(m_ui->shadowBuildDirEdit->path()));
        m_ui->importLabel->setVisible(false);
    }
}

void Qt4ProjectConfigWidget::importLabelClicked()
{
    if (!m_buildConfiguration->qmakeStep() || !m_buildConfiguration->makeStep())
        return;
    QString directory = m_buildConfiguration->buildDirectory();
    if (!directory.isEmpty()) {
        QString qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(directory);
        if (!qmakePath.isEmpty()) {
            QtVersionManager *vm = QtVersionManager::instance();
            QtVersion *version = vm->qtVersionForQMakeBinary(qmakePath);
            if (!version) {
                version = new QtVersion(qmakePath);
                vm->addVersion(version);
            }

            QPair<QtVersion::QmakeBuildConfigs, QStringList> result =
                    QtVersionManager::scanMakeFile(directory, version->defaultBuildConfig());
            QtVersion::QmakeBuildConfigs qmakeBuildConfig = result.first;
            QStringList additionalArguments = Qt4BuildConfiguration::removeSpecFromArgumentList(result.second);
            QString parsedSpec = Qt4BuildConfiguration::extractSpecFromArgumentList(result.second, directory, version);
            QString versionSpec = version->mkspec();
            if (parsedSpec.isEmpty() || parsedSpec == versionSpec || parsedSpec == "default") {
                // using the default spec, don't modify additional arguments
            } else {
                additionalArguments.prepend(parsedSpec);
                additionalArguments.prepend("-spec");
            }

            // So we got all the information now apply it...
            m_buildConfiguration->setQtVersion(version);
            // Combo box will be updated at the end

            QMakeStep *qmakeStep = m_buildConfiguration->qmakeStep();
            qmakeStep->setUserArguments(additionalArguments);
            MakeStep *makeStep = m_buildConfiguration->makeStep();

            m_buildConfiguration->setQMakeBuildConfiguration(qmakeBuildConfig);
            // Adjust command line arguments, this is ugly as hell
            // If we are switching to BuildAll we want "release" in there and no "debug"
            // or "debug" in there and no "release"
            // If we are switching to not BuildAl we want neither "release" nor "debug" in there
            QStringList makeCmdArguments = makeStep->userArguments();
            bool debug = qmakeBuildConfig & QtVersion::DebugBuild;
            if (qmakeBuildConfig & QtVersion::BuildAll) {
                makeCmdArguments.removeAll(debug ? "release" : "debug");
                if (!makeCmdArguments.contains(debug ? "debug" : "release"))
                    makeCmdArguments.append(debug ? "debug" : "release");
            } else {
                makeCmdArguments.removeAll("debug");
                makeCmdArguments.removeAll("release");
            }
            makeStep->setUserArguments(makeCmdArguments);
        }
    }
    // All our widgets are updated by signals from the buildconfiguration
    // if not, there's either a signal missing
    // or we don't respond to it correctly
}

void Qt4ProjectConfigWidget::qtVersionSelected(const QString &)
{
    //Qt Version
    int newQtVersionId = m_ui->qtVersionComboBox->itemData(m_ui->qtVersionComboBox->currentIndex()).toInt();
    QtVersionManager *vm = QtVersionManager::instance();
    QtVersion *newQtVersion = vm->version(newQtVersionId);
    bool isValid = newQtVersion->isValid();
    m_ui->invalidQtWarningLabel->setVisible(!isValid);
    if (newQtVersion != m_buildConfiguration->qtVersion()) {
        m_ignoreChange = true;
        m_buildConfiguration->setQtVersion(newQtVersion);
        m_ignoreChange = false;
        updateToolChainCombo();
    }
    updateDetails();
}

void Qt4ProjectConfigWidget::updateToolChainCombo()
{
    m_ui->toolChainComboBox->clear();
    QList<ProjectExplorer::ToolChain::ToolChainType> toolchains(m_buildConfiguration->qtVersion()->possibleToolChainTypes());
    toolchains = m_buildConfiguration->qt4Target()->filterToolChainTypes(toolchains);
    foreach (ToolChain::ToolChainType toolchain, toolchains)
        m_ui->toolChainComboBox->addItem(ToolChain::toolChainName(toolchain), qVariantFromValue(toolchain));
    m_ui->toolChainComboBox->setEnabled(toolchains.size() > 1);
    m_ui->toolChainComboBox->setCurrentIndex(toolchains.indexOf(m_buildConfiguration->qt4Target()->preferredToolChainType(toolchains)));
    updateDetails();
}

void Qt4ProjectConfigWidget::toolChainSelected(int index)
{
    ProjectExplorer::ToolChain::ToolChainType selectedToolChainType =
        m_ui->toolChainComboBox->itemData(index,
            Qt::UserRole).value<ProjectExplorer::ToolChain::ToolChainType>();
    m_ignoreChange = true;
    m_buildConfiguration->setToolChainType(selectedToolChainType);
    m_ignoreChange = false;
    updateDetails();
}
<commit_msg>Fix a typo<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://qt.nokia.com/contact.
**
**************************************************************************/

#include "qt4projectconfigwidget.h"

#include "makestep.h"
#include "qmakestep.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanager.h"
#include "qt4buildconfiguration.h"
#include "ui_qt4projectconfigwidget.h"

#include <coreplugin/icore.h>
#include <coreplugin/mainwindow.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/buildconfiguration.h>
#include <utils/qtcassert.h>
#include <extensionsystem/pluginmanager.h>

#include <QtGui/QFileDialog>

namespace {
bool debug = false;
}

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using ProjectExplorer::ToolChain;

Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(Qt4Project *project)
    : BuildConfigWidget(),
      m_buildConfiguration(0),
      m_ignoreChange(false)
{
    Q_UNUSED(project);
    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setMargin(0);
    m_detailsContainer = new Utils::DetailsWidget(this);
    m_detailsContainer->setState(Utils::DetailsWidget::NoSummary);
    vbox->addWidget(m_detailsContainer);
    QWidget *details = new QWidget(m_detailsContainer);
    m_detailsContainer->setWidget(details);
    m_ui = new Ui::Qt4ProjectConfigWidget();
    m_ui->setupUi(details);

    m_browseButton = m_ui->shadowBuildDirEdit->buttonAtIndex(0);
    // TODO refix the layout

    m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr("Shadow Build Directory"));
    m_ui->shadowBuildDirEdit->setExpectedKind(Utils::PathChooser::Directory);
    m_ui->invalidQtWarningLabel->setVisible(false);

    connect(m_ui->nameLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(configNameEdited(QString)));

    connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),
            this, SLOT(shadowBuildClicked(bool)));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),
            this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(changed(QString)),
            this, SLOT(shadowBuildEdited()));

    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(qtVersionSelected(QString)));

    connect(m_ui->toolChainComboBox, SIGNAL(activated(int)),
            this, SLOT(toolChainSelected(int)));

    connect(m_ui->importLabel, SIGNAL(linkActivated(QString)),
            this, SLOT(importLabelClicked()));

    connect(m_ui->manageQtVersionPushButtons, SIGNAL(clicked()),
            this, SLOT(manageQtVersions()));

    QtVersionManager *vm = QtVersionManager::instance();
    connect(vm, SIGNAL(qtVersionsChanged(QList<int>)),
            this, SLOT(qtVersionsChanged()));
}

Qt4ProjectConfigWidget::~Qt4ProjectConfigWidget()
{
    delete m_ui;
}

void Qt4ProjectConfigWidget::updateDetails()
{
    QtVersion *version = m_buildConfiguration->qtVersion();

    QString versionString;
    versionString = version->displayName();

    if (!version || !version->isValid()) {
        // Not a valid qt version
        m_detailsContainer->setSummaryText(
                tr("using invalid Qt Version: %1
"
                   "%2")
                .arg(versionString,
                     version ? version->invalidReason() : tr("No Qt Version found.")));
    } else {
        // Qt Version, Build Directory and Toolchain
        m_detailsContainer->setSummaryText(
                tr("using Qt version: %1
"
                   "with tool chain %2
"
                   "building in %3")
                .arg(versionString,
                     ProjectExplorer::ToolChain::toolChainName(m_buildConfiguration->toolChainType()),
                     QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));
    }
}

void Qt4ProjectConfigWidget::manageQtVersions()
{
    Core::ICore *core = Core::ICore::instance();
    core->showOptionsDialog(Constants::QT_SETTINGS_CATEGORY, Constants::QTVERSION_SETTINGS_PAGE_ID);
}

QString Qt4ProjectConfigWidget::displayName() const
{
    return tr("General");
}

void Qt4ProjectConfigWidget::init(ProjectExplorer::BuildConfiguration *bc)
{
    QTC_ASSERT(bc, return);

    if (debug)
        qDebug() << "Qt4ProjectConfigWidget::init() for"<<bc->displayName();

    if (m_buildConfiguration) {
        disconnect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
                   this, SLOT(buildDirectoryChanged()));
        disconnect(m_buildConfiguration, SIGNAL(qtVersionChanged()),
                   this, SLOT(qtVersionChanged()));
        disconnect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
                   this, SLOT(updateImportLabel()));
    }
    m_buildConfiguration = static_cast<Qt4BuildConfiguration *>(bc);

    connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
            this, SLOT(buildDirectoryChanged()));
    connect(m_buildConfiguration, SIGNAL(qtVersionChanged()),
            this, SLOT(qtVersionChanged()));
    connect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
            this, SLOT(updateImportLabel()));

    m_ui->nameLineEdit->setText(m_buildConfiguration->displayName());

    qtVersionsChanged();

    bool shadowBuild = m_buildConfiguration->shadowBuild();
    m_ui->shadowBuildCheckBox->setChecked(shadowBuild);
    m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);
    m_browseButton->setEnabled(shadowBuild);
    m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->buildDirectory());
    updateImportLabel();
    updateToolChainCombo();
    updateDetails();
}

void Qt4ProjectConfigWidget::qtVersionChanged()
{
    updateImportLabel();
    updateToolChainCombo();
    updateDetails();
}

void Qt4ProjectConfigWidget::configNameEdited(const QString &newName)
{
    m_buildConfiguration->setDisplayName(newName);
}

void Qt4ProjectConfigWidget::qtVersionsChanged()
{
    if (!m_buildConfiguration) // not yet initialized
        return;

    disconnect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionSelected(QString)));

    QtVersionManager *vm = QtVersionManager::instance();

    m_ui->qtVersionComboBox->clear();
    QtVersion * qtVersion = m_buildConfiguration->qtVersion();

    const QList<QtVersion *> validVersions(vm->versionsForTargetId(m_buildConfiguration->target()->id()));
    if (validVersions.isEmpty()) {
        m_ui->invalidQtWarningLabel->setVisible(true);
    } else {
        m_ui->invalidQtWarningLabel->setVisible(false);
        for (int i = 0; i < validVersions.size(); ++i) {
            m_ui->qtVersionComboBox->addItem(validVersions.at(i)->displayName(),
                                             validVersions.at(i)->uniqueId());

            if (validVersions.at(i) == qtVersion) {
                m_ui->qtVersionComboBox->setCurrentIndex(i);
                m_ui->invalidQtWarningLabel->setVisible(!validVersions.at(i)->isValid());
            }
        }
        m_ui->qtVersionComboBox->setEnabled(validVersions.count() > 1);
    }

    // And connect again
    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionSelected(QString)));
}

void Qt4ProjectConfigWidget::buildDirectoryChanged()
{
    if (m_ignoreChange)
        return;
    m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->shadowBuildDirectory());
    updateDetails();
    updateImportLabel();
}

void Qt4ProjectConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()
{
    QString initialDirectory = QFileInfo(m_buildConfiguration->target()->project()->file()->fileName()).absolutePath();
    if (!initialDirectory.isEmpty())
        m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);
}

void Qt4ProjectConfigWidget::shadowBuildClicked(bool checked)
{
    m_ui->shadowBuildDirEdit->setEnabled(checked);
    m_browseButton->setEnabled(checked);
    bool b = m_ui->shadowBuildCheckBox->isChecked();

    m_ignoreChange = true;
    m_buildConfiguration->setShadowBuildAndDirectory(b, m_ui->shadowBuildDirEdit->path());
    m_ignoreChange = false;

    updateDetails();
    updateImportLabel();
}

void Qt4ProjectConfigWidget::shadowBuildEdited()
{
    if (m_buildConfiguration->shadowBuildDirectory() == m_ui->shadowBuildDirEdit->path())
        return;
    m_ignoreChange = true;
    m_buildConfiguration->setShadowBuildAndDirectory(true, m_ui->shadowBuildDirEdit->path());
    m_ignoreChange = false;

    // if the directory already exists
    // check if we have a build in there and
    // offer to import it
    updateImportLabel();
    updateDetails();
}

void Qt4ProjectConfigWidget::updateImportLabel()
{
    bool visible = false;
    bool targetMatches = false;

    QtVersionManager *vm = QtVersionManager::instance();
    // we only show if we actually have a qmake and makestep
    if (m_buildConfiguration->qmakeStep() && m_buildConfiguration->makeStep()) {
        QString qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(m_buildConfiguration->buildDirectory());
        QtVersion *version = m_buildConfiguration->qtVersion();
        // check that there's a makefile
        if (!qmakePath.isEmpty()) {
            // and that the qmake path is different from the current version
            if (qmakePath != (version ? version->qmakeCommand() : QString())) {
                // import enable
                visible = true;
                QtVersion *newVersion = vm->qtVersionForQMakeBinary(qmakePath);
                bool mustDelete(false);
                if (!newVersion) {
                    newVersion = new QtVersion(qmakePath);
                    mustDelete = true;
                }
                targetMatches = newVersion->supportsTargetId(m_buildConfiguration->target()->id());
                if (mustDelete)
                    delete newVersion;
            } else {
                // check that the qmake flags, arguments match
                visible = !m_buildConfiguration->compareToImportFrom(m_buildConfiguration->buildDirectory());
            }
        } else {
            visible = false;
        }
    }

    if (targetMatches) {
        m_ui->importProblemLabel->setVisible(false);
        m_ui->importWarningLabel->setVisible(false);
        m_ui->importLabel->setVisible(visible);
    } else {
        m_ui->importWarningLabel->setVisible(visible);
        m_ui->importProblemLabel->setVisible(visible);
        m_ui->importProblemLabel->setText(tr("An incompatible build exists in %1 and will be overwritten!",
                                             "%1 build directory").
                                          arg(m_ui->shadowBuildDirEdit->path()));
        m_ui->importLabel->setVisible(false);
    }
}

void Qt4ProjectConfigWidget::importLabelClicked()
{
    if (!m_buildConfiguration->qmakeStep() || !m_buildConfiguration->makeStep())
        return;
    QString directory = m_buildConfiguration->buildDirectory();
    if (!directory.isEmpty()) {
        QString qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(directory);
        if (!qmakePath.isEmpty()) {
            QtVersionManager *vm = QtVersionManager::instance();
            QtVersion *version = vm->qtVersionForQMakeBinary(qmakePath);
            if (!version) {
                version = new QtVersion(qmakePath);
                vm->addVersion(version);
            }

            QPair<QtVersion::QmakeBuildConfigs, QStringList> result =
                    QtVersionManager::scanMakeFile(directory, version->defaultBuildConfig());
            QtVersion::QmakeBuildConfigs qmakeBuildConfig = result.first;
            QStringList additionalArguments = Qt4BuildConfiguration::removeSpecFromArgumentList(result.second);
            QString parsedSpec = Qt4BuildConfiguration::extractSpecFromArgumentList(result.second, directory, version);
            QString versionSpec = version->mkspec();
            if (parsedSpec.isEmpty() || parsedSpec == versionSpec || parsedSpec == "default") {
                // using the default spec, don't modify additional arguments
            } else {
                additionalArguments.prepend(parsedSpec);
                additionalArguments.prepend("-spec");
            }

            // So we got all the information now apply it...
            m_buildConfiguration->setQtVersion(version);
            // Combo box will be updated at the end

            QMakeStep *qmakeStep = m_buildConfiguration->qmakeStep();
            qmakeStep->setUserArguments(additionalArguments);
            MakeStep *makeStep = m_buildConfiguration->makeStep();

            m_buildConfiguration->setQMakeBuildConfiguration(qmakeBuildConfig);
            // Adjust command line arguments, this is ugly as hell
            // If we are switching to BuildAll we want "release" in there and no "debug"
            // or "debug" in there and no "release"
            // If we are switching to not BuildAl we want neither "release" nor "debug" in there
            QStringList makeCmdArguments = makeStep->userArguments();
            bool debug = qmakeBuildConfig & QtVersion::DebugBuild;
            if (qmakeBuildConfig & QtVersion::BuildAll) {
                makeCmdArguments.removeAll(debug ? "release" : "debug");
                if (!makeCmdArguments.contains(debug ? "debug" : "release"))
                    makeCmdArguments.append(debug ? "debug" : "release");
            } else {
                makeCmdArguments.removeAll("debug");
                makeCmdArguments.removeAll("release");
            }
            makeStep->setUserArguments(makeCmdArguments);
        }
    }
    // All our widgets are updated by signals from the buildconfiguration
    // if not, there's either a signal missing
    // or we don't respond to it correctly
}

void Qt4ProjectConfigWidget::qtVersionSelected(const QString &)
{
    //Qt Version
    int newQtVersionId = m_ui->qtVersionComboBox->itemData(m_ui->qtVersionComboBox->currentIndex()).toInt();
    QtVersionManager *vm = QtVersionManager::instance();
    QtVersion *newQtVersion = vm->version(newQtVersionId);
    bool isValid = newQtVersion->isValid();
    m_ui->invalidQtWarningLabel->setVisible(!isValid);
    if (newQtVersion != m_buildConfiguration->qtVersion()) {
        m_ignoreChange = true;
        m_buildConfiguration->setQtVersion(newQtVersion);
        m_ignoreChange = false;
        updateToolChainCombo();
    }
    updateDetails();
}

void Qt4ProjectConfigWidget::updateToolChainCombo()
{
    m_ui->toolChainComboBox->clear();
    QList<ProjectExplorer::ToolChain::ToolChainType> toolchains(m_buildConfiguration->qtVersion()->possibleToolChainTypes());
    toolchains = m_buildConfiguration->qt4Target()->filterToolChainTypes(toolchains);
    foreach (ToolChain::ToolChainType toolchain, toolchains)
        m_ui->toolChainComboBox->addItem(ToolChain::toolChainName(toolchain), qVariantFromValue(toolchain));
    m_ui->toolChainComboBox->setEnabled(toolchains.size() > 1);
    m_ui->toolChainComboBox->setCurrentIndex(toolchains.indexOf(m_buildConfiguration->qt4Target()->preferredToolChainType(toolchains)));
    updateDetails();
}

void Qt4ProjectConfigWidget::toolChainSelected(int index)
{
    ProjectExplorer::ToolChain::ToolChainType selectedToolChainType =
        m_ui->toolChainComboBox->itemData(index,
            Qt::UserRole).value<ProjectExplorer::ToolChain::ToolChainType>();
    m_ignoreChange = true;
    m_buildConfiguration->setToolChainType(selectedToolChainType);
    m_ignoreChange = false;
    updateDetails();
}
<|endoftext|>


<commit_before>#ifndef ALEPH_PERSISTENCE_PAIRING_HH__
#define ALEPH_PERSISTENCE_PAIRING_HH__

#include <algorithm>
#include <limits>
#include <utility>
#include <vector>

namespace aleph
{

template <class Index> class PersistencePairing
{
public:

  // Typedefs & aliases ------------------------------------------------

  using IndexType     = Index;

  using ValueType     = std::pair<Index, Index>;
  using ContainerType = std::vector<ValueType>;

  using ConstIterator = typename ContainerType::const_iterator;
  using Iterator      = typename ContainerType::iterator;

  using value_type    = ValueType;

  // Iterators ---------------------------------------------------------

  ConstIterator begin() const { return _pairs.begin(); }
  Iterator      begin()       { return _pairs.begin(); }

  ConstIterator end() const   { return _pairs.end(); }
  Iterator      end()         { return _pairs.end(); }

  // Container modification --------------------------------------------

  void add( Index birth )
  {
    _pairs.push_back( std::make_pair( birth, std::numeric_limits<Index>::max() ) );
  }

  void add( Index birth, Index destruction )
  {
    _pairs.push_back( std::make_pair( birth, destruction ) );
  }

  Iterator erase( Iterator position )
  {
    return _pairs.erase( position );
  }

  Iterator erase( Iterator begin, Iterator end )
  {
    return _pairs.erase( begin, end );
  }

  // Comparison operators ----------------------------------------------

  bool operator==( const PersistencePairing<Index>& other ) const
  {
    return _pairs == other._pairs;
  }

  bool operator!=( const PersistencePairing<Index>& other ) const
  {
    return !( this->operator==( other ) );
  }

  // Queries -----------------------------------------------------------

  /**
    Returns the iterator corresponding to a given pair of indices. If
    the pairing does not contain the pair the function returns an end
    iterator.
  */

  ConstIterator find( Index creator, Index destroyer ) const noexcept
  {
    return std::find( _pairs.begin(), _pairs.end(),
                      std::make_pair( creator, destroyer ) );
  }

  /**
    Returns the iterator corresponding to a given creator index. If the
    creator cannot be found in the pairing, the function returns an end
    iterator.
  */

  ConstIterator find( Index creator ) const noexcept
  {
    return std::find_if( _pairs.begin(), _pairs.end(),
                         [this, &creator] ( const ValueType& pair )
                         {
                           return pair.first == creator;
                         } );

  }

  bool contains( Index creator, Index destroyer ) const
  {
    return this->find( creator, destroyer ) != _pairs.end();
  }

  bool contains( Index creator ) const
  {
    return this->find( creator ) != _pairs.end();
  }

  std::size_t size() const
  {
    return _pairs.size();
  }

  bool empty() const
  {
    return _pairs.empty();
  }

private:
  ContainerType _pairs;
};

}

#endif
<commit_msg>Documented persistence pairing class<commit_after>#ifndef ALEPH_PERSISTENCE_PAIRING_HH__
#define ALEPH_PERSISTENCE_PAIRING_HH__

#include <algorithm>
#include <limits>
#include <utility>
#include <vector>

namespace aleph
{

/**
  @class PersistencePairing
  @brief Container for index-based persistence pairings

  This class is a general-purpose container for pairings based on
  persistent homology. It consists of pairs of indices that refer
  to the paired simplices (or critical points) calculated using a
  persistent homology algorithm, for example.

  The class is purposefully kept simple and represents 'unpaired'
  simplices using a very large value. More precisely,

      std::numeric_limits<Index>::max()

  is used.
*/

template <class Index> class PersistencePairing
{
public:

  // Typedefs & aliases ------------------------------------------------

  using IndexType     = Index;

  using ValueType     = std::pair<Index, Index>;
  using ContainerType = std::vector<ValueType>;

  using ConstIterator = typename ContainerType::const_iterator;
  using Iterator      = typename ContainerType::iterator;

  using value_type    = ValueType;

  // Iterators ---------------------------------------------------------

  ConstIterator begin() const { return _pairs.begin(); }
  Iterator      begin()       { return _pairs.begin(); }

  ConstIterator end() const   { return _pairs.end(); }
  Iterator      end()         { return _pairs.end(); }

  // Container modification --------------------------------------------

  void add( Index birth )
  {
    _pairs.push_back( std::make_pair( birth, std::numeric_limits<Index>::max() ) );
  }

  void add( Index birth, Index destruction )
  {
    _pairs.push_back( std::make_pair( birth, destruction ) );
  }

  Iterator erase( Iterator position )
  {
    return _pairs.erase( position );
  }

  Iterator erase( Iterator begin, Iterator end )
  {
    return _pairs.erase( begin, end );
  }

  // Comparison operators ----------------------------------------------

  bool operator==( const PersistencePairing<Index>& other ) const
  {
    return _pairs == other._pairs;
  }

  bool operator!=( const PersistencePairing<Index>& other ) const
  {
    return !( this->operator==( other ) );
  }

  // Queries -----------------------------------------------------------

  /**
    Returns the iterator corresponding to a given pair of indices. If
    the pairing does not contain the pair the function returns an end
    iterator.
  */

  ConstIterator find( Index creator, Index destroyer ) const noexcept
  {
    return std::find( _pairs.begin(), _pairs.end(),
                      std::make_pair( creator, destroyer ) );
  }

  /**
    Returns the iterator corresponding to a given creator index. If the
    creator cannot be found in the pairing, the function returns an end
    iterator.
  */

  ConstIterator find( Index creator ) const noexcept
  {
    return std::find_if( _pairs.begin(), _pairs.end(),
                         [this, &creator] ( const ValueType& pair )
                         {
                           return pair.first == creator;
                         } );

  }

  bool contains( Index creator, Index destroyer ) const
  {
    return this->find( creator, destroyer ) != _pairs.end();
  }

  bool contains( Index creator ) const
  {
    return this->find( creator ) != _pairs.end();
  }

  std::size_t size() const
  {
    return _pairs.size();
  }

  bool empty() const
  {
    return _pairs.empty();
  }

private:
  ContainerType _pairs;
};

} // namespace aleph

#endif
<|endoftext|>


<commit_before>/* Copyright (C) 2002 MySQL AB

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "mysql_priv.h"
#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation
#endif
#include "sp_cache.h"
#include "sp_head.h"

static pthread_mutex_t Cversion_lock;
static ulong Cversion = 0;

/*
  Cache of stored routines.
*/

class sp_cache
{
public:
  ulong version;

  sp_cache();
  ~sp_cache();

  inline void insert(sp_head *sp)
  {
    /* TODO: why don't we check return value? */
    my_hash_insert(&m_hashtable, (const byte *)sp);
  }

  inline sp_head *lookup(char *name, uint namelen)
  {
    return (sp_head *)hash_search(&m_hashtable, (const byte *)name, namelen);
  }

#ifdef NOT_USED
  inline bool remove(char *name, uint namelen)
  {
    sp_head *sp= lookup(name, namelen);
    if (sp)
    {
      hash_delete(&m_hashtable, (byte *)sp);
      return TRUE;
    }
    return FALSE;
  }
#endif

  inline void remove_all()
  {
    cleanup();
    init();
  }

private:
  void init();
  void cleanup();

  /* All routines in this cache */
  HASH m_hashtable;
}; // class sp_cache

/* Initialize the SP caching once at startup */

void sp_cache_init()
{
  pthread_mutex_init(&Cversion_lock, MY_MUTEX_INIT_FAST);
}

/*
  Clear the cache *cp and set *cp to NULL.
  SYNOPSIS
    sp_cache_clear()
      cp  Pointer to cache to clear
  NOTE
    This function doesn't invalidate other caches.
*/

void sp_cache_clear(sp_cache **cp)
{
  sp_cache *c= *cp;
  if (c)
  {
    delete c;
    *cp= NULL;
  }
}

/*
  Insert a routine into the cache.

  SYNOPSIS
    sp_cache_insert()
      cp  The cache to put routine into
      sp  Routine to insert.
*/

void sp_cache_insert(sp_cache **cp, sp_head *sp)
{
  sp_cache *c= *cp;

  if (! c)
  {
    ulong v;
    c= new sp_cache();
    pthread_mutex_lock(&Cversion_lock); // LOCK
    v= Cversion;
    pthread_mutex_unlock(&Cversion_lock); // UNLOCK
    c->version= v;
  }
  if (c)
  {
    DBUG_PRINT("info",("sp_cache: inserting: %*s", sp->m_qname.length, sp->m_qname.str));
    c->insert(sp);
    if (*cp == NULL)
      *cp= c;
  }
}

/*
  Look up a routine in the cache.
  SYNOPSIS
    sp_cache_lookup()
      cp    Cache to look into
      name  Name of rutine to find

  NOTE
    An obsolete (but not more obsolete then since last
    sp_cache_flush_obsolete call) routine may be returned.

  RETURN
    The routine or
    NULL if the routine not found.
*/

sp_head *sp_cache_lookup(sp_cache **cp, sp_name *name)
{
  sp_cache *c= *cp;
  if (!c)
    return NULL;
  return c->lookup(name->m_qname.str, name->m_qname.length);
}

/*
  Invalidate all routines in all caches.

  SYNOPSIS
    sp_cache_invalidate()

  NOTE
    This is called when a VIEW definition is modifed. We can't destroy sp_head
    objects here as one may modify VIEW definitions from prelocking-free SPs.
*/

void sp_cache_invalidate()
{
  DBUG_PRINT("info",("sp_cache: invalidating"));
  pthread_mutex_lock(&Cversion_lock); // LOCK
  Cversion++;
  pthread_mutex_unlock(&Cversion_lock); // UNLOCK
}

/*
  Remove out-of-date SPs from the cache.

  SYNOPSIS
    sp_cache_flush_obsolete()
      cp  Cache to flush

  NOTE
    This invalidates pointers to sp_head objects this thread uses.
    In practice that means 'dont call this function when inside SP'.
*/

void sp_cache_flush_obsolete(sp_cache **cp)
{
  sp_cache *c= *cp;
  if (c)
  {
    ulong v;
    pthread_mutex_lock(&Cversion_lock); // LOCK
    v= Cversion;
    pthread_mutex_unlock(&Cversion_lock); // UNLOCK
    if (c->version < v)
    {
      DBUG_PRINT("info",("sp_cache: deleting all functions"));
      /* We need to delete all elements. */
      c->remove_all();
      c->version= v;
    }
  }
}

/*************************************************************************
  Internal functions
 *************************************************************************/

static byte *
hash_get_key_for_sp_head(const byte *ptr, uint *plen,
			       my_bool first)
{
  sp_head *sp= (sp_head *)ptr;

  *plen= sp->m_qname.length;
  return (byte*) sp->m_qname.str;
}

static void
hash_free_sp_head(void *p)
{
  sp_head *sp= (sp_head *)p;
  delete sp;
}

sp_cache::sp_cache()
{
  init();
}

sp_cache::~sp_cache()
{
  hash_free(&m_hashtable);
}

void
sp_cache::init()
{
  hash_init(&m_hashtable, system_charset_info, 0, 0, 0,
	    hash_get_key_for_sp_head, hash_free_sp_head, 0);
  version= 0;
}

void
sp_cache::cleanup()
{
  hash_free(&m_hashtable);
}
<commit_msg>BUG#12228: Pre-review fixes: Fix coding style, handle the case when we're out of memory.<commit_after>/* Copyright (C) 2002 MySQL AB

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "mysql_priv.h"
#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation
#endif
#include "sp_cache.h"
#include "sp_head.h"

static pthread_mutex_t Cversion_lock;
static ulong Cversion = 0;

/*
  Cache of stored routines.
*/

class sp_cache
{
public:
  ulong version;

  sp_cache();
  ~sp_cache();

  inline void insert(sp_head *sp)
  {
    /* TODO: why don't we check return value? */
    my_hash_insert(&m_hashtable, (const byte *)sp);
  }

  inline sp_head *lookup(char *name, uint namelen)
  {
    return (sp_head *)hash_search(&m_hashtable, (const byte *)name, namelen);
  }

#ifdef NOT_USED
  inline bool remove(char *name, uint namelen)
  {
    sp_head *sp= lookup(name, namelen);
    if (sp)
    {
      hash_delete(&m_hashtable, (byte *)sp);
      return TRUE;
    }
    return FALSE;
  }
#endif

  inline void remove_all()
  {
    cleanup();
    init();
  }

private:
  void init();
  void cleanup();

  /* All routines in this cache */
  HASH m_hashtable;
}; // class sp_cache

/* Initialize the SP caching once at startup */

void sp_cache_init()
{
  pthread_mutex_init(&Cversion_lock, MY_MUTEX_INIT_FAST);
}

/*
  Clear the cache *cp and set *cp to NULL.
  SYNOPSIS
    sp_cache_clear()
      cp  Pointer to cache to clear
  NOTE
    This function doesn't invalidate other caches.
*/

void sp_cache_clear(sp_cache **cp)
{
  sp_cache *c= *cp;
  if (c)
  {
    delete c;
    *cp= NULL;
  }
}

/*
  Insert a routine into the cache.

  SYNOPSIS
    sp_cache_insert()
      cp  The cache to put routine into
      sp  Routine to insert.

  TODO: Perhaps it will be more straightforward if in case we returned an
        error from this function when we couldn't allocate sp_cache. (right
        now failure to put routine into cache will cause a 'SP not found'
        error to be reported at some later time)
*/

void sp_cache_insert(sp_cache **cp, sp_head *sp)
{
  sp_cache *c= *cp;

  if (! c)
  {
    ulong v;
    c= new sp_cache();
    pthread_mutex_lock(&Cversion_lock); // LOCK
    v= Cversion;
    pthread_mutex_unlock(&Cversion_lock); // UNLOCK
    if (c)
      c->version= v;
  }
  if (c)
  {
    DBUG_PRINT("info",("sp_cache: inserting: %*s", sp->m_qname.length,
                       sp->m_qname.str));
    c->insert(sp);
    if (*cp == NULL)
      *cp= c;
  }
}

/*
  Look up a routine in the cache.
  SYNOPSIS
    sp_cache_lookup()
      cp    Cache to look into
      name  Name of rutine to find

  NOTE
    An obsolete (but not more obsolete then since last
    sp_cache_flush_obsolete call) routine may be returned.

  RETURN
    The routine or
    NULL if the routine not found.
*/

sp_head *sp_cache_lookup(sp_cache **cp, sp_name *name)
{
  sp_cache *c= *cp;
  if (!c)
    return NULL;
  return c->lookup(name->m_qname.str, name->m_qname.length);
}

/*
  Invalidate all routines in all caches.

  SYNOPSIS
    sp_cache_invalidate()

  NOTE
    This is called when a VIEW definition is modifed. We can't destroy sp_head
    objects here as one may modify VIEW definitions from prelocking-free SPs.
*/

void sp_cache_invalidate()
{
  DBUG_PRINT("info",("sp_cache: invalidating"));
  pthread_mutex_lock(&Cversion_lock); // LOCK
  Cversion++;
  pthread_mutex_unlock(&Cversion_lock); // UNLOCK
}

/*
  Remove out-of-date SPs from the cache.

  SYNOPSIS
    sp_cache_flush_obsolete()
      cp  Cache to flush

  NOTE
    This invalidates pointers to sp_head objects this thread uses.
    In practice that means 'dont call this function when inside SP'.
*/

void sp_cache_flush_obsolete(sp_cache **cp)
{
  sp_cache *c= *cp;
  if (c)
  {
    ulong v;
    pthread_mutex_lock(&Cversion_lock); // LOCK
    v= Cversion;
    pthread_mutex_unlock(&Cversion_lock); // UNLOCK
    if (c->version < v)
    {
      DBUG_PRINT("info",("sp_cache: deleting all functions"));
      /* We need to delete all elements. */
      c->remove_all();
      c->version= v;
    }
  }
}

/*************************************************************************
  Internal functions
 *************************************************************************/

static byte *
hash_get_key_for_sp_head(const byte *ptr, uint *plen,
			       my_bool first)
{
  sp_head *sp= (sp_head *)ptr;

  *plen= sp->m_qname.length;
  return (byte*) sp->m_qname.str;
}

static void
hash_free_sp_head(void *p)
{
  sp_head *sp= (sp_head *)p;
  delete sp;
}

sp_cache::sp_cache()
{
  init();
}

sp_cache::~sp_cache()
{
  hash_free(&m_hashtable);
}

void
sp_cache::init()
{
  hash_init(&m_hashtable, system_charset_info, 0, 0, 0,
	    hash_get_key_for_sp_head, hash_free_sp_head, 0);
  version= 0;
}

void
sp_cache::cleanup()
{
  hash_free(&m_hashtable);
}
<|endoftext|>


<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/matching/regions_matcher.hpp"
#include "openMVG/matching/matcher_brute_force.hpp"
#include "openMVG/matching/matcher_cascade_hashing.hpp"
#include "openMVG/matching/matcher_kdtree_flann.hpp"
#include "openMVG/matching/matcher_hnsw.hpp"
#include "openMVG/matching/metric.hpp"
#include "openMVG/matching/metric_hamming.hpp"

namespace openMVG {
namespace matching {

void Match
(
  const matching::EMatcherType & matcher_type,
  const features::Regions & database_regions,
  const features::Regions & query_regions,
  matching::IndMatches & matches
)
{
  const std::unique_ptr<RegionsMatcher> matcher =
    RegionMatcherFactory(matcher_type, database_regions);
  if (matcher)
  {
    matcher->Match(query_regions, matches);
  }
}

void DistanceRatioMatch
(
  float f_dist_ratio,
  const matching::EMatcherType & matcher_type,
  const features::Regions & database_regions,
  const features::Regions & query_regions,
  matching::IndMatches & matches
)
{
  const std::unique_ptr<RegionsMatcher> matcher =
    RegionMatcherFactory(matcher_type, database_regions);
  if (matcher)
  {
    matcher->MatchDistanceRatio(f_dist_ratio, query_regions, matches);
  }
}

std::unique_ptr<RegionsMatcher> RegionMatcherFactory
(
  matching::EMatcherType eMatcherType,
  const features::Regions & regions
)
{
  // Handle invalid request
  if (regions.IsScalar() && (eMatcherType == BRUTE_FORCE_HAMMING && eMatcherType == HNSW_HAMMING) )
    return {};
  if (regions.IsBinary() && (eMatcherType != BRUTE_FORCE_HAMMING && eMatcherType != HNSW_HAMMING) )
    return {};

  std::unique_ptr<RegionsMatcher> region_matcher;
  // Switch regions type ID, matcher & Metric: initialize the Matcher interface
  if (regions.IsScalar())
  {
    if (regions.Type_id() == typeid(unsigned char).name())
    {
      // Build on the fly unsigned char based Matcher
      switch (eMatcherType)
      {
        case BRUTE_FORCE_L2:
        {
          using MetricT = L2<unsigned char>;
          using MatcherT = ArrayMatcherBruteForce<unsigned char, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case ANN_L2:
        {
          using MetricT = flann::L2<unsigned char>;
          using MatcherT = ArrayMatcher_Kdtree_Flann<unsigned char, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case HNSW_L2:
        {
          using MetricT = L2<unsigned char>;
          using MatcherT = HNSWMatcher<unsigned char, MetricT, HNSWMETRIC::L2_HNSW>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        case HNSW_L1:
        {
          using MetricT = L1<unsigned char>;
          using MatcherT = HNSWMatcher<unsigned char, MetricT, HNSWMETRIC::L1_HNSW>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, false));
        }
        break;
        case CASCADE_HASHING_L2:
        {
          using MetricT = L2<unsigned char>;
          using MatcherT = ArrayMatcherCascadeHashing<unsigned char, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        default:
          std::cerr << "Using unknown matcher type" << std::endl;
      }
    }
    else if (regions.Type_id() == typeid(float).name())
    {
      // Build on the fly float based Matcher
      switch (eMatcherType)
      {
        case BRUTE_FORCE_L2:
        {
          using MetricT = L2<float>;
          using MatcherT = ArrayMatcherBruteForce<float, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case ANN_L2:
        {
          using MetricT = flann::L2<float>;
          using MatcherT = ArrayMatcher_Kdtree_Flann<float, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case HNSW_L2:
        {
          using MetricT = L2<float>;
          using MatcherT = HNSWMatcher<float, MetricT, HNSWMETRIC::L2_HNSW>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case CASCADE_HASHING_L2:
        {
          using MetricT = L2<float>;
          using MatcherT = ArrayMatcherCascadeHashing<float, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        default:
          std::cerr << "Using unknown matcher type" << std::endl;
      }
    }
    else if (regions.Type_id() == typeid(double).name())
    {
      // Build on the fly double based Matcher
      switch (eMatcherType)
      {
        case BRUTE_FORCE_L2:
        {
          using MetricT = L2<double>;
          using MatcherT = ArrayMatcherBruteForce<double, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case ANN_L2:
        {
          using MetricT = flann::L2<double>;
          using MatcherT = ArrayMatcher_Kdtree_Flann<double, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case CASCADE_HASHING_L2:
        {
          std::cerr << "Not implemented" << std::endl;
        }
        break;
        default:
          std::cerr << "Using unknown matcher type" << std::endl;
      }
    }
  }
  else if (regions.IsBinary() && regions.Type_id() == typeid(unsigned char).name())
  {
    switch (eMatcherType)
    {
      case BRUTE_FORCE_HAMMING:
      {
        using MetricT = Hamming<unsigned char>;
        using MatcherT = ArrayMatcherBruteForce<unsigned char, MetricT>;
        region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, false));
      }
      break;
      case HNSW_HAMMING:
      {
        using MetricT = Hamming<unsigned char>;
        using MatcherT = HNSWMatcher<unsigned char, MetricT, HNSWMETRIC::HAMMING_HNSW>;
        region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, false));
      }
      break;
      default:
        std::cerr << "Using unknown matcher type" << std::endl;
    }
  }
  else
  {
    std::cerr << "Please consider add this region type_id to RegionMatcherFactory(...)\n"
      << "typeid: " << regions.Type_id() << std::endl;
  }
  return region_matcher;
}

}  // namespace matching
}  // namespace openMVG
<commit_msg>[Misc] missing break<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/matching/regions_matcher.hpp"
#include "openMVG/matching/matcher_brute_force.hpp"
#include "openMVG/matching/matcher_cascade_hashing.hpp"
#include "openMVG/matching/matcher_kdtree_flann.hpp"
#include "openMVG/matching/matcher_hnsw.hpp"
#include "openMVG/matching/metric.hpp"
#include "openMVG/matching/metric_hamming.hpp"

namespace openMVG {
namespace matching {

void Match
(
  const matching::EMatcherType & matcher_type,
  const features::Regions & database_regions,
  const features::Regions & query_regions,
  matching::IndMatches & matches
)
{
  const std::unique_ptr<RegionsMatcher> matcher =
    RegionMatcherFactory(matcher_type, database_regions);
  if (matcher)
  {
    matcher->Match(query_regions, matches);
  }
}

void DistanceRatioMatch
(
  float f_dist_ratio,
  const matching::EMatcherType & matcher_type,
  const features::Regions & database_regions,
  const features::Regions & query_regions,
  matching::IndMatches & matches
)
{
  const std::unique_ptr<RegionsMatcher> matcher =
    RegionMatcherFactory(matcher_type, database_regions);
  if (matcher)
  {
    matcher->MatchDistanceRatio(f_dist_ratio, query_regions, matches);
  }
}

std::unique_ptr<RegionsMatcher> RegionMatcherFactory
(
  matching::EMatcherType eMatcherType,
  const features::Regions & regions
)
{
  // Handle invalid request
  if (regions.IsScalar() && (eMatcherType == BRUTE_FORCE_HAMMING && eMatcherType == HNSW_HAMMING) )
    return {};
  if (regions.IsBinary() && (eMatcherType != BRUTE_FORCE_HAMMING && eMatcherType != HNSW_HAMMING) )
    return {};

  std::unique_ptr<RegionsMatcher> region_matcher;
  // Switch regions type ID, matcher & Metric: initialize the Matcher interface
  if (regions.IsScalar())
  {
    if (regions.Type_id() == typeid(unsigned char).name())
    {
      // Build on the fly unsigned char based Matcher
      switch (eMatcherType)
      {
        case BRUTE_FORCE_L2:
        {
          using MetricT = L2<unsigned char>;
          using MatcherT = ArrayMatcherBruteForce<unsigned char, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case ANN_L2:
        {
          using MetricT = flann::L2<unsigned char>;
          using MatcherT = ArrayMatcher_Kdtree_Flann<unsigned char, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case HNSW_L2:
        {
          using MetricT = L2<unsigned char>;
          using MatcherT = HNSWMatcher<unsigned char, MetricT, HNSWMETRIC::L2_HNSW>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case HNSW_L1:
        {
          using MetricT = L1<unsigned char>;
          using MatcherT = HNSWMatcher<unsigned char, MetricT, HNSWMETRIC::L1_HNSW>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, false));
        }
        break;
        case CASCADE_HASHING_L2:
        {
          using MetricT = L2<unsigned char>;
          using MatcherT = ArrayMatcherCascadeHashing<unsigned char, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        default:
          std::cerr << "Using unknown matcher type" << std::endl;
      }
    }
    else if (regions.Type_id() == typeid(float).name())
    {
      // Build on the fly float based Matcher
      switch (eMatcherType)
      {
        case BRUTE_FORCE_L2:
        {
          using MetricT = L2<float>;
          using MatcherT = ArrayMatcherBruteForce<float, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case ANN_L2:
        {
          using MetricT = flann::L2<float>;
          using MatcherT = ArrayMatcher_Kdtree_Flann<float, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case HNSW_L2:
        {
          using MetricT = L2<float>;
          using MatcherT = HNSWMatcher<float, MetricT, HNSWMETRIC::L2_HNSW>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case CASCADE_HASHING_L2:
        {
          using MetricT = L2<float>;
          using MatcherT = ArrayMatcherCascadeHashing<float, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        default:
          std::cerr << "Using unknown matcher type" << std::endl;
      }
    }
    else if (regions.Type_id() == typeid(double).name())
    {
      // Build on the fly double based Matcher
      switch (eMatcherType)
      {
        case BRUTE_FORCE_L2:
        {
          using MetricT = L2<double>;
          using MatcherT = ArrayMatcherBruteForce<double, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case ANN_L2:
        {
          using MetricT = flann::L2<double>;
          using MatcherT = ArrayMatcher_Kdtree_Flann<double, MetricT>;
          region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, true));
        }
        break;
        case CASCADE_HASHING_L2:
        {
          std::cerr << "Not implemented" << std::endl;
        }
        break;
        default:
          std::cerr << "Using unknown matcher type" << std::endl;
      }
    }
  }
  else if (regions.IsBinary() && regions.Type_id() == typeid(unsigned char).name())
  {
    switch (eMatcherType)
    {
      case BRUTE_FORCE_HAMMING:
      {
        using MetricT = Hamming<unsigned char>;
        using MatcherT = ArrayMatcherBruteForce<unsigned char, MetricT>;
        region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, false));
      }
      break;
      case HNSW_HAMMING:
      {
        using MetricT = Hamming<unsigned char>;
        using MatcherT = HNSWMatcher<unsigned char, MetricT, HNSWMETRIC::HAMMING_HNSW>;
        region_matcher.reset(new matching::RegionsMatcherT<MatcherT>(regions, false));
      }
      break;
      default:
        std::cerr << "Using unknown matcher type" << std::endl;
    }
  }
  else
  {
    std::cerr << "Please consider add this region type_id to RegionMatcherFactory(...)\n"
      << "typeid: " << regions.Type_id() << std::endl;
  }
  return region_matcher;
}

}  // namespace matching
}  // namespace openMVG
<|endoftext|>


<commit_before>//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "ProfilingConnectionDumpToFileDecorator.hpp"

#include <armnn/Exceptions.hpp>

#include <fstream>

namespace armnn
{

namespace profiling
{

ProfilingConnectionDumpToFileDecorator::ProfilingConnectionDumpToFileDecorator(
    std::unique_ptr<IProfilingConnection> connection,
    const Settings& settings)
    : m_Connection(std::move(connection))
    , m_Settings(settings)
{
    if (!m_Connection)
    {
        throw InvalidArgumentException("Connection cannot be nullptr");
    }
}

ProfilingConnectionDumpToFileDecorator::~ProfilingConnectionDumpToFileDecorator()
{
    Close();
}

bool ProfilingConnectionDumpToFileDecorator::IsOpen()
{
    return m_Connection->IsOpen();
}

void ProfilingConnectionDumpToFileDecorator::Close()
{
    m_IncomingDumpFileStream.close();
    m_OutgoingDumpFileStream.close();
    m_Connection->Close();
}

bool ProfilingConnectionDumpToFileDecorator::WritePacket(const unsigned char* buffer, uint32_t length)
{
    bool success = true;
    if (m_Settings.m_DumpOutgoing)
    {
        success &= DumpOutgoingToFile(reinterpret_cast<const char*>(buffer), length);
    }
    success &= m_Connection->WritePacket(buffer, length);
    return success;
}

Packet ProfilingConnectionDumpToFileDecorator::ReadPacket(uint32_t timeout)
{
    Packet packet = m_Connection->ReadPacket(timeout);
    if (m_Settings.m_DumpIncoming)
    {
        DumpIncomingToFile(packet);
    }
    return packet;
}

bool ProfilingConnectionDumpToFileDecorator::OpenIncomingDumpFile()
{
    m_IncomingDumpFileStream.open(m_Settings.m_IncomingDumpFileName, std::ios::out | std::ios::binary);
    return m_IncomingDumpFileStream.is_open();
}

bool ProfilingConnectionDumpToFileDecorator::OpenOutgoingDumpFile()
{
    m_OutgoingDumpFileStream.open(m_Settings.m_OutgoingDumpFileName, std::ios::out | std::ios::binary);
    return m_OutgoingDumpFileStream.is_open();
}

/// Dumps incoming data into the file specified by m_Settings.m_IncomingDumpFileName.
/// If m_IgnoreFileErrors is set to true in m_Settings, write errors will be ignored,
/// i.e. the method will not throw an exception if it encounters an error while trying
/// to write the data into the specified file.
/// @param packet data packet to write
/// @return nothing
void ProfilingConnectionDumpToFileDecorator::DumpIncomingToFile(const Packet& packet)
{
    bool success = true;
    if (!m_IncomingDumpFileStream.is_open())
    {
        // attempt to open dump file
        success &= OpenIncomingDumpFile();
        if (!(success || m_Settings.m_IgnoreFileErrors))
        {
            Fail("Failed to open \"" + m_Settings.m_IncomingDumpFileName + "\" for writing");
        }
    }

    // attempt to write binary data from packet
    const unsigned int header = packet.GetHeader();
    const unsigned int packetLength = packet.GetLength();

    m_IncomingDumpFileStream.write(reinterpret_cast<const char*>(&header), sizeof header);
    m_IncomingDumpFileStream.write(reinterpret_cast<const char*>(&packetLength), sizeof packetLength);
    m_IncomingDumpFileStream.write(packet.GetData(), packetLength);

    success &= m_IncomingDumpFileStream.good();
    if (!(success || m_Settings.m_IgnoreFileErrors))
    {
        Fail("Error writing incoming packet of " + std::to_string(packetLength) + " bytes");
    }
}

/// Dumps outgoing data into the file specified by m_Settings.m_OutgoingDumpFileName.
/// If m_IgnoreFileErrors is set to true in m_Settings, write errors will be ignored,
/// i.e. the method will not throw an exception if it encounters an error while trying
/// to write the data into the specified file. However, the return value will still
/// signal if the write has not been completed succesfully.
/// @param buffer pointer to data to write
/// @param length number of bytes to write
/// @return true if write successful, false otherwise
bool ProfilingConnectionDumpToFileDecorator::DumpOutgoingToFile(const char* buffer, uint32_t length)
{
    bool success = true;
    if (!m_OutgoingDumpFileStream.is_open())
    {
        // attempt to open dump file
        success &= OpenOutgoingDumpFile();
        if (!(success || m_Settings.m_IgnoreFileErrors))
        {
            Fail("Failed to open \"" + m_Settings.m_OutgoingDumpFileName + "\" for writing");
        }
    }

    // attempt to write binary data
    m_OutgoingDumpFileStream.write(buffer, length);
    success &= m_OutgoingDumpFileStream.good();
    if (!(success || m_Settings.m_IgnoreFileErrors))
    {
        Fail("Error writing outgoing packet of " + std::to_string(length) + " bytes");
    }

    return success;
}

void ProfilingConnectionDumpToFileDecorator::Fail(const std::string& errorMessage)
{
    Close();
    throw RuntimeException(errorMessage);
}

} // namespace profiling

} // namespace armnn
<commit_msg>IVGCVSW-3920 Fix build regression due to implicit conversion in ProfilingConnectionDumpToFileDecorator<commit_after>//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "ProfilingConnectionDumpToFileDecorator.hpp"

#include <armnn/Exceptions.hpp>

#include <fstream>

#include <boost/numeric/conversion/cast.hpp>

namespace armnn
{

namespace profiling
{

ProfilingConnectionDumpToFileDecorator::ProfilingConnectionDumpToFileDecorator(
    std::unique_ptr<IProfilingConnection> connection,
    const Settings& settings)
    : m_Connection(std::move(connection))
    , m_Settings(settings)
{
    if (!m_Connection)
    {
        throw InvalidArgumentException("Connection cannot be nullptr");
    }
}

ProfilingConnectionDumpToFileDecorator::~ProfilingConnectionDumpToFileDecorator()
{
    Close();
}

bool ProfilingConnectionDumpToFileDecorator::IsOpen()
{
    return m_Connection->IsOpen();
}

void ProfilingConnectionDumpToFileDecorator::Close()
{
    m_IncomingDumpFileStream.close();
    m_OutgoingDumpFileStream.close();
    m_Connection->Close();
}

bool ProfilingConnectionDumpToFileDecorator::WritePacket(const unsigned char* buffer, uint32_t length)
{
    bool success = true;
    if (m_Settings.m_DumpOutgoing)
    {
        success &= DumpOutgoingToFile(reinterpret_cast<const char*>(buffer), length);
    }
    success &= m_Connection->WritePacket(buffer, length);
    return success;
}

Packet ProfilingConnectionDumpToFileDecorator::ReadPacket(uint32_t timeout)
{
    Packet packet = m_Connection->ReadPacket(timeout);
    if (m_Settings.m_DumpIncoming)
    {
        DumpIncomingToFile(packet);
    }
    return packet;
}

bool ProfilingConnectionDumpToFileDecorator::OpenIncomingDumpFile()
{
    m_IncomingDumpFileStream.open(m_Settings.m_IncomingDumpFileName, std::ios::out | std::ios::binary);
    return m_IncomingDumpFileStream.is_open();
}

bool ProfilingConnectionDumpToFileDecorator::OpenOutgoingDumpFile()
{
    m_OutgoingDumpFileStream.open(m_Settings.m_OutgoingDumpFileName, std::ios::out | std::ios::binary);
    return m_OutgoingDumpFileStream.is_open();
}

/// Dumps incoming data into the file specified by m_Settings.m_IncomingDumpFileName.
/// If m_IgnoreFileErrors is set to true in m_Settings, write errors will be ignored,
/// i.e. the method will not throw an exception if it encounters an error while trying
/// to write the data into the specified file.
/// @param packet data packet to write
/// @return nothing
void ProfilingConnectionDumpToFileDecorator::DumpIncomingToFile(const Packet& packet)
{
    bool success = true;
    if (!m_IncomingDumpFileStream.is_open())
    {
        // attempt to open dump file
        success &= OpenIncomingDumpFile();
        if (!(success || m_Settings.m_IgnoreFileErrors))
        {
            Fail("Failed to open \"" + m_Settings.m_IncomingDumpFileName + "\" for writing");
        }
    }

    // attempt to write binary data from packet
    const unsigned int header       = packet.GetHeader();
    const unsigned int packetLength = packet.GetLength();

    m_IncomingDumpFileStream.write(reinterpret_cast<const char*>(&header), sizeof header);
    m_IncomingDumpFileStream.write(reinterpret_cast<const char*>(&packetLength), sizeof packetLength);
    m_IncomingDumpFileStream.write(packet.GetData(), boost::numeric_cast<std::streamsize>(packetLength));

    success &= m_IncomingDumpFileStream.good();
    if (!(success || m_Settings.m_IgnoreFileErrors))
    {
        Fail("Error writing incoming packet of " + std::to_string(packetLength) + " bytes");
    }
}

/// Dumps outgoing data into the file specified by m_Settings.m_OutgoingDumpFileName.
/// If m_IgnoreFileErrors is set to true in m_Settings, write errors will be ignored,
/// i.e. the method will not throw an exception if it encounters an error while trying
/// to write the data into the specified file. However, the return value will still
/// signal if the write has not been completed succesfully.
/// @param buffer pointer to data to write
/// @param length number of bytes to write
/// @return true if write successful, false otherwise
bool ProfilingConnectionDumpToFileDecorator::DumpOutgoingToFile(const char* buffer, uint32_t length)
{
    bool success = true;
    if (!m_OutgoingDumpFileStream.is_open())
    {
        // attempt to open dump file
        success &= OpenOutgoingDumpFile();
        if (!(success || m_Settings.m_IgnoreFileErrors))
        {
            Fail("Failed to open \"" + m_Settings.m_OutgoingDumpFileName + "\" for writing");
        }
    }

    // attempt to write binary data
    m_OutgoingDumpFileStream.write(buffer, boost::numeric_cast<std::streamsize>(length));
    success &= m_OutgoingDumpFileStream.good();
    if (!(success || m_Settings.m_IgnoreFileErrors))
    {
        Fail("Error writing outgoing packet of " + std::to_string(length) + " bytes");
    }

    return success;
}

void ProfilingConnectionDumpToFileDecorator::Fail(const std::string& errorMessage)
{
    Close();
    throw RuntimeException(errorMessage);
}

} // namespace profiling

} // namespace armnn
<|endoftext|>


<commit_before>#ifndef Renderer_HPP
#define Renderer_HPP

#include "FBO.hpp"
#include "BeatDetect.hpp"
#include "Common.hpp"
#include <string>
#include <set>

#ifdef USE_GLES1
#include <GLES/gl.h>
#else
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#endif

#ifdef USE_FTGL
#ifdef WIN32
#include <ftgl.h>
#include <FTGLPixmapFont.h>
#include <FTGLExtrdFont.h>
#else
#include <FTGL/ftgl.h>
#endif
#endif /** USE_FTGL */

#include "Pipeline.hpp"
#include "PerPixelMesh.hpp"
#include "Transformation.hpp"
#include "ShaderEngine.hpp"

class UserTexture;
class BeatDetect;
class TextureManager;

class Renderer
{

public:

  bool showfps;
  bool showtitle;
  bool showpreset;
  bool showhelp;
  bool showstats;

  bool studio;
  bool correction;

  bool noSwitch;

  int totalframes;
  float realfps;

  std::string title;
  int drawtitle;
  int texsize;

  Renderer( int width, int height, int gx, int gy, int texsize,  BeatDetect *beatDetect, std::string presetURL, std::string title_fontURL, std::string menu_fontURL);
  ~Renderer();

  void RenderFrame(const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void ResetTextures();
  void reset(int w, int h);
  GLuint initRenderToTexture();

  void SetPipeline(Pipeline &pipeline);

  void setPresetName(const std::string& theValue)
  {
    m_presetName = theValue;
  }

  std::string presetName() const
  {
    return m_presetName;
  }

private:

	PerPixelMesh mesh;
  RenderTarget *renderTarget;
  BeatDetect *beatDetect;
  TextureManager *textureManager;
  static Pipeline* currentPipe;
  RenderContext renderContext;
  //per pixel equation variables
#ifdef USE_CG
  ShaderEngine shaderEngine;
#endif
  std::string m_presetName;

  float* p;

  int vw;
  int vh;

  float aspect;

  std::string title_fontURL;
  std::string menu_fontURL;
  std::string presetURL;

#ifdef USE_FTGL
  FTGLPixmapFont *title_font;
  FTGLPixmapFont *other_font;
  FTGLExtrdFont *poly_font;
#endif /** USE_FTGL */

  void SetupPass1(const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void Interpolation(const Pipeline &pipeline);
  void RenderItems(const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void FinishPass1();
  void Pass2 (const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void CompositeOutput(const Pipeline &pipeline, const PipelineContext &pipelineContext);

  inline static PixelPoint PerPixel(PixelPoint p, PerPixelContext &context)
  {
	  return currentPipe->PerPixel(p,context);
  }

  void rescale_per_pixel_matrices();

  void draw_fps( float realfps );
  void draw_stats();
  void draw_help();
  void draw_preset();
  void draw_title();
  void draw_title_to_screen(bool flip);
  void draw_title_to_texture();

};

#endif
<commit_msg>gles gl.h support<commit_after>#ifndef Renderer_HPP
#define Renderer_HPP

#include "FBO.hpp"
#include "BeatDetect.hpp"
#include "Common.hpp"
#include <string>
#include <set>

#ifdef USE_GLES1
  #include <GLES/gl.h>
#else
  #ifdef __APPLE__
    #include <OpenGL/gl.h>
  #else
    #include <GL/gl.h>
    #include <GL/glu.h>
  #endif
#endif

#ifdef USE_FTGL
#ifdef WIN32
#include <ftgl.h>
#include <FTGLPixmapFont.h>
#include <FTGLExtrdFont.h>
#else
#include <FTGL/ftgl.h>
#endif
#endif /** USE_FTGL */

#include "Pipeline.hpp"
#include "PerPixelMesh.hpp"
#include "Transformation.hpp"
#include "ShaderEngine.hpp"

class UserTexture;
class BeatDetect;
class TextureManager;

class Renderer
{

public:

  bool showfps;
  bool showtitle;
  bool showpreset;
  bool showhelp;
  bool showstats;

  bool studio;
  bool correction;

  bool noSwitch;

  int totalframes;
  float realfps;

  std::string title;
  int drawtitle;
  int texsize;

  Renderer( int width, int height, int gx, int gy, int texsize,  BeatDetect *beatDetect, std::string presetURL, std::string title_fontURL, std::string menu_fontURL);
  ~Renderer();

  void RenderFrame(const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void ResetTextures();
  void reset(int w, int h);
  GLuint initRenderToTexture();

  void SetPipeline(Pipeline &pipeline);

  void setPresetName(const std::string& theValue)
  {
    m_presetName = theValue;
  }

  std::string presetName() const
  {
    return m_presetName;
  }

private:

	PerPixelMesh mesh;
  RenderTarget *renderTarget;
  BeatDetect *beatDetect;
  TextureManager *textureManager;
  static Pipeline* currentPipe;
  RenderContext renderContext;
  //per pixel equation variables
#ifdef USE_CG
  ShaderEngine shaderEngine;
#endif
  std::string m_presetName;

  float* p;

  int vw;
  int vh;

  float aspect;

  std::string title_fontURL;
  std::string menu_fontURL;
  std::string presetURL;

#ifdef USE_FTGL
  FTGLPixmapFont *title_font;
  FTGLPixmapFont *other_font;
  FTGLExtrdFont *poly_font;
#endif /** USE_FTGL */

  void SetupPass1(const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void Interpolation(const Pipeline &pipeline);
  void RenderItems(const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void FinishPass1();
  void Pass2 (const Pipeline &pipeline, const PipelineContext &pipelineContext);
  void CompositeOutput(const Pipeline &pipeline, const PipelineContext &pipelineContext);

  inline static PixelPoint PerPixel(PixelPoint p, PerPixelContext &context)
  {
	  return currentPipe->PerPixel(p,context);
  }

  void rescale_per_pixel_matrices();

  void draw_fps( float realfps );
  void draw_stats();
  void draw_help();
  void draw_preset();
  void draw_title();
  void draw_title_to_screen(bool flip);
  void draw_title_to_texture();

};

#endif
<|endoftext|>


<commit_before>#include "settings.h"

#include <QtCore/QUrl>
#include <QtCore/QDebug>

using namespace QMatrixClient;

QString Settings::legacyOrganizationName {};
QString Settings::legacyApplicationName {};

void Settings::setLegacyNames(const QString& organizationName,
                              const QString& applicationName)
{
    legacyOrganizationName = organizationName;
    legacyApplicationName = applicationName;
}

void Settings::setValue(const QString& key, const QVariant& value)
{
//    qCDebug() << "Setting" << key << "to" << value;
    QSettings::setValue(key, value);
}

QVariant Settings::value(const QString& key, const QVariant& defaultValue) const
{
    return QSettings::value(key, legacySettings.value(key, defaultValue));
}

bool Settings::contains(const QString& key) const
{
    return QSettings::contains(key) || legacySettings.contains(key);
}

QStringList Settings::childGroups() const
{
    auto l = QSettings::childGroups();
    return !l.isEmpty() ? l : legacySettings.childGroups();
}

void SettingsGroup::setValue(const QString& key, const QVariant& value)
{
    Settings::setValue(groupPath + '/' + key, value);
}

bool SettingsGroup::contains(const QString& key) const
{
    return Settings::contains(groupPath + '/' + key);
}

QVariant SettingsGroup::value(const QString& key, const QVariant& defaultValue) const
{
    return Settings::value(groupPath + '/' + key, defaultValue);
}

QString SettingsGroup::group() const
{
    return groupPath;
}

QStringList SettingsGroup::childGroups() const
{
    const_cast<SettingsGroup*>(this)->beginGroup(groupPath);
    const_cast<QSettings&>(legacySettings).beginGroup(groupPath);
    QStringList l = Settings::childGroups();
    const_cast<SettingsGroup*>(this)->endGroup();
    const_cast<QSettings&>(legacySettings).endGroup();
    return l;
}

void SettingsGroup::remove(const QString& key)
{
    QString fullKey { groupPath };
    if (!key.isEmpty())
        fullKey += "/" + key;
    Settings::remove(fullKey);
}

bool AccountSettings::keepLoggedIn() const
{
    return value("keep_logged_in", false).toBool();
}

void AccountSettings::setKeepLoggedIn(bool newSetting)
{
    setValue("keep_logged_in", newSetting);
}

QUrl AccountSettings::homeserver() const
{
    return QUrl::fromUserInput(value("homeserver").toString());
}

void AccountSettings::setHomeserver(const QUrl& url)
{
    setValue("homeserver", url.toString());
}

QString AccountSettings::userId() const
{
    return group().section('/', -1);
}

QString AccountSettings::deviceId() const
{
    return value("device_id").toString();
}

void AccountSettings::setDeviceId(const QString& deviceId)
{
    setValue("device_id", deviceId);
}

QString AccountSettings::deviceName() const
{
    return value("device_name").toString();
}

void AccountSettings::setDeviceName(const QString& deviceName)
{
    setValue("device_name", deviceName);
}

QString AccountSettings::accessToken() const
{
    return value("access_token").toString();
}

void AccountSettings::setAccessToken(const QString& accessToken)
{
    setValue("access_token", accessToken);
}

void AccountSettings::clearAccessToken()
{
    remove("access_token");
}
<commit_msg>Settings: Catch literal "false" values stored by Qt.labs.Settings QML module<commit_after>#include "settings.h"

#include <QtCore/QUrl>
#include <QtCore/QDebug>

using namespace QMatrixClient;

QString Settings::legacyOrganizationName {};
QString Settings::legacyApplicationName {};

void Settings::setLegacyNames(const QString& organizationName,
                              const QString& applicationName)
{
    legacyOrganizationName = organizationName;
    legacyApplicationName = applicationName;
}

void Settings::setValue(const QString& key, const QVariant& value)
{
//    qCDebug() << "Setting" << key << "to" << value;
    QSettings::setValue(key, value);
}

QVariant Settings::value(const QString& key, const QVariant& defaultValue) const
{
    auto value = QSettings::value(key, legacySettings.value(key, defaultValue));
    // QML's Qt.labs.Settings stores boolean values as strings, which, if loaded
    // through the usual QSettings interface, confuses QML
    // (QVariant("false") == true in JavaScript). Since we have a mixed
    // environment where both QSettings and Qt.labs.Settings may potentially
    // work with same settings, better ensure compatibility.
    return value.toString() == QStringLiteral("false") ? QVariant(false) : value;
}

bool Settings::contains(const QString& key) const
{
    return QSettings::contains(key) || legacySettings.contains(key);
}

QStringList Settings::childGroups() const
{
    auto l = QSettings::childGroups();
    return !l.isEmpty() ? l : legacySettings.childGroups();
}

void SettingsGroup::setValue(const QString& key, const QVariant& value)
{
    Settings::setValue(groupPath + '/' + key, value);
}

bool SettingsGroup::contains(const QString& key) const
{
    return Settings::contains(groupPath + '/' + key);
}

QVariant SettingsGroup::value(const QString& key, const QVariant& defaultValue) const
{
    return Settings::value(groupPath + '/' + key, defaultValue);
}

QString SettingsGroup::group() const
{
    return groupPath;
}

QStringList SettingsGroup::childGroups() const
{
    const_cast<SettingsGroup*>(this)->beginGroup(groupPath);
    const_cast<QSettings&>(legacySettings).beginGroup(groupPath);
    QStringList l = Settings::childGroups();
    const_cast<SettingsGroup*>(this)->endGroup();
    const_cast<QSettings&>(legacySettings).endGroup();
    return l;
}

void SettingsGroup::remove(const QString& key)
{
    QString fullKey { groupPath };
    if (!key.isEmpty())
        fullKey += "/" + key;
    Settings::remove(fullKey);
}

bool AccountSettings::keepLoggedIn() const
{
    return value("keep_logged_in", false).toBool();
}

void AccountSettings::setKeepLoggedIn(bool newSetting)
{
    setValue("keep_logged_in", newSetting);
}

QUrl AccountSettings::homeserver() const
{
    return QUrl::fromUserInput(value("homeserver").toString());
}

void AccountSettings::setHomeserver(const QUrl& url)
{
    setValue("homeserver", url.toString());
}

QString AccountSettings::userId() const
{
    return group().section('/', -1);
}

QString AccountSettings::deviceId() const
{
    return value("device_id").toString();
}

void AccountSettings::setDeviceId(const QString& deviceId)
{
    setValue("device_id", deviceId);
}

QString AccountSettings::deviceName() const
{
    return value("device_name").toString();
}

void AccountSettings::setDeviceName(const QString& deviceName)
{
    setValue("device_name", deviceName);
}

QString AccountSettings::accessToken() const
{
    return value("access_token").toString();
}

void AccountSettings::setAccessToken(const QString& accessToken)
{
    setValue("access_token", accessToken);
}

void AccountSettings::clearAccessToken()
{
    remove("access_token");
}
<|endoftext|>


<commit_before>#ifndef MOTOR_CONTROLER
#define MOTOR_CONTROLER
#include "ros/ros.h"
#include "ros/console.h"
#include "std_msgs/Float64.h"
#include "geometry_msgs/Twist.h"
#include <tf/transform_listener.h>
#include <string>
#include <vector>
#include <cmath>

// publisher of right and left motor velocity values
ros::Publisher right_motor_pub;
ros::Publisher left_motor_pub;

// robot's index in ROS ecosystem (if multiple instances)
int robot_id = 0;
double WHEELS_HALF_SPACING = 0;
double WHEEL_RADIUS = 0.1;

void callback_val(const geometry_msgs::Twist::ConstPtr &msg) {

  // creating new message
  std_msgs::Float64 msg_right_;
  std_msgs::Float64 msg_left_;
  double yaw = 0;

  if (msg.get()->angular.z < -0.0001 || msg.get()->angular.z > 0.0001)
    yaw = msg.get()->angular.z;
  else if (msg.get()->linear.y < -0.0001 || msg.get()->linear.y > 0.0001) {
    // yaw is not set-- trying to calculate from linear x and y
    ROS_WARN("DPL: in Twist msg no yaw component");
    yaw = std::atan2(msg.get()->linear.y, msg.get()->linear.x);
  }

  // calculate from linear x and yaw speed for each wheel
  msg_right_.data =
      (msg.get()->linear.x + WHEELS_HALF_SPACING * yaw) / WHEEL_RADIUS;
  msg_left_.data =
      (msg.get()->linear.x - WHEELS_HALF_SPACING * yaw) / WHEEL_RADIUS;
  // publishing wheel velocities
  right_motor_pub.publish(move(msg_right_));
  left_motor_pub.publish(move(msg_left_));
}

int main(int argc, char **argv) {
  std::string pub_right_ = "hal/rightMotor/setVel";
  std::string pub_left_ = "hal/leftMotor/setVel";
  std::string sub_twist = "/cmd_vel";
  ros::init(argc, argv, "motorControl");

  // read  from command line names of topics to publish data
  if (argc >= 3) {
    std::vector<std::string> argv_(argv + 1, argv + argc);
    pub_right_ = argv_[0];
    pub_left_ = argv_[1];
    if(argc==4) sub_twist = argv_[2];
  }
  // set relative node namespace
  ros::NodeHandle n;
  n.getParam("robot_id", robot_id);

  // tf listener for calculation of wheel spacing
  tf::TransformListener listener;
  tf::StampedTransform transform;
  // get length in between wheels
  try {
    listener.waitForTransform(std::to_string(robot_id) + "/base/joint1",
                              std::to_string(robot_id) + "/base/joint0",
                              ros::Time::now(), ros::Duration(3.0));
    listener.lookupTransform(std::to_string(robot_id) + "/base/joint1",
                             std::to_string(robot_id) + "/base/joint0",
                             ros::Time(0), transform);
    WHEELS_HALF_SPACING = transform.getOrigin().absolute().getY() / 2;
    ROS_INFO("DPL: motor_controler WHEELS_HALF_SPACING: %f",
             WHEELS_HALF_SPACING);

  } catch (tf::TransformException ex) {
    ROS_ERROR("Problem with transformation between wheels: %s", ex.what());
  }

  // read msg from standard ROS topic for receiving Twist commands
  ros::Subscriber twist_sub = n.subscribe("/cmd_vel", 1000, callback_val);

  right_motor_pub = n.advertise<std_msgs::Float64>(pub_right_, 1000);
  left_motor_pub = n.advertise<std_msgs::Float64>(pub_left_, 1000);
  ROS_INFO("DPL: motor_controler node initialized");

  // run event loop
  ros::spin();
  return 0;
}
#endif
<commit_msg>fix cmd line param of subscribing for twist msg added to subscriber initialization<commit_after>#ifndef MOTOR_CONTROLER
#define MOTOR_CONTROLER
#include "ros/ros.h"
#include "ros/console.h"
#include "std_msgs/Float64.h"
#include "geometry_msgs/Twist.h"
#include <tf/transform_listener.h>
#include <string>
#include <vector>
#include <cmath>

// publisher of right and left motor velocity values
ros::Publisher right_motor_pub;
ros::Publisher left_motor_pub;

// robot's index in ROS ecosystem (if multiple instances)
int robot_id = 0;
double WHEELS_HALF_SPACING = 0;
double WHEEL_RADIUS = 0.1;

void callback_val(const geometry_msgs::Twist::ConstPtr &msg) {

  // creating new message
  std_msgs::Float64 msg_right_;
  std_msgs::Float64 msg_left_;
  double yaw = 0;

  if (msg.get()->angular.z < -0.0001 || msg.get()->angular.z > 0.0001)
    yaw = msg.get()->angular.z;
  else if (msg.get()->linear.y < -0.0001 || msg.get()->linear.y > 0.0001) {
    // yaw is not set-- trying to calculate from linear x and y
    ROS_WARN("DPL: in Twist msg no yaw component");
    yaw = std::atan2(msg.get()->linear.y, msg.get()->linear.x);
  }

  // calculate from linear x and yaw speed for each wheel
  msg_right_.data =
      (msg.get()->linear.x + WHEELS_HALF_SPACING * yaw) / WHEEL_RADIUS;
  msg_left_.data =
      (msg.get()->linear.x - WHEELS_HALF_SPACING * yaw) / WHEEL_RADIUS;
  // publishing wheel velocities
  right_motor_pub.publish(move(msg_right_));
  left_motor_pub.publish(move(msg_left_));
}

int main(int argc, char **argv) {
  std::string pub_right_ = "hal/rightMotor/setVel";
  std::string pub_left_ = "hal/leftMotor/setVel";
  std::string sub_twist = "/cmd_vel";
  ros::init(argc, argv, "motorControl");

  // read  from command line names of topics to publish data
  if (argc >= 3) {
    std::vector<std::string> argv_(argv + 1, argv + argc);
    pub_right_ = argv_[0];
    pub_left_ = argv_[1];
    if(argc==4) sub_twist = argv_[2];
  }
  // set relative node namespace
  ros::NodeHandle n;
  n.getParam("robot_id", robot_id);

  // tf listener for calculation of wheel spacing
  tf::TransformListener listener;
  tf::StampedTransform transform;
  // get length in between wheels
  try {
    listener.waitForTransform(std::to_string(robot_id) + "/base/joint1",
                              std::to_string(robot_id) + "/base/joint0",
                              ros::Time::now(), ros::Duration(3.0));
    listener.lookupTransform(std::to_string(robot_id) + "/base/joint1",
                             std::to_string(robot_id) + "/base/joint0",
                             ros::Time(0), transform);
    WHEELS_HALF_SPACING = transform.getOrigin().absolute().getY() / 2;
    ROS_INFO("DPL: motor_controler WHEELS_HALF_SPACING: %f",
             WHEELS_HALF_SPACING);

  } catch (tf::TransformException ex) {
    ROS_ERROR("Problem with transformation between wheels: %s", ex.what());
  }

  // read msg from standard ROS topic for receiving Twist commands
  ros::Subscriber twist_sub = n.subscribe(sub_twist, 1000, callback_val);

  right_motor_pub = n.advertise<std_msgs::Float64>(pub_right_, 1000);
  left_motor_pub = n.advertise<std_msgs::Float64>(pub_left_, 1000);
  ROS_INFO("DPL: motor_controler node initialized");

  // run event loop
  ros::spin();
  return 0;
}
#endif
<|endoftext|>