<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 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 "subcomponentmanager.h"
#include "metainfo.h"

#include <QDir>
#include <QMetaType>
#include <QUrl>
#include <QDeclarativeEngine>
#include <private/qdeclarativemetatype_p.h>
#include <QFileSystemWatcher>
#include <private/qdeclarativedom_p.h>

enum { debug = false };

QT_BEGIN_NAMESPACE

// Allow usage of QFileInfo in hash / qSort

static bool operator<(const QFileInfo &file1, const QFileInfo &file2)
{
    return file1.filePath() < file2.filePath();
}

static uint qHash(const QFileInfo &fileInfo)
{
    return qHash(fileInfo.filePath());
}

QT_END_NAMESPACE

namespace QmlDesigner {

namespace Internal {

static const QString QMLFILEPATTERN = QString(QLatin1String("*.qml"));

class SubComponentManagerPrivate : QObject {
    Q_OBJECT
public:
    SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q);

    void addImport(int pos, const QDeclarativeDomImport &import);
    void removeImport(int pos);
    void parseDirectories();

public slots:
    void parseDirectory(const QString &dirPath);
    void parseFile(const QString &filePath);

public:
    QList<QFileInfo> watchedFiles(const QDir &dirInfo);
    void unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier);
    void registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document);

    SubComponentManager *m_q;

    MetaInfo m_metaInfo;
    QDeclarativeEngine m_engine;

    QFileSystemWatcher m_watcher;

    QMultiHash<QFileInfo,QString> m_dirToQualifier;

    QUrl m_filePath;

    QList<QDeclarativeDomImport> m_imports;
};

SubComponentManagerPrivate::SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q) :
        m_q(q),
        m_metaInfo(metaInfo)
{
    connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));
    connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(parseFile(QString)));
}

void SubComponentManagerPrivate::addImport(int pos, const QDeclarativeDomImport &import)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << pos << import.uri();

    if (import.type() == QDeclarativeDomImport::File) {
        QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());
        if (dirInfo.exists() && dirInfo.isDir()) {
            m_watcher.addPath(dirInfo.filePath());
            m_dirToQualifier.insertMulti(dirInfo, import.qualifier());
        }
    } else {
        // TODO: QDeclarativeDomImport::Library
    }

    m_imports.insert(pos, import);
}

void SubComponentManagerPrivate::removeImport(int pos)
{
    const QDeclarativeDomImport import = m_imports.takeAt(pos);

    if (import.type() == QDeclarativeDomImport::File) {
        QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());

        m_dirToQualifier.remove(dirInfo, import.qualifier());

        if (!m_dirToQualifier.contains(dirInfo))
            m_watcher.removePath(dirInfo.filePath());

        foreach (const QFileInfo &monitoredFile, watchedFiles(dirInfo.filePath())) {
            if (!m_dirToQualifier.contains(dirInfo))
                m_watcher.removePath(monitoredFile.filePath());
            unregisterQmlFile(monitoredFile, import.qualifier());
        }
    } else {
            // TODO: QDeclarativeDomImport::Library
    }
}

void SubComponentManagerPrivate::parseDirectories()
{
    if (!m_filePath.isEmpty()) {
        const QString file = m_filePath.toLocalFile();
        QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
        if (dirInfo.exists() && dirInfo.isDir())
            parseDirectory(dirInfo.filePath());
    }

    foreach (const QDeclarativeDomImport &import, m_imports) {
        if (import.type() == QDeclarativeDomImport::File) {
            QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());
            if (dirInfo.exists() && dirInfo.isDir()) {
                parseDirectory(dirInfo.filePath());
            }
        }
    }
}

void SubComponentManagerPrivate::parseDirectory(const QString &dirPath)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << dirPath;

    QDir dir(dirPath);

    dir.setNameFilters(QStringList(QMLFILEPATTERN));
    dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);

    QList<QFileInfo> monitoredList = watchedFiles(dir);
    QList<QFileInfo> newList;
    foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {
        if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {
            // do not parse main file
            continue;
        }
        if (!qmlFile.fileName().at(0).isUpper()) {
            // Qml sub components must be upper case
            continue;
        }
        newList << qmlFile;
    }

    qSort(monitoredList);
    qSort(newList);

    if (debug)
        qDebug() << "monitored list " << monitoredList.size() << "new list " << newList.size();
    QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();
    QList<QFileInfo>::const_iterator newIter = newList.constBegin();

    while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {
        const QFileInfo oldFileInfo = *oldIter;
        const QFileInfo newFileInfo = *newIter;
        if (oldFileInfo == newFileInfo) {
            ++oldIter;
            ++newIter;
            continue;
        }
        if (oldFileInfo < newFileInfo) {
            foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))
                unregisterQmlFile(oldFileInfo, qualifier);
            m_watcher.removePath(oldFileInfo.filePath());
            ++oldIter;
            continue;
        }
        // oldFileInfo > newFileInfo
        parseFile(newFileInfo.filePath());
        m_watcher.addPath(oldFileInfo.filePath());
        ++newIter;
    }

    while (oldIter != monitoredList.constEnd()) {
        foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))
            unregisterQmlFile(*oldIter, qualifier);
        m_watcher.removePath(oldIter->filePath());
        ++oldIter;
    }

    while (newIter != newList.constEnd()) {
        parseFile(newIter->filePath());
        if (debug)
            qDebug() << "m_watcher.addPath(" << newIter->filePath() << ')';
        m_watcher.addPath(newIter->filePath());
        ++newIter;
    }
}

void SubComponentManagerPrivate::parseFile(const QString &filePath)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << filePath;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    QDeclarativeDomDocument document;
    if (!document.load(&m_engine, file.readAll(), QUrl::fromLocalFile(filePath))) {
        // TODO: Put the errors somewhere?
        qWarning() << "Could not load qml file " << filePath;
        return;
    }

    QFileInfo dir = QFileInfo(filePath).absolutePath();
    foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
        registerQmlFile(filePath, qualifier, document);
    }
}

QList<QFileInfo> SubComponentManagerPrivate::watchedFiles(const QDir &dirInfo)
{
    QList<QFileInfo> files;

    const QString dirPath = dirInfo.absolutePath();
    foreach (const QString &monitoredFile, m_watcher.files()) {
        QFileInfo fileInfo(monitoredFile);
        if (fileInfo.dir().absolutePath() == dirPath) {
            files.append(fileInfo);
        }
    }
    return files;
}

void SubComponentManagerPrivate::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)
{
    QString componentName = fileInfo.baseName();
    if (!qualifier.isEmpty())
        componentName = qualifier + '/' + componentName;

    if (m_metaInfo.hasNodeMetaInfo(componentName)) {
        NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);
        m_metaInfo.removeNodeInfo(nodeInfo);
    }
}

void SubComponentManagerPrivate::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document)
{
    QString componentName = fileInfo.baseName();
    if (!qualifier.isEmpty())
        componentName = qualifier + '/' + componentName;

    if (debug)
        qDebug() << "SubComponentManager" << __FUNCTION__ << componentName;

    if (m_metaInfo.hasNodeMetaInfo(componentName)) {
        NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);
        m_metaInfo.removeNodeInfo(nodeInfo);
    }

    const QDeclarativeDomObject rootObject = document.rootObject();

    const QString baseType = document.rootObject().objectType();
    Q_ASSERT_X(!baseType.isEmpty(), Q_FUNC_INFO, "Type of root object cannot be empty");

    NodeMetaInfo nodeInfo(m_metaInfo);
    nodeInfo.setTypeName(componentName);
    nodeInfo.setQmlFile(fileInfo.filePath());

    // Add file components to the library
    nodeInfo.setCategory(tr("Qml Component"));
    nodeInfo.setIsVisibleToItemLibrary(true);

    m_metaInfo.addItemLibraryInfo(nodeInfo, componentName);
    m_metaInfo.addNodeInfo(nodeInfo, baseType);

    foreach (const QDeclarativeDomDynamicProperty &dynamicProperty, document.rootObject().dynamicProperties()) {
        Q_ASSERT(!dynamicProperty.propertyName().isEmpty());
        Q_ASSERT(!dynamicProperty.propertyTypeName().isEmpty());

        PropertyMetaInfo propertyMetaInfo;
        propertyMetaInfo.setName(dynamicProperty.propertyName());
        propertyMetaInfo.setType(dynamicProperty.propertyTypeName());
        propertyMetaInfo.setValid(true);
        propertyMetaInfo.setReadable(true);
        propertyMetaInfo.setWritable(true);

        QDeclarativeDomProperty defaultValue = dynamicProperty.defaultValue();
        if (defaultValue.value().isLiteral()) {
            QVariant defaultValueVariant(defaultValue.value().toLiteral().literal());
            defaultValueVariant.convert((QVariant::Type) dynamicProperty.propertyType());
            propertyMetaInfo.setDefaultValue(nodeInfo, defaultValueVariant);
        }

        nodeInfo.addProperty(propertyMetaInfo);
    }
}

} // namespace Internal

/*!
  \class SubComponentManager

  Detects & monitors (potential) component files in a list of directories, and registers
  these in the metatype system.
*/

SubComponentManager::SubComponentManager(MetaInfo metaInfo, QObject *parent) :
        QObject(parent),
        m_d(new Internal::SubComponentManagerPrivate(metaInfo, this))
{
}

SubComponentManager::~SubComponentManager()
{
    delete m_d;
}

QStringList SubComponentManager::directories() const
{
    return m_d->m_watcher.directories();
}

QStringList SubComponentManager::qmlFiles() const
{
    return m_d->m_watcher.files();
}

static bool importEqual(const QDeclarativeDomImport &import1, const QDeclarativeDomImport &import2)
{
    return import1.type() == import2.type()
           && import1.uri() == import2.uri()
           && import1.version() == import2.version()
           && import1.qualifier() == import2.qualifier();
}

void SubComponentManager::update(const QUrl &filePath, const QByteArray &data)
{
    QDeclarativeEngine engine;
    QDeclarativeDomDocument document;

    QList<QDeclarativeDomImport> imports;
    if (document.load(&engine, data, filePath))
        imports = document.imports();

    update(filePath, imports);
}

void SubComponentManager::update(const QUrl &filePath, const QList<QDeclarativeDomImport> &imports)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << filePath << imports.size();

    QFileInfo oldDir, newDir;

    if (!m_d->m_filePath.isEmpty()) {
        const QString file = m_d->m_filePath.toLocalFile();
        oldDir = QFileInfo(QFileInfo(file).path());
    }
    if (!filePath.isEmpty()) {
        const QString file = filePath.toLocalFile();
        newDir = QFileInfo(QFileInfo(file).path());
    }

    m_d->m_filePath = filePath;

    //
    // (implicit) import of local directory
    //
    if (oldDir != newDir) {
        if (!oldDir.filePath().isEmpty()) {
            m_d->m_dirToQualifier.remove(oldDir, QString());
            if (!m_d->m_dirToQualifier.contains(oldDir))
                m_d->m_watcher.removePath(oldDir.filePath());
        }

        if (!newDir.filePath().isEmpty()) {
            m_d->m_watcher.addPath(newDir.filePath());
            m_d->m_dirToQualifier.insertMulti(newDir, QString());
        }
    }

    //
    // Imports
    //

    // skip first list items until the lists differ
    int i = 0;
    while (i < qMin(imports.size(), m_d->m_imports.size())) {
        if (!importEqual(imports.at(i), m_d->m_imports.at(i)))
            break;
        ++i;
    }

    for (int ii = m_d->m_imports.size() - 1; ii >= i; --ii)
        m_d->removeImport(ii);

    for (int ii = i; ii < imports.size(); ++ii) {
        m_d->addImport(ii, imports.at(ii));
    }

    m_d->parseDirectories();
}

} // namespace QmlDesigner

#include "subcomponentmanager.moc"
<commit_msg>QmlDesigner.MetaInfo:  renamed subcomponents group<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 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 "subcomponentmanager.h"
#include "metainfo.h"

#include <QDir>
#include <QMetaType>
#include <QUrl>
#include <QDeclarativeEngine>
#include <private/qdeclarativemetatype_p.h>
#include <QFileSystemWatcher>
#include <private/qdeclarativedom_p.h>

enum { debug = false };

QT_BEGIN_NAMESPACE

// Allow usage of QFileInfo in hash / qSort

static bool operator<(const QFileInfo &file1, const QFileInfo &file2)
{
    return file1.filePath() < file2.filePath();
}

static uint qHash(const QFileInfo &fileInfo)
{
    return qHash(fileInfo.filePath());
}

QT_END_NAMESPACE

namespace QmlDesigner {

namespace Internal {

static const QString QMLFILEPATTERN = QString(QLatin1String("*.qml"));

class SubComponentManagerPrivate : QObject {
    Q_OBJECT
public:
    SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q);

    void addImport(int pos, const QDeclarativeDomImport &import);
    void removeImport(int pos);
    void parseDirectories();

public slots:
    void parseDirectory(const QString &dirPath);
    void parseFile(const QString &filePath);

public:
    QList<QFileInfo> watchedFiles(const QDir &dirInfo);
    void unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier);
    void registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document);

    SubComponentManager *m_q;

    MetaInfo m_metaInfo;
    QDeclarativeEngine m_engine;

    QFileSystemWatcher m_watcher;

    QMultiHash<QFileInfo,QString> m_dirToQualifier;

    QUrl m_filePath;

    QList<QDeclarativeDomImport> m_imports;
};

SubComponentManagerPrivate::SubComponentManagerPrivate(MetaInfo metaInfo, SubComponentManager *q) :
        m_q(q),
        m_metaInfo(metaInfo)
{
    connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));
    connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(parseFile(QString)));
}

void SubComponentManagerPrivate::addImport(int pos, const QDeclarativeDomImport &import)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << pos << import.uri();

    if (import.type() == QDeclarativeDomImport::File) {
        QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());
        if (dirInfo.exists() && dirInfo.isDir()) {
            m_watcher.addPath(dirInfo.filePath());
            m_dirToQualifier.insertMulti(dirInfo, import.qualifier());
        }
    } else {
        // TODO: QDeclarativeDomImport::Library
    }

    m_imports.insert(pos, import);
}

void SubComponentManagerPrivate::removeImport(int pos)
{
    const QDeclarativeDomImport import = m_imports.takeAt(pos);

    if (import.type() == QDeclarativeDomImport::File) {
        QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());

        m_dirToQualifier.remove(dirInfo, import.qualifier());

        if (!m_dirToQualifier.contains(dirInfo))
            m_watcher.removePath(dirInfo.filePath());

        foreach (const QFileInfo &monitoredFile, watchedFiles(dirInfo.filePath())) {
            if (!m_dirToQualifier.contains(dirInfo))
                m_watcher.removePath(monitoredFile.filePath());
            unregisterQmlFile(monitoredFile, import.qualifier());
        }
    } else {
            // TODO: QDeclarativeDomImport::Library
    }
}

void SubComponentManagerPrivate::parseDirectories()
{
    if (!m_filePath.isEmpty()) {
        const QString file = m_filePath.toLocalFile();
        QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
        if (dirInfo.exists() && dirInfo.isDir())
            parseDirectory(dirInfo.filePath());
    }

    foreach (const QDeclarativeDomImport &import, m_imports) {
        if (import.type() == QDeclarativeDomImport::File) {
            QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.uri()).toLocalFile());
            if (dirInfo.exists() && dirInfo.isDir()) {
                parseDirectory(dirInfo.filePath());
            }
        }
    }
}

void SubComponentManagerPrivate::parseDirectory(const QString &dirPath)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << dirPath;

    QDir dir(dirPath);

    dir.setNameFilters(QStringList(QMLFILEPATTERN));
    dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);

    QList<QFileInfo> monitoredList = watchedFiles(dir);
    QList<QFileInfo> newList;
    foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {
        if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {
            // do not parse main file
            continue;
        }
        if (!qmlFile.fileName().at(0).isUpper()) {
            // Qml sub components must be upper case
            continue;
        }
        newList << qmlFile;
    }

    qSort(monitoredList);
    qSort(newList);

    if (debug)
        qDebug() << "monitored list " << monitoredList.size() << "new list " << newList.size();
    QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();
    QList<QFileInfo>::const_iterator newIter = newList.constBegin();

    while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {
        const QFileInfo oldFileInfo = *oldIter;
        const QFileInfo newFileInfo = *newIter;
        if (oldFileInfo == newFileInfo) {
            ++oldIter;
            ++newIter;
            continue;
        }
        if (oldFileInfo < newFileInfo) {
            foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))
                unregisterQmlFile(oldFileInfo, qualifier);
            m_watcher.removePath(oldFileInfo.filePath());
            ++oldIter;
            continue;
        }
        // oldFileInfo > newFileInfo
        parseFile(newFileInfo.filePath());
        m_watcher.addPath(oldFileInfo.filePath());
        ++newIter;
    }

    while (oldIter != monitoredList.constEnd()) {
        foreach (const QString &qualifier, m_dirToQualifier.value(dirPath))
            unregisterQmlFile(*oldIter, qualifier);
        m_watcher.removePath(oldIter->filePath());
        ++oldIter;
    }

    while (newIter != newList.constEnd()) {
        parseFile(newIter->filePath());
        if (debug)
            qDebug() << "m_watcher.addPath(" << newIter->filePath() << ')';
        m_watcher.addPath(newIter->filePath());
        ++newIter;
    }
}

void SubComponentManagerPrivate::parseFile(const QString &filePath)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << filePath;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    QDeclarativeDomDocument document;
    if (!document.load(&m_engine, file.readAll(), QUrl::fromLocalFile(filePath))) {
        // TODO: Put the errors somewhere?
        qWarning() << "Could not load qml file " << filePath;
        return;
    }

    QFileInfo dir = QFileInfo(filePath).absolutePath();
    foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
        registerQmlFile(filePath, qualifier, document);
    }
}

QList<QFileInfo> SubComponentManagerPrivate::watchedFiles(const QDir &dirInfo)
{
    QList<QFileInfo> files;

    const QString dirPath = dirInfo.absolutePath();
    foreach (const QString &monitoredFile, m_watcher.files()) {
        QFileInfo fileInfo(monitoredFile);
        if (fileInfo.dir().absolutePath() == dirPath) {
            files.append(fileInfo);
        }
    }
    return files;
}

void SubComponentManagerPrivate::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)
{
    QString componentName = fileInfo.baseName();
    if (!qualifier.isEmpty())
        componentName = qualifier + '/' + componentName;

    if (m_metaInfo.hasNodeMetaInfo(componentName)) {
        NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);
        m_metaInfo.removeNodeInfo(nodeInfo);
    }
}

void SubComponentManagerPrivate::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier, const QDeclarativeDomDocument &document)
{
    QString componentName = fileInfo.baseName();
    if (!qualifier.isEmpty())
        componentName = qualifier + '/' + componentName;

    if (debug)
        qDebug() << "SubComponentManager" << __FUNCTION__ << componentName;

    if (m_metaInfo.hasNodeMetaInfo(componentName)) {
        NodeMetaInfo nodeInfo = m_metaInfo.nodeMetaInfo(componentName);
        m_metaInfo.removeNodeInfo(nodeInfo);
    }

    const QDeclarativeDomObject rootObject = document.rootObject();

    const QString baseType = document.rootObject().objectType();
    Q_ASSERT_X(!baseType.isEmpty(), Q_FUNC_INFO, "Type of root object cannot be empty");

    NodeMetaInfo nodeInfo(m_metaInfo);
    nodeInfo.setTypeName(componentName);
    nodeInfo.setQmlFile(fileInfo.filePath());

    // Add file components to the library
    nodeInfo.setCategory(tr("Qml Components"));
    nodeInfo.setIsVisibleToItemLibrary(true);

    m_metaInfo.addItemLibraryInfo(nodeInfo, componentName);
    m_metaInfo.addNodeInfo(nodeInfo, baseType);

    foreach (const QDeclarativeDomDynamicProperty &dynamicProperty, document.rootObject().dynamicProperties()) {
        Q_ASSERT(!dynamicProperty.propertyName().isEmpty());
        Q_ASSERT(!dynamicProperty.propertyTypeName().isEmpty());

        PropertyMetaInfo propertyMetaInfo;
        propertyMetaInfo.setName(dynamicProperty.propertyName());
        propertyMetaInfo.setType(dynamicProperty.propertyTypeName());
        propertyMetaInfo.setValid(true);
        propertyMetaInfo.setReadable(true);
        propertyMetaInfo.setWritable(true);

        QDeclarativeDomProperty defaultValue = dynamicProperty.defaultValue();
        if (defaultValue.value().isLiteral()) {
            QVariant defaultValueVariant(defaultValue.value().toLiteral().literal());
            defaultValueVariant.convert((QVariant::Type) dynamicProperty.propertyType());
            propertyMetaInfo.setDefaultValue(nodeInfo, defaultValueVariant);
        }

        nodeInfo.addProperty(propertyMetaInfo);
    }
}

} // namespace Internal

/*!
  \class SubComponentManager

  Detects & monitors (potential) component files in a list of directories, and registers
  these in the metatype system.
*/

SubComponentManager::SubComponentManager(MetaInfo metaInfo, QObject *parent) :
        QObject(parent),
        m_d(new Internal::SubComponentManagerPrivate(metaInfo, this))
{
}

SubComponentManager::~SubComponentManager()
{
    delete m_d;
}

QStringList SubComponentManager::directories() const
{
    return m_d->m_watcher.directories();
}

QStringList SubComponentManager::qmlFiles() const
{
    return m_d->m_watcher.files();
}

static bool importEqual(const QDeclarativeDomImport &import1, const QDeclarativeDomImport &import2)
{
    return import1.type() == import2.type()
           && import1.uri() == import2.uri()
           && import1.version() == import2.version()
           && import1.qualifier() == import2.qualifier();
}

void SubComponentManager::update(const QUrl &filePath, const QByteArray &data)
{
    QDeclarativeEngine engine;
    QDeclarativeDomDocument document;

    QList<QDeclarativeDomImport> imports;
    if (document.load(&engine, data, filePath))
        imports = document.imports();

    update(filePath, imports);
}

void SubComponentManager::update(const QUrl &filePath, const QList<QDeclarativeDomImport> &imports)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << filePath << imports.size();

    QFileInfo oldDir, newDir;

    if (!m_d->m_filePath.isEmpty()) {
        const QString file = m_d->m_filePath.toLocalFile();
        oldDir = QFileInfo(QFileInfo(file).path());
    }
    if (!filePath.isEmpty()) {
        const QString file = filePath.toLocalFile();
        newDir = QFileInfo(QFileInfo(file).path());
    }

    m_d->m_filePath = filePath;

    //
    // (implicit) import of local directory
    //
    if (oldDir != newDir) {
        if (!oldDir.filePath().isEmpty()) {
            m_d->m_dirToQualifier.remove(oldDir, QString());
            if (!m_d->m_dirToQualifier.contains(oldDir))
                m_d->m_watcher.removePath(oldDir.filePath());
        }

        if (!newDir.filePath().isEmpty()) {
            m_d->m_watcher.addPath(newDir.filePath());
            m_d->m_dirToQualifier.insertMulti(newDir, QString());
        }
    }

    //
    // Imports
    //

    // skip first list items until the lists differ
    int i = 0;
    while (i < qMin(imports.size(), m_d->m_imports.size())) {
        if (!importEqual(imports.at(i), m_d->m_imports.at(i)))
            break;
        ++i;
    }

    for (int ii = m_d->m_imports.size() - 1; ii >= i; --ii)
        m_d->removeImport(ii);

    for (int ii = i; ii < imports.size(); ++ii) {
        m_d->addImport(ii, imports.at(ii));
    }

    m_d->parseDirectories();
}

} // namespace QmlDesigner

#include "subcomponentmanager.moc"
<|endoftext|>


<commit_before>// ROS Libraries
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
// Standard Libraries
#include <stdlib.h>
#include <math.h>

float linear_x_button=0;
float angular_z_button=0;
float linear_x_stick=0;
float angular_z_stick=0;

// Defines
#define Joystick_Stick_Left_Right msg->axes[4]
#define Joystick_Stick_Up_Down msg->axes[5]
#define Joystick_Button_Left_Right msg->axes[0]
#define Joystick_Button_Up_Down msg->axes[1]

// Callback Functions
void Joy_Callback (const sensor_msgs::Joy::ConstPtr& msg)
{
//  for (unsigned i = 0; i < msg->axes.size(); ++i) {
//      ROS_INFO("Axis %d is now at position %f", i, msg->axes[i]);
//  }

    // Test if joystick buttons are pressed?
    if (Joystick_Button_Left_Right>0) {
        angular_z_button=Joystick_Button_Left_Right;
    }
    if (Joystick_Button_Left_Right<0) {
        angular_z_button=Joystick_Button_Left_Right;
    }
    if (Joystick_Button_Up_Down>0) {
        linear_x_button=Joystick_Button_Up_Down/5;
    }
    if (Joystick_Button_Up_Down<0) {
        linear_x_button=Joystick_Button_Up_Down/5;
    }
    if (Joystick_Button_Up_Down==0) {
        linear_x_button=Joystick_Button_Up_Down;
    }
    if (Joystick_Button_Left_Right==0) {
        angular_z_button=Joystick_Button_Left_Right;
    }

    // Test if joystick stick is pressed?
    if (Joystick_Stick_Left_Right>0) {
        angular_z_stick=Joystick_Stick_Left_Right;
    }
    if (Joystick_Stick_Left_Right<0) {
        angular_z_stick=Joystick_Stick_Left_Right;
    }
    if (Joystick_Stick_Up_Down>0) {
        linear_x_stick=Joystick_Stick_Up_Down/5;
    }
    if (Joystick_Stick_Up_Down<0) {
        linear_x_stick=Joystick_Stick_Up_Down/5;
    }
    if (Joystick_Stick_Up_Down==0) {
        linear_x_stick=Joystick_Stick_Up_Down;
    }
    if (Joystick_Stick_Left_Right==0) {
        angular_z_stick=Joystick_Stick_Left_Right;
    }

}

void onExit( void )
{
    // Run cleanup code here!
    ROS_INFO("joystick_teleop: Exit node");
}

int main(int argc, char **argv)
{
  atexit(onExit);
  ros::init(argc, argv, "joystick_teleop");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("joy", 100, Joy_Callback);
  ros::Publisher cmd_vel_pub = n.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
  ros::Rate loop_rate(20);                                                  //Sets the loop to publish at a rate of 10Hz
  geometry_msgs::Twist cmd_vel_msg;                                         //Declares the message to be sent
  while (n.ok()){

    if ((cmd_vel_msg.linear.x != linear_x_button) || (cmd_vel_msg.angular.z != angular_z_button)){
      cmd_vel_msg.linear.x=linear_x_button;
      cmd_vel_msg.angular.z=angular_z_button;
      cmd_vel_pub.publish(cmd_vel_msg);
      ROS_INFO("linear.x = %f angular.z = %f",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);
    }
    if ((cmd_vel_msg.linear.x != linear_x_stick) || (cmd_vel_msg.angular.z != angular_z_stick)){
      cmd_vel_msg.linear.x=linear_x_stick;
      cmd_vel_msg.angular.z=angular_z_stick;
      cmd_vel_pub.publish(cmd_vel_msg);
      ROS_INFO("linear.x = %f angular.z = %f",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);
    }

    ros::spinOnce();
    loop_rate.sleep();
  }//end.mainloop
  return 0;
}//end.main

<commit_msg>UPDATE joystick_teleop_node.cpp: Node is now continously sending cmd_vel messages if button or stick is pressed<commit_after>// ROS Libraries
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
// Standard Libraries
#include <stdlib.h>
#include <math.h>

float linear_x_button=0;
float angular_z_button=0;
float linear_x_stick=0;
float angular_z_stick=0;

bool stick_used=false;
bool button_used=false;

// Defines
#define Joystick_Stick_Left_Right msg->axes[4]
#define Joystick_Stick_Up_Down msg->axes[5]
#define Joystick_Button_Left_Right msg->axes[0]
#define Joystick_Button_Up_Down msg->axes[1]

// Callback Functions
void Joy_Callback (const sensor_msgs::Joy::ConstPtr& msg)
{
//  for (unsigned i = 0; i < msg->axes.size(); ++i) {
//      ROS_INFO("Axis %d is now at position %f", i, msg->axes[i]);
//  }

    // Test if joystick buttons are pressed?
    if (Joystick_Button_Left_Right>0) {
        angular_z_button=Joystick_Button_Left_Right;
        button_used = true;
    }
    if (Joystick_Button_Left_Right<0) {
        angular_z_button=Joystick_Button_Left_Right;
        button_used = true;
    }
    if (Joystick_Button_Up_Down>0) {
        linear_x_button=Joystick_Button_Up_Down/5;
        button_used = true;
    }
    if (Joystick_Button_Up_Down<0) {
        linear_x_button=Joystick_Button_Up_Down/5;
        button_used = true;
    }
    if (Joystick_Button_Up_Down==0) {
        linear_x_button=Joystick_Button_Up_Down;
        button_used = true;
    }
    if (Joystick_Button_Left_Right==0) {
        angular_z_button=Joystick_Button_Left_Right;
        button_used = true;
    }
    if ((Joystick_Button_Left_Right==0) && (Joystick_Button_Up_Down==0))
    {
        button_used=false;
    }

    // Test if joystick stick is pressed?
    if (Joystick_Stick_Left_Right>0) {
        angular_z_stick=Joystick_Stick_Left_Right;
        stick_used = true;
    }
    if (Joystick_Stick_Left_Right<0) {
        angular_z_stick=Joystick_Stick_Left_Right;
        stick_used = true;
    }
    if (Joystick_Stick_Up_Down>0) {
        linear_x_stick=Joystick_Stick_Up_Down/5;
        stick_used = true;
    }
    if (Joystick_Stick_Up_Down<0) {
        linear_x_stick=Joystick_Stick_Up_Down/5;
        stick_used = true;
    }
    if (Joystick_Stick_Up_Down==0) {
        linear_x_stick=Joystick_Stick_Up_Down;
        stick_used = true;
    }
    if (Joystick_Stick_Left_Right==0) {
        angular_z_stick=Joystick_Stick_Left_Right;
        stick_used = true;
    }
     if ((Joystick_Stick_Left_Right==0) && (Joystick_Stick_Up_Down==0))
     {
         stick_used=false;
     }

}

void onExit( void )
{
    // Run cleanup code here!
    ROS_INFO("joystick_teleop: Exit node");
}

int main(int argc, char **argv)
{
  atexit(onExit);
  ros::init(argc, argv, "joystick_teleop");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("joy", 100, Joy_Callback);
  ros::Publisher cmd_vel_pub = n.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
  ros::Rate loop_rate(20);                                                  //Sets the loop to publish at a rate of 10Hz
  geometry_msgs::Twist cmd_vel_msg;                                         //Declares the message to be sent
  bool publish_cmd_vel=false;

  while (ros::ok()){

    if (button_used==true && stick_used==false){
      cmd_vel_msg.linear.x=linear_x_button;
      cmd_vel_msg.angular.z=angular_z_button;
      cmd_vel_pub.publish(cmd_vel_msg);
      ROS_INFO("linear.x = %f angular.z = %f",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);
      publish_cmd_vel = true;
    }
    if (stick_used==true && button_used==false){
      cmd_vel_msg.linear.x=linear_x_stick;
      cmd_vel_msg.angular.z=angular_z_stick;
      cmd_vel_pub.publish(cmd_vel_msg);
      ROS_INFO("linear.x = %f angular.z = %f",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);
      publish_cmd_vel = true;
    }
    // If nor button or stick is pressed, send null-message to cmd_vel once
    if ((stick_used==false && button_used==false) && publish_cmd_vel==true){
        cmd_vel_msg.linear.x=0;
        cmd_vel_msg.angular.z =0;
        cmd_vel_pub.publish(cmd_vel_msg);
        ROS_INFO("linear.x = %f angular.z = %f",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);
        publish_cmd_vel = false;
    }

    ros::spinOnce();
    loop_rate.sleep();
  }//end.mainloop
  return 0;
}//end.main

<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_MATRIX
#define MFEM_MATRIX

#include "../general/array.hpp"
#include "../general/globals.hpp"
#include "operator.hpp"

namespace mfem
{

// Abstract data types matrix, inverse matrix

class MatrixInverse;

/// Abstract data type matrix
class Matrix : public Operator
{
   friend class MatrixInverse;
public:
   //// Defines matrix diagonal policy upon elimination of rows and/or columns.
   enum DiagonalPolicy
   {
      DIAG_ZERO, ///< Set the diagonal value to zero
      DIAG_ONE,  ///< Set the diagonal value to one
      DIAG_KEEP  ///< Keep the diagonal value
   };

   /// Creates a square matrix of size s.
   explicit Matrix(int s) : Operator(s) { }

   /// Creates a matrix of the given height and width.
   explicit Matrix(int h, int w) : Operator(h, w) { }

   /// Returns whether this matrix instanse is a square matrix.
   bool IsSquare() const { return (height==width); };

   /// Returns reference to a_{ij}.
   virtual double &Elem(int i, int j) = 0;

   /// Returns constant reference to a_{ij}.
   virtual const double &Elem(int i, int j) const = 0;

   /// Returns a pointer to (an approximation) of the matrix inverse.
   virtual MatrixInverse *Inverse() const = 0;

   /// Finalizes the matrix initialization.
   virtual void Finalize(int) { }

   /// Prints matrix to stream out.
   virtual void Print (std::ostream & out = mfem::out, int width_ = 4) const;

   /// Destroys matrix.
   virtual ~Matrix() { }
};

/// Abstract data type for matrix inverse
class MatrixInverse : public Solver
{
public:
   MatrixInverse() { }

   /// Creates approximation of the inverse of square matrix
   MatrixInverse(const Matrix &mat)
      : Solver(mat.height, mat.width) { }
};

/// Abstract data type for sparse matrices
class AbstractSparseMatrix : public Matrix
{
public:
   /// Creates a square matrix of the given size.
   explicit AbstractSparseMatrix(int s = 0) : Matrix(s) { }

   /// Creates a matrix of the given height and width.
   explicit AbstractSparseMatrix(int h, int w) : Matrix(h, w) { }

   /// Returns the number of non-zeros in a matrix
   virtual int NumNonZeroElems() const = 0;

   /// Gets the columns indexes and values for row *row*.
   /** Returns:
       - 0 if @a cols and @a srow are copies of the values in the matrix.
       - 1 if @a cols and @a srow are views of the values in the matrix. */
   virtual int GetRow(const int row, Array<int> &cols, Vector &srow) const = 0;

   /** @brief If the matrix is square, this method will place 1 on the diagonal
       (i,i) if row i has "almost" zero l1-norm.

       If entry (i,i) does not belong to the sparsity pattern of A, then an
       error will occur. */
   virtual void EliminateZeroRows(const double threshold = 1e-12) = 0;

   /// Matrix-Vector Multiplication y = A*x
   virtual void Mult(const Vector &x, Vector &y) const = 0;
   /// Matrix-Vector Multiplication y = y + val*A*x
   virtual void AddMult(const Vector &x, Vector &y,
                        const double val = 1.) const = 0;
   /// MatrixTranspose-Vector Multiplication y = A'*x
   virtual void MultTranspose(const Vector &x, Vector &y) const = 0;
   /// MatrixTranspose-Vector Multiplication y = y + val*A'*x
   virtual void AddMultTranspose(const Vector &x, Vector &y,
                                 const double val = 1.) const = 0;

   /// Destroys AbstractSparseMatrix.
   virtual ~AbstractSparseMatrix() { }
};

}

#endif
<commit_msg>DOC: fix typo in doxygen documentation<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_MATRIX
#define MFEM_MATRIX

#include "../general/array.hpp"
#include "../general/globals.hpp"
#include "operator.hpp"

namespace mfem
{

// Abstract data types matrix, inverse matrix

class MatrixInverse;

/// Abstract data type matrix
class Matrix : public Operator
{
   friend class MatrixInverse;
public:
   //// Defines matrix diagonal policy upon elimination of rows and/or columns.
   enum DiagonalPolicy
   {
      DIAG_ZERO, ///< Set the diagonal value to zero
      DIAG_ONE,  ///< Set the diagonal value to one
      DIAG_KEEP  ///< Keep the diagonal value
   };

   /// Creates a square matrix of size s.
   explicit Matrix(int s) : Operator(s) { }

   /// Creates a matrix of the given height and width.
   explicit Matrix(int h, int w) : Operator(h, w) { }

   /// Returns whether this matrix instance is a square matrix.
   bool IsSquare() const { return (height==width); };

   /// Returns reference to a_{ij}.
   virtual double &Elem(int i, int j) = 0;

   /// Returns constant reference to a_{ij}.
   virtual const double &Elem(int i, int j) const = 0;

   /// Returns a pointer to (an approximation) of the matrix inverse.
   virtual MatrixInverse *Inverse() const = 0;

   /// Finalizes the matrix initialization.
   virtual void Finalize(int) { }

   /// Prints matrix to stream out.
   virtual void Print (std::ostream & out = mfem::out, int width_ = 4) const;

   /// Destroys matrix.
   virtual ~Matrix() { }
};

/// Abstract data type for matrix inverse
class MatrixInverse : public Solver
{
public:
   MatrixInverse() { }

   /// Creates approximation of the inverse of square matrix
   MatrixInverse(const Matrix &mat)
      : Solver(mat.height, mat.width) { }
};

/// Abstract data type for sparse matrices
class AbstractSparseMatrix : public Matrix
{
public:
   /// Creates a square matrix of the given size.
   explicit AbstractSparseMatrix(int s = 0) : Matrix(s) { }

   /// Creates a matrix of the given height and width.
   explicit AbstractSparseMatrix(int h, int w) : Matrix(h, w) { }

   /// Returns the number of non-zeros in a matrix
   virtual int NumNonZeroElems() const = 0;

   /// Gets the columns indexes and values for row *row*.
   /** Returns:
       - 0 if @a cols and @a srow are copies of the values in the matrix.
       - 1 if @a cols and @a srow are views of the values in the matrix. */
   virtual int GetRow(const int row, Array<int> &cols, Vector &srow) const = 0;

   /** @brief If the matrix is square, this method will place 1 on the diagonal
       (i,i) if row i has "almost" zero l1-norm.

       If entry (i,i) does not belong to the sparsity pattern of A, then an
       error will occur. */
   virtual void EliminateZeroRows(const double threshold = 1e-12) = 0;

   /// Matrix-Vector Multiplication y = A*x
   virtual void Mult(const Vector &x, Vector &y) const = 0;
   /// Matrix-Vector Multiplication y = y + val*A*x
   virtual void AddMult(const Vector &x, Vector &y,
                        const double val = 1.) const = 0;
   /// MatrixTranspose-Vector Multiplication y = A'*x
   virtual void MultTranspose(const Vector &x, Vector &y) const = 0;
   /// MatrixTranspose-Vector Multiplication y = y + val*A'*x
   virtual void AddMultTranspose(const Vector &x, Vector &y,
                                 const double val = 1.) const = 0;

   /// Destroys AbstractSparseMatrix.
   virtual ~AbstractSparseMatrix() { }
};

}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <iostream>

#include "QXmppMessage.h"
#include "QXmppRosterManager.h"

#include "xmppClient.h"

xmppClient::xmppClient(QObject *parent)
    : QXmppClient(parent)
{
    bool check = connect(this, SIGNAL(connected()),
        SLOT(clientConnected()));
    Q_ASSERT(check);

    check = connect(&this->rosterManager(), SIGNAL(rosterReceived()),
        SLOT(rosterReceived()));
    Q_ASSERT(check);

    /// Then QXmppRoster::presenceChanged() is emitted whenever presence of someone
    /// in roster changes
    check = connect(&this->rosterManager(),
                    SIGNAL(presenceChanged(const QString&, const QString&)),
        SLOT(presenceChanged(const QString&, const QString&)));
    Q_ASSERT(check);
}

xmppClient::~xmppClient()
{

}

void xmppClient::clientConnected()
{
    std::cout<<"example_2_rosterHandling:: CONNECTED"<<std::endl;
}

void xmppClient::rosterReceived()
{
    std::cout<<"example_2_rosterHandling:: Roster Received"<<std::endl;
    QStringList list = rosterManager().getRosterBareJids();
    for(int i = 0; i < list.size(); ++i)
    {
        std::cout<<"Roster Received:: "<<qPrintable(list.at(i))<<std::endl;
    }
}

void xmppClient::presenceChanged(const QString& bareJid,
                                 const QString& resource)
{
    std::cout<<"Presence changed:: "<< qPrintable(bareJid)
            << qPrintable(resource)<<std::endl;
}
<commit_msg>display name also<commit_after>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <iostream>

#include "QXmppMessage.h"
#include "QXmppRosterManager.h"

#include "xmppClient.h"

xmppClient::xmppClient(QObject *parent)
    : QXmppClient(parent)
{
    bool check = connect(this, SIGNAL(connected()),
        SLOT(clientConnected()));
    Q_ASSERT(check);

    check = connect(&this->rosterManager(), SIGNAL(rosterReceived()),
        SLOT(rosterReceived()));
    Q_ASSERT(check);

    /// Then QXmppRoster::presenceChanged() is emitted whenever presence of someone
    /// in roster changes
    check = connect(&this->rosterManager(),
                    SIGNAL(presenceChanged(const QString&, const QString&)),
        SLOT(presenceChanged(const QString&, const QString&)));
    Q_ASSERT(check);
}

xmppClient::~xmppClient()
{

}

void xmppClient::clientConnected()
{
    std::cout<<"example_2_rosterHandling:: CONNECTED"<<std::endl;
}

void xmppClient::rosterReceived()
{
    std::cout<<"example_2_rosterHandling:: Roster Received"<<std::endl;
    QStringList list = rosterManager().getRosterBareJids();
    QString rosterEntry = "Roster Received:: %1 [%2]";
    for(int i = 0; i < list.size(); ++i)
    {
        QString bareJid = list.at(i);
        QString name = rosterManager().getRosterEntry(bareJid).name();
        if(name.isEmpty())
            name = "-";
        std::cout << qPrintable(rosterEntry.arg(bareJid).arg(name)) << std::endl;
    }
}

void xmppClient::presenceChanged(const QString& bareJid,
                                 const QString& resource)
{
    std::cout<<"Presence changed:: "<< qPrintable(bareJid)
            << qPrintable(resource)<<std::endl;
}
<|endoftext|>


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

// INTERNAL INCLUDES

#include "vertical-layout.h"
#include "emoji-strings.h"

// EXTERNAL INCLUDES
#include <dali-toolkit/dali-toolkit.h>
#include <dali/public-api/text-abstraction/text-abstraction.h>
#include <iostream>

using namespace Dali;
using namespace Dali::Toolkit;
using namespace EmojiStrings;

 // TODO Need to expose Text::RENDER.....
const int ATLAS_RENDERER = 0;

// This example shows how to create and display Hello World! using a simple TextActor
//
class EmojiExample : public ConnectionTracker
{
public:

  typedef uint32_t SizeType;

  EmojiExample( Application& application )
  : mApplication( application )
  {
    std::cout << "EmoticonController::EmoticonController" << std::endl;

    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &EmojiExample::Create );
  }

  ~EmojiExample()
  {
    // Nothing to do here;
  }

  // The Init signal is received once (only) during the Application lifetime
  void Create( Application& application )
  {

    mLayout = VerticalLayout::New();
    mLayout.SetParentOrigin( ParentOrigin::TOP_LEFT );
    mLayout.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    Stage stage = Stage::GetCurrent();
    stage.Add( mLayout );
    stage.KeyEventSignal().Connect(this, &EmojiExample::OnKeyEvent);

    for( unsigned int index = 0u; index < NUMBER_OF_EMOJIS; ++index )
    {
      const Emoji& emoji = EMOJIS[index];
      const std::string text = emoji.mUTF8 + " " + emoji.mDescription;
      TextLabel label = TextLabel::New();
      label.SetParentOrigin( ParentOrigin::TOP_CENTER );
      label.SetAnchorPoint( AnchorPoint::TOP_CENTER );
      label.SetProperty( TextLabel::Property::MULTI_LINE, true );
      label.SetProperty( TextLabel::Property::RENDERING_BACKEND, 0 );
      label.SetProperty( TextLabel::Property::TEXT, text );
      mLayout.AddLabel( label );
      mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );
    }

    const Vector2& size = stage.GetSize();
    const float height = mLayout.GetHeightForWidth( size.width );
    mLayout.SetSize( Size( size.width, height ) );
    mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );

  }

  bool OnTouchEvent( Actor actor, const TouchEvent& event )
  {
    if( 1u == event.GetPointCount() )
    {
      const TouchPoint::State state = event.GetPoint(0u).state;

      // Clamp to integer values; this is to reduce flicking due to pixel misalignment
      const float localPoint = static_cast<float>( static_cast<int>( event.GetPoint( 0 ).local.y ) );

      if( TouchPoint::Down == state )
      {
        mLastPoint = localPoint;
        mAnimation = Animation::New( 0.25f );
      }
      else if( TouchPoint::Motion == state )
      {
        if( mAnimation )
        {
          mAnimation.MoveBy( mLayout, Vector3( 0.f, localPoint - mLastPoint, 0.f ), AlphaFunctions::Linear );
          mAnimation.Play();
          mLastPoint = localPoint;
        }
      }
    }

    return true;
  }

  /**
   * Main key event handler
   */
  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) )
      {
        mApplication.Quit();
      }
    }
  }

private:
  Application&  mApplication;
  VerticalLayout mLayout;
  Animation      mAnimation;
  float          mLastPoint;
};

void RunTest( Application& application )
{
  EmojiExample test( application );

  application.MainLoop();
}

// Entry point for Linux & SLP applications
//
int main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv );

  RunTest( application );

  return 0;
}
<commit_msg>Text renderer not using default backend in emoji example<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// INTERNAL INCLUDES

#include "vertical-layout.h"
#include "emoji-strings.h"

// EXTERNAL INCLUDES
#include <dali-toolkit/dali-toolkit.h>
#include <dali/public-api/text-abstraction/text-abstraction.h>
#include <iostream>

using namespace Dali;
using namespace Dali::Toolkit;
using namespace EmojiStrings;

 // TODO Need to expose Text::RENDER.....
const int ATLAS_RENDERER = 0;

// This example shows how to create and display Hello World! using a simple TextActor
//
class EmojiExample : public ConnectionTracker
{
public:

  typedef uint32_t SizeType;

  EmojiExample( Application& application )
  : mApplication( application )
  {
    std::cout << "EmoticonController::EmoticonController" << std::endl;

    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &EmojiExample::Create );
  }

  ~EmojiExample()
  {
    // Nothing to do here;
  }

  // The Init signal is received once (only) during the Application lifetime
  void Create( Application& application )
  {

    mLayout = VerticalLayout::New();
    mLayout.SetParentOrigin( ParentOrigin::TOP_LEFT );
    mLayout.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    Stage stage = Stage::GetCurrent();
    stage.Add( mLayout );
    stage.KeyEventSignal().Connect(this, &EmojiExample::OnKeyEvent);

    for( unsigned int index = 0u; index < NUMBER_OF_EMOJIS; ++index )
    {
      const Emoji& emoji = EMOJIS[index];
      const std::string text = emoji.mUTF8 + " " + emoji.mDescription;
      TextLabel label = TextLabel::New();
      label.SetParentOrigin( ParentOrigin::TOP_CENTER );
      label.SetAnchorPoint( AnchorPoint::TOP_CENTER );
      label.SetProperty( TextLabel::Property::MULTI_LINE, true );
      label.SetProperty( TextLabel::Property::TEXT, text );
      mLayout.AddLabel( label );
      mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );
    }

    const Vector2& size = stage.GetSize();
    const float height = mLayout.GetHeightForWidth( size.width );
    mLayout.SetSize( Size( size.width, height ) );
    mLayout.TouchedSignal().Connect( this, &EmojiExample::OnTouchEvent );

  }

  bool OnTouchEvent( Actor actor, const TouchEvent& event )
  {
    if( 1u == event.GetPointCount() )
    {
      const TouchPoint::State state = event.GetPoint(0u).state;

      // Clamp to integer values; this is to reduce flicking due to pixel misalignment
      const float localPoint = static_cast<float>( static_cast<int>( event.GetPoint( 0 ).local.y ) );

      if( TouchPoint::Down == state )
      {
        mLastPoint = localPoint;
        mAnimation = Animation::New( 0.25f );
      }
      else if( TouchPoint::Motion == state )
      {
        if( mAnimation )
        {
          mAnimation.MoveBy( mLayout, Vector3( 0.f, localPoint - mLastPoint, 0.f ), AlphaFunctions::Linear );
          mAnimation.Play();
          mLastPoint = localPoint;
        }
      }
    }

    return true;
  }

  /**
   * Main key event handler
   */
  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) )
      {
        mApplication.Quit();
      }
    }
  }

private:
  Application&  mApplication;
  VerticalLayout mLayout;
  Animation      mAnimation;
  float          mLastPoint;
};

void RunTest( Application& application )
{
  EmojiExample test( application );

  application.MainLoop();
}

// Entry point for Linux & SLP applications
//
int main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv );

  RunTest( application );

  return 0;
}
<|endoftext|>


<commit_before>// =============================================================================
//
// Copyright (c) 2014 Brannon Dorsey <http://brannondorsey.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================

#include "EditorSettings.h"

namespace of {
namespace Sketch {

EditorSettings::EditorSettings(const std::string& path):
    _path(path)
{
    load();
    cout<<getProjectDir()<<endl;
}

bool EditorSettings::load()
{
    return _data.open(_path);
}

bool EditorSettings::save()
{
    return _data.save(_path);
}

const Json::Value& EditorSettings::getData() const
{
    return _data;
}

int EditorSettings::getPort() const
{
    return _data["port"].asInt();
}

std::string EditorSettings::getProjectDir() const
{
    return _data["projectDir"].asString();
}

std::string EditorSettings::getSketchDir() const
{
    return _data["sketchDir"].asString();
}

std::string EditorSettings::getAddonsDir() const
{
    return _data["addonsDir"].asString();
}

std::string EditorSettings::getOpenFrameworksDir() const
{
    return _data["openFrameworksDir"].asString();
}

std::string EditorSettings::getOpenFrameworksVersion() const
{
    return _data["openFrameworksVersion"].asString();
}

std::string EditorSettings::getProjectSettingsFilename() const
{
    return _data["projectSettingsFilename"].asString();
}

std::string EditorSettings::getProjectExtension() const
{
    return _data["projectExtension"].asString();
}

std::string EditorSettings::getClassExtension() const
{
    return _data["classExtension"].asString();
}

} } // namespace of::Sketch
<commit_msg>Cleanup.<commit_after>// =============================================================================
//
// Copyright (c) 2014 Brannon Dorsey <http://brannondorsey.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================

#include "EditorSettings.h"

namespace of {
namespace Sketch {

EditorSettings::EditorSettings(const std::string& path):
    _path(path)
{
    load();
    ofLogVerbose("EditorSettings::EditorSettings") << "Project Directory: " << getProjectDir();
}

bool EditorSettings::load()
{
    return _data.open(_path);
}

bool EditorSettings::save()
{
    return _data.save(_path);
}

const Json::Value& EditorSettings::getData() const
{
    return _data;
}

int EditorSettings::getPort() const
{
    return _data["port"].asInt();
}

std::string EditorSettings::getProjectDir() const
{
    return _data["projectDir"].asString();
}

std::string EditorSettings::getSketchDir() const
{
    return _data["sketchDir"].asString();
}

std::string EditorSettings::getAddonsDir() const
{
    return _data["addonsDir"].asString();
}

std::string EditorSettings::getOpenFrameworksDir() const
{
    return _data["openFrameworksDir"].asString();
}

std::string EditorSettings::getOpenFrameworksVersion() const
{
    return _data["openFrameworksVersion"].asString();
}

std::string EditorSettings::getProjectSettingsFilename() const
{
    return _data["projectSettingsFilename"].asString();
}

std::string EditorSettings::getProjectExtension() const
{
    return _data["projectExtension"].asString();
}

std::string EditorSettings::getClassExtension() const
{
    return _data["classExtension"].asString();
}

} } // namespace of::Sketch
<|endoftext|>


<commit_before>#include "barcode\PerkAttribMenu.hpp"

PerkAttribMenu::PerkAttribMenu()
{

}

PerkAttribMenu::~PerkAttribMenu()
{
}
void PerkAttribMenu::render(bool & thing, Hydra::Renderer::Batch * renderBatch, float delta)
{
	ImGui::SetNextWindowSize(ImVec2(500, 1000), ImGuiCond_Once);
	ImGui::Begin("Attributes", &thing, ImGuiWindowFlags_MenuBar);

	//Whatever you choose in the editor will be added/multiplied by
	//whatever values the player already has
	ImGui::Checkbox("Glow on/off", &Bullet.glow);
	ImGui::Separator();
	ImGui::Text("Glow Intensity:"); ImGui::SameLine(); ImGui::DragFloat("                             ", &Bullet.glowIntensity);
	ImGui::Separator();
	ImGui::Text("Bullet Size:"); ImGui::SameLine(); ImGui::DragFloat("", &Bullet.bulletSize);
	ImGui::Separator();
	ImGui::Text("Bullet Damage:"); ImGui::SameLine(); ImGui::DragFloat("  ",&Bullet.dmg);
	ImGui::Separator();
	ImGui::Text("Weapon Recoil:"); ImGui::SameLine(); ImGui::DragFloat("   ", &Bullet.recoil);
	ImGui::Separator();
	ImGui::Text("Mag Ammo:"); ImGui::SameLine(); ImGui::DragInt("      ", &Bullet.currentMagAmmo);
	ImGui::Separator();
	ImGui::Text("Shot Spread:"); ImGui::SameLine(); ImGui::DragFloat("       ", &Bullet.bulletSpread);
	ImGui::Separator();
	ImGui::Text("Shot RPM:"); ImGui::SameLine(); ImGui::DragFloat("          ", &Bullet.roundsPerMinute);
	ImGui::Separator();
	ImGui::ColorPicker4("Bullet Color:",(float*)&Bullet.bulletColor,ImGuiColorEditFlags_RGB);
	ImGui::Separator();
	ImGui::Text("Perk Description:");
	ImGui::InputText("                            ", Bullet.perkDescription, 128);
	ImGui::Separator();
	//ImGui::RadioButton("Multiplier", &Bullet.multi); ImGui::SameLine(); ImGui::RadioButton("Adder", &Bullet.add);
	ImGui::Checkbox("Multiplier", &Bullet.Multiplier), ImGui::SameLine(); ImGui::Checkbox("Adder", &Bullet.Adder);

	if (ImGui::Button("Export", ImVec2(200, 75)))
	{
		openPopup = true;
	}

	if (openPopup)
	{
		ImGui::OpenPopup("Exporter");
		if (ImGui::BeginPopup("Exporter"))
		{
			ImGui::Text("Write the name of your Perk:");
			ImGui::InputText("  ", Bullet.perkName, 128);

			if (ImGui::Button("Done", ImVec2(200, 75)))
			{
				writeToFile(Bullet.perkName);
				openPopup = false;
			}
			ImGui::SameLine();
			if (ImGui::Button("Exit", ImVec2(50, 75)))
			{
				openPopup = false;
			}
			ImGui::EndPopup();
		}
	}

	ImGui::End();
}

void PerkAttribMenu::updateBullet(BulletInfo& bullet)
{
	bullet = Bullet;
}

void PerkAttribMenu::writeToFile(const char* fileName)
{
	//file << Bullet.bulletSize;
	//file << Bullet.dmg;
	//file << Bullet.recoil;
	//file << Bullet.currentMagAmmo;
	//file << Bullet.bulletSpread;
	//file << Bullet.roundsPerMinute;
	//file << Bullet.bulletColor[0];
	//file << Bullet.bulletColor[1];
	//file << Bullet.bulletColor[2];
	//file.write(reinterpret_cast<char *>(&Bullet.perkDescription), sizeof(char));
	//binary
	//file << Bullet.perkDescription;

	std::string name = fileName;
	std::string filepath = "C:/Users/destroyer/Documents/GitHub/Hydra/assets/perks/" + name + ".PERK";
	std::ofstream file;
	file.open(filepath, std::ios::binary);

	file.write(reinterpret_cast<char *>(&Bullet.bulletSize), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.dmg), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.recoil), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.currentMagAmmo), sizeof(int));
	file.write(reinterpret_cast<char *>(&Bullet.bulletSpread), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.roundsPerMinute), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.bulletColor[0]), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.bulletColor[1]), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.bulletColor[2]), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.Adder), sizeof(bool));
	file.write(reinterpret_cast<char *>(&Bullet.Multiplier), sizeof(bool));
	file.write(reinterpret_cast<char *>(&Bullet.glow), sizeof(bool));
	file.write(reinterpret_cast<char *>(&Bullet.glowIntensity), sizeof(float));

	std::string description = Bullet.perkDescription;
	int size = description.size();

	file.write(reinterpret_cast<char*>(&size), sizeof(int));
	file.write(description.data(), size);

	file.close();
}

<commit_msg>Stuff<commit_after>#include "barcode\PerkAttribMenu.hpp"

PerkAttribMenu::PerkAttribMenu()
{

}

PerkAttribMenu::~PerkAttribMenu()
{
}
void PerkAttribMenu::render(bool & thing, Hydra::Renderer::Batch * renderBatch, float delta)
{
	ImGui::SetNextWindowSize(ImVec2(500, 1000), ImGuiCond_Once);
	ImGui::Begin("Attributes", &thing, ImGuiWindowFlags_MenuBar);

	//Whatever you choose in the editor will be added/multiplied by
	//whatever values the player already has
	ImGui::Checkbox("Glow on/off", &Bullet.glow);
	ImGui::Separator();
	ImGui::Text("Glow Intensity:"); ImGui::SameLine(); ImGui::DragFloat("                             ", &Bullet.glowIntensity, 0.01f);
	ImGui::Separator();
	ImGui::Text("Bullet Size:"); ImGui::SameLine(); ImGui::DragFloat("", &Bullet.bulletSize);
	ImGui::Separator();
	ImGui::Text("Bullet Damage:"); ImGui::SameLine(); ImGui::DragFloat("  ",&Bullet.dmg);
	ImGui::Separator();
	ImGui::Text("Weapon Recoil:"); ImGui::SameLine(); ImGui::DragFloat("   ", &Bullet.recoil);
	ImGui::Separator();
	ImGui::Text("Mag Ammo:"); ImGui::SameLine(); ImGui::DragInt("      ", &Bullet.currentMagAmmo);
	ImGui::Separator();
	ImGui::Text("Shot Spread:"); ImGui::SameLine(); ImGui::DragFloat("       ", &Bullet.bulletSpread);
	ImGui::Separator();
	ImGui::Text("Shot RPM:"); ImGui::SameLine(); ImGui::DragFloat("          ", &Bullet.roundsPerMinute);
	ImGui::Separator();
	ImGui::ColorPicker4("Bullet Color:",(float*)&Bullet.bulletColor,ImGuiColorEditFlags_RGB);
	ImGui::Separator();
	ImGui::Text("Perk Description:");
	ImGui::InputText("                            ", Bullet.perkDescription, 128);
	ImGui::Separator();
	//ImGui::RadioButton("Multiplier", &Bullet.multi); ImGui::SameLine(); ImGui::RadioButton("Adder", &Bullet.add);
	ImGui::Checkbox("Multiplier", &Bullet.Multiplier), ImGui::SameLine(); ImGui::Checkbox("Adder", &Bullet.Adder);

	if (ImGui::Button("Export", ImVec2(200, 75)))
	{
		openPopup = true;
	}

	if (openPopup)
	{
		ImGui::OpenPopup("Exporter");
		if (ImGui::BeginPopup("Exporter"))
		{
			ImGui::Text("Write the name of your Perk:");
			ImGui::InputText("  ", Bullet.perkName, 128);

			if (ImGui::Button("Done", ImVec2(200, 75)))
			{
				writeToFile(Bullet.perkName);
				openPopup = false;
			}
			ImGui::SameLine();
			if (ImGui::Button("Exit", ImVec2(50, 75)))
			{
				openPopup = false;
			}
			ImGui::EndPopup();
		}
	}

	ImGui::End();
}

void PerkAttribMenu::updateBullet(BulletInfo& bullet)
{
	bullet = Bullet;
}

void PerkAttribMenu::writeToFile(const char* fileName)
{
	//file << Bullet.bulletSize;
	//file << Bullet.dmg;
	//file << Bullet.recoil;
	//file << Bullet.currentMagAmmo;
	//file << Bullet.bulletSpread;
	//file << Bullet.roundsPerMinute;
	//file << Bullet.bulletColor[0];
	//file << Bullet.bulletColor[1];
	//file << Bullet.bulletColor[2];
	//file.write(reinterpret_cast<char *>(&Bullet.perkDescription), sizeof(char));
	//binary
	//file << Bullet.perkDescription;

	std::string name = fileName;
	std::string filepath = "C:/Users/destroyer/Documents/GitHub/Hydra/assets/perks/" + name + ".PERK";
	std::ofstream file;
	file.open(filepath, std::ios::binary);

	file.write(reinterpret_cast<char *>(&Bullet.bulletSize), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.dmg), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.recoil), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.currentMagAmmo), sizeof(int));
	file.write(reinterpret_cast<char *>(&Bullet.bulletSpread), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.roundsPerMinute), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.bulletColor[0]), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.bulletColor[1]), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.bulletColor[2]), sizeof(float));
	file.write(reinterpret_cast<char *>(&Bullet.Adder), sizeof(bool));
	file.write(reinterpret_cast<char *>(&Bullet.Multiplier), sizeof(bool));
	file.write(reinterpret_cast<char *>(&Bullet.glow), sizeof(bool));
	file.write(reinterpret_cast<char *>(&Bullet.glowIntensity), sizeof(float));

	std::string description = Bullet.perkDescription;
	int size = description.size();

	file.write(reinterpret_cast<char*>(&size), sizeof(int));
	file.write(description.data(), size);

	file.close();
}

<|endoftext|>


<commit_before>
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <iostream>
#include "shape_featureset.hpp"

template <typename filterT>
shape_featureset<filterT>::shape_featureset(const filterT& filter,
                                            const std::string& shape_file,
                                            const std::set<std::string>& attribute_names,
                                            std::string const& encoding,
                                            long file_length )
    : filter_(filter),
      shape_type_(shape_io::shape_null),
      shape_(shape_file),
      query_ext_(),
      tr_(new transcoder(encoding)),
      file_length_(file_length),
      count_(0)
{
    shape_.shp().skip(100);
    //attributes
    typename std::set<std::string>::const_iterator pos=attribute_names.begin();
    while (pos!=attribute_names.end())
    {
        bool found_name = false;
        for (int i=0;i<shape_.dbf().num_fields();++i)
        {
            if (shape_.dbf().descriptor(i).name_ == *pos)
            {
                attr_ids_.push_back(i);
                found_name = true;
                break;
            }
        }
        if (!found_name)
        {
            std::ostringstream s;

            s << "Shapefile Plugin: Error: no attribute by the name of '" << *pos << "'"
            << ", available attributes are:";
            for (int i=0;i<shape_.dbf().num_fields();++i)
            {
                s << " '" << shape_.dbf().descriptor(i).name_ << "'";
            }

            throw mapnik::datasource_exception( s.str() );
        }
        ++pos;
    }
}

template <typename filterT>
feature_ptr shape_featureset<filterT>::next()
{
    using mapnik::point_impl;
    std::streampos pos=shape_.shp().pos();

    if (!shape_.shp().is_eof())
    {
        shape_.move_to(pos);
        int type=shape_.type();
        feature_ptr feature(new Feature(shape_.id_));
        if (type == shape_io::shape_point)
        {
            double x=shape_.shp().read_double();
            double y=shape_.shp().read_double();
            geometry2d * point = new point_impl;
            point->move_to(x,y);
            feature->add_geometry(point);
            ++count_;
        }
        else if (type == shape_io::shape_pointm)
        {
            double x=shape_.shp().read_double();
            double y=shape_.shp().read_double();
            shape_.shp().skip(8); //m
            geometry2d * point = new point_impl;
            point->move_to(x,y);
            feature->add_geometry(point);
            ++count_;
        }
        else if (type == shape_io::shape_pointz)
        {
            double x=shape_.shp().read_double();
            double y=shape_.shp().read_double();
            // skip z
            shape_.shp().skip(8);

            //skip m if exists
            if ( shape_.reclength_ == 8 + 36)
            {
                shape_.shp().skip(8);
            }
            geometry2d * point=new point_impl;
            point->move_to(x,y);
            feature->add_geometry(point);
            ++count_;
        }
        else
        {
            while (!filter_.pass(shape_.current_extent()))
            {
                if (!shape_.shp().is_eof())
                {
                    std::streampos pos = shape_.shp().pos();
                    if (shape_.type() != shape_io::shape_null)
                    {
                       pos += std::streampos(2 * shape_.reclength_ - 36);
                    }
                    shape_.move_to(pos);
                }
                else
                {
                    return feature_ptr();
                }
            }

            switch (type)
            {
                case shape_io::shape_multipoint:
                {
                    int num_points = shape_.shp().read_ndr_integer();
                    for (int i=0; i< num_points;++i)
                    {
                        double x=shape_.shp().read_double();
                        double y=shape_.shp().read_double();
                        geometry2d * point = new point_impl;
                        point->move_to(x,y);
                        feature->add_geometry(point);
                    }
                    ++count_;
                    break;
                }
                case shape_io::shape_multipointm:
                {
                    int num_points = shape_.shp().read_ndr_integer();
                    for (int i=0; i< num_points;++i)
                    {
                        double x=shape_.shp().read_double();
                        double y=shape_.shp().read_double();
                        geometry2d * point = new point_impl;
                        point->move_to(x,y);
                        feature->add_geometry(point);
                    }

                    // skip m
                    shape_.shp().skip(2*8 + 8*num_points);
                    ++count_;
                    break;
                }
                case shape_io::shape_multipointz:
                {
                    unsigned num_points = shape_.shp().read_ndr_integer();
                    for (unsigned i=0; i< num_points;++i)
                    {
                        double x=shape_.shp().read_double();
                        double y=shape_.shp().read_double();
                        geometry2d * point = new point_impl;
                        point->move_to(x,y);
                        feature->add_geometry(point);
                    }

                    // skip z
                    shape_.shp().skip(2*8 + 8*num_points);

                    // check if we have measure data

                    if ( shape_.reclength_ == num_points * 16 + 36)
                    {
                        // skip m
                        shape_.shp().skip(2*8 + 8*num_points);
                    }
                    ++count_;
                    break;
                }
                case shape_io::shape_polyline:
                {
                    geometry2d * line = shape_.read_polyline();
                    feature->add_geometry(line);
                    ++count_;
                    break;
                }
                case shape_io::shape_polylinem:
                {
                    geometry2d * line = shape_.read_polylinem();
                    feature->add_geometry(line);
                    ++count_;
                    break;
                }
                case shape_io::shape_polylinez:
                {
                    geometry2d * line = shape_.read_polylinez();
                    feature->add_geometry(line);
                    ++count_;
                    break;
                }
                case shape_io::shape_polygon:
                {
                    geometry2d * poly = shape_.read_polygon();
                    feature->add_geometry(poly);
                    ++count_;
                    break;
                }
                case shape_io::shape_polygonm:
                {
                    geometry2d * poly = shape_.read_polygonm();
                    feature->add_geometry(poly);
                    ++count_;
                    break;
                }
                case shape_io::shape_polygonz:
                {
                    geometry2d * poly = shape_.read_polygonz();
                    feature->add_geometry(poly);
                    ++count_;
                    break;
                }

            }
        }
        if (attr_ids_.size())
        {
            shape_.dbf().move_to(shape_.id_);
            std::vector<int>::const_iterator pos=attr_ids_.begin();
            std::vector<int>::const_iterator end=attr_ids_.end();

            while (pos!=end)
            {
                try
                {
                    shape_.dbf().add_attribute(*pos,*tr_,*feature);//TODO optimize!!!
                }
                catch (...)
                {
                    std::clog << "error processing attributes " << std::endl;
                }
                ++pos;
            }
        }
        return feature;
    }
    else
    {
#ifdef MAPNIK_DEBUG
        std::clog<<" total shapes read="<<count_<<"\n";
#endif
        return feature_ptr();
    }
}

template <typename filterT>
shape_featureset<filterT>::~shape_featureset() {}

template class shape_featureset<mapnik::filter_in_box>;
template class shape_featureset<mapnik::filter_at_point>;

<commit_msg>shape: switch back to previous end of file method - closes #647<commit_after>
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <iostream>
#include "shape_featureset.hpp"

template <typename filterT>
shape_featureset<filterT>::shape_featureset(const filterT& filter,
                                            const std::string& shape_file,
                                            const std::set<std::string>& attribute_names,
                                            std::string const& encoding,
                                            long file_length )
    : filter_(filter),
      shape_type_(shape_io::shape_null),
      shape_(shape_file),
      query_ext_(),
      tr_(new transcoder(encoding)),
      file_length_(file_length),
      count_(0)
{
    shape_.shp().skip(100);
    //attributes
    typename std::set<std::string>::const_iterator pos=attribute_names.begin();
    while (pos!=attribute_names.end())
    {
        bool found_name = false;
        for (int i=0;i<shape_.dbf().num_fields();++i)
        {
            if (shape_.dbf().descriptor(i).name_ == *pos)
            {
                attr_ids_.push_back(i);
                found_name = true;
                break;
            }
        }
        if (!found_name)
        {
            std::ostringstream s;

            s << "Shapefile Plugin: Error: no attribute by the name of '" << *pos << "'"
            << ", available attributes are:";
            for (int i=0;i<shape_.dbf().num_fields();++i)
            {
                s << " '" << shape_.dbf().descriptor(i).name_ << "'";
            }

            throw mapnik::datasource_exception( s.str() );
        }
        ++pos;
    }
}

template <typename filterT>
feature_ptr shape_featureset<filterT>::next()
{
    using mapnik::point_impl;
    std::streampos pos=shape_.shp().pos();

    if (pos < std::streampos(file_length_ * 2))
    {
        shape_.move_to(pos);
        int type=shape_.type();
        feature_ptr feature(new Feature(shape_.id_));
        if (type == shape_io::shape_point)
        {
            double x=shape_.shp().read_double();
            double y=shape_.shp().read_double();
            geometry2d * point = new point_impl;
            point->move_to(x,y);
            feature->add_geometry(point);
            ++count_;
        }
        else if (type == shape_io::shape_pointm)
        {
            double x=shape_.shp().read_double();
            double y=shape_.shp().read_double();
            shape_.shp().skip(8); //m
            geometry2d * point = new point_impl;
            point->move_to(x,y);
            feature->add_geometry(point);
            ++count_;
        }
        else if (type == shape_io::shape_pointz)
        {
            double x=shape_.shp().read_double();
            double y=shape_.shp().read_double();
            // skip z
            shape_.shp().skip(8);

            //skip m if exists
            if ( shape_.reclength_ == 8 + 36)
            {
                shape_.shp().skip(8);
            }
            geometry2d * point=new point_impl;
            point->move_to(x,y);
            feature->add_geometry(point);
            ++count_;
        }
        else
        {
            while (!filter_.pass(shape_.current_extent()))
            {
                if (!shape_.shp().is_eof())
                {
                    std::streampos pos = shape_.shp().pos();
                    if (shape_.type() != shape_io::shape_null)
                    {
                       pos += std::streampos(2 * shape_.reclength_ - 36);
                    }
                    shape_.move_to(pos);
                }
                else
                {
                    return feature_ptr();
                }
            }

            switch (type)
            {
                case shape_io::shape_multipoint:
                {
                    int num_points = shape_.shp().read_ndr_integer();
                    for (int i=0; i< num_points;++i)
                    {
                        double x=shape_.shp().read_double();
                        double y=shape_.shp().read_double();
                        geometry2d * point = new point_impl;
                        point->move_to(x,y);
                        feature->add_geometry(point);
                    }
                    ++count_;
                    break;
                }
                case shape_io::shape_multipointm:
                {
                    int num_points = shape_.shp().read_ndr_integer();
                    for (int i=0; i< num_points;++i)
                    {
                        double x=shape_.shp().read_double();
                        double y=shape_.shp().read_double();
                        geometry2d * point = new point_impl;
                        point->move_to(x,y);
                        feature->add_geometry(point);
                    }

                    // skip m
                    shape_.shp().skip(2*8 + 8*num_points);
                    ++count_;
                    break;
                }
                case shape_io::shape_multipointz:
                {
                    unsigned num_points = shape_.shp().read_ndr_integer();
                    for (unsigned i=0; i< num_points;++i)
                    {
                        double x=shape_.shp().read_double();
                        double y=shape_.shp().read_double();
                        geometry2d * point = new point_impl;
                        point->move_to(x,y);
                        feature->add_geometry(point);
                    }

                    // skip z
                    shape_.shp().skip(2*8 + 8*num_points);

                    // check if we have measure data

                    if ( shape_.reclength_ == num_points * 16 + 36)
                    {
                        // skip m
                        shape_.shp().skip(2*8 + 8*num_points);
                    }
                    ++count_;
                    break;
                }
                case shape_io::shape_polyline:
                {
                    geometry2d * line = shape_.read_polyline();
                    feature->add_geometry(line);
                    ++count_;
                    break;
                }
                case shape_io::shape_polylinem:
                {
                    geometry2d * line = shape_.read_polylinem();
                    feature->add_geometry(line);
                    ++count_;
                    break;
                }
                case shape_io::shape_polylinez:
                {
                    geometry2d * line = shape_.read_polylinez();
                    feature->add_geometry(line);
                    ++count_;
                    break;
                }
                case shape_io::shape_polygon:
                {
                    geometry2d * poly = shape_.read_polygon();
                    feature->add_geometry(poly);
                    ++count_;
                    break;
                }
                case shape_io::shape_polygonm:
                {
                    geometry2d * poly = shape_.read_polygonm();
                    feature->add_geometry(poly);
                    ++count_;
                    break;
                }
                case shape_io::shape_polygonz:
                {
                    geometry2d * poly = shape_.read_polygonz();
                    feature->add_geometry(poly);
                    ++count_;
                    break;
                }

            }
        }
        if (attr_ids_.size())
        {
            shape_.dbf().move_to(shape_.id_);
            std::vector<int>::const_iterator pos=attr_ids_.begin();
            std::vector<int>::const_iterator end=attr_ids_.end();

            while (pos!=end)
            {
                try
                {
                    shape_.dbf().add_attribute(*pos,*tr_,*feature);//TODO optimize!!!
                }
                catch (...)
                {
                    std::clog << "error processing attributes " << std::endl;
                }
                ++pos;
            }
        }
        return feature;
    }
    else
    {
#ifdef MAPNIK_DEBUG
        std::clog<<" total shapes read="<<count_<<"\n";
#endif
        return feature_ptr();
    }
}

template <typename filterT>
shape_featureset<filterT>::~shape_featureset() {}

template class shape_featureset<mapnik::filter_in_box>;
template class shape_featureset<mapnik::filter_at_point>;

<|endoftext|>