<commit_before>#include "OpenNIPlugin.h"
#include <iostream>
#include <StreamTypes.h>
#include "../../SenseKit/sensekit_internal.h"

#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif

#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif

using std::cout;
using std::endl;

EXPORT_PLUGIN(sensekit::openni::OpenNIPlugin);

namespace sensekit
{
    namespace openni
    {
        void OpenNIPlugin::init_openni()
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            ::openni::OpenNI::addDeviceConnectedListener(this);
            ::openni::OpenNI::addDeviceDisconnectedListener(this);

            cout << "Initializing openni" << endl;
            rc = ::openni::OpenNI::initialize();
        }

        void OpenNIPlugin::onDeviceConnected(const ::openni::DeviceInfo* info)
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            cout << "Opening device" << endl;
            rc = m_device.open(info->getUri());

            if (rc != ::openni::STATUS_OK)
            {
                cout << "Failed to open" << endl;
                ::openni::OpenNI::shutdown();
            }

            m_deviceInfo = m_device.getDeviceInfo();

            open_sensor_streams();
        }

        void OpenNIPlugin::onDeviceDisconnected(const ::openni::DeviceInfo* info)
        {
            get_pluginService().destroy_stream(m_depthHandle);
            get_pluginService().destroy_stream(m_colorHandle);
            get_pluginService().destroy_stream_set(m_streamSetHandle);
            close_sensor_streams();
        }

        OpenNIPlugin::~OpenNIPlugin()
        {
            get_pluginService().destroy_stream(m_depthHandle);
            get_pluginService().destroy_stream(m_colorHandle);
            get_pluginService().destroy_stream_set(m_streamSetHandle);
            close_sensor_streams();

            cout << "closing device" << endl;
            m_device.close();
            cout << "shutting down openni" << endl;
            ::openni::OpenNI::shutdown();
        }

        sensekit_status_t OpenNIPlugin::open_sensor_streams()
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            cout << "opening depth stream" << endl;
            rc = m_depthStream.create(m_device, ::openni::SENSOR_DEPTH);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting depth stream." << endl;
                rc = m_depthStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start depth stream" << endl;
                    m_depthStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open depth stream" << endl;
            }

            if (!m_depthStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            cout << "opening color stream" << endl;
            rc = m_colorStream.create(m_device, ::openni::SENSOR_COLOR);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting color stream." << endl;
                rc = m_colorStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start color stream" << endl;
                    m_colorStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open color stream" << endl;
            }

            if (!m_colorStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            sensekit_frame_t* nextBuffer = nullptr;

            stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this);

            get_pluginService().create_stream_set(m_streamSetHandle);

            sensekit_stream_desc_t depthDesc;
            depthDesc.type = SENSEKIT_STREAM_DEPTH;
            depthDesc.subType = DEPTH_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              depthDesc,
                                              pluginCallbacks,
                                              &m_depthHandle);

            sensekit_stream_desc_t colorDesc;
            colorDesc.type = SENSEKIT_STREAM_COLOR;
            colorDesc.subType = COLOR_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              colorDesc,
                                              pluginCallbacks,
                                              &m_colorHandle);

            m_depthMode = m_depthStream.getVideoMode();
            m_colorMode = m_colorStream.getVideoMode();

            m_depthBufferLength  = m_depthMode.getResolutionX() * m_depthMode.getResolutionY() * 2;
            m_colorBufferLength = m_colorMode.getResolutionX() * m_colorMode.getResolutionY() * 3;

            get_pluginService()
                .create_stream_bin(m_depthHandle,
                                   sizeof(sensekit_depthframe_wrapper_t) + m_depthBufferLength,
                                   &m_depthBinHandle,
                                   &nextBuffer);

            set_new_depth_buffer(nextBuffer);

            get_pluginService()
                .create_stream_bin(m_colorHandle,
                                   sizeof(sensekit_colorframe_wrapper_t) + m_colorBufferLength,
                                   &m_colorBinHandle,
                                   &nextBuffer);

            set_new_color_buffer(nextBuffer);

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_parameter(sensekit_streamconnection_t streamConnection,
                                         sensekit_parameter_id id, size_t byteLength,
                                         sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::get_parameter_size(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t& byteLength)
        {}

        void OpenNIPlugin::get_parameter_data(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t byteLength,
                                              sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::connection_added(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, m_depthBinHandle);
                cout << "openniplugin: new connection added, linked to global depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, m_colorBinHandle);
                cout << "openniplugin: new connection added, linked to global color" << endl;
                break;
            }
        }

        void OpenNIPlugin::connection_removed(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from color" << endl;
                break;
            }
        }

        sensekit_status_t OpenNIPlugin::close_sensor_streams()
        {
            cout << "stopping depth stream" << endl;
            m_depthStream.stop();
            cout << "stopping color stream" << endl;
            m_colorStream.stop();
            cout << "destroying depth stream" << endl;
            m_depthStream.destroy();
            cout << "destroying color stream" << endl;
            m_colorStream.destroy();

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_new_depth_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentDepthBuffer = nextBuffer;
            m_currentDepthFrame = nullptr;
            if (m_currentDepthBuffer != nullptr)
            {
                m_currentDepthBuffer->frameIndex = m_frameIndex;
                m_currentDepthFrame = static_cast<sensekit_depthframe_wrapper_t*>(m_currentDepthBuffer->data);
                if (m_currentDepthFrame != nullptr)
                {
                    m_currentDepthFrame->frame.data = reinterpret_cast<int16_t *>(&(m_currentDepthFrame->frame_data));

                    sensekit_depthframe_metadata_t metadata;

                    metadata.width = m_depthMode.getResolutionX();
                    metadata.height = m_depthMode.getResolutionY();
                    metadata.bytesPerPixel = 2;

                    m_currentDepthFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::set_new_color_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentColorBuffer = nextBuffer;
            m_currentColorFrame = nullptr;
            if (m_currentColorBuffer != nullptr)
            {
                m_currentColorBuffer->frameIndex = m_frameIndex;
                m_currentColorFrame = static_cast<sensekit_colorframe_wrapper_t*>(m_currentColorBuffer->data);
                if (m_currentColorFrame != nullptr)
                {
                    m_currentColorFrame->frame.data = reinterpret_cast<uint8_t *>(&(m_currentColorFrame->frame_data));

                    sensekit_colorframe_metadata_t metadata;

                    metadata.width = m_colorMode.getResolutionX();
                    metadata.height = m_colorMode.getResolutionY();
                    metadata.bytesPerPixel = 3;

                    m_currentColorFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::temp_update()
        {
            if (m_currentColorBuffer != nullptr
                && m_currentDepthBuffer != nullptr)
            {
                read_streams();
            }
        }

        sensekit_status_t OpenNIPlugin::read_streams()
        {
            int streamIndex = -1;
            int timeout = ::openni::TIMEOUT_NONE;

            ::openni::VideoStream* pStreams[] =  { &m_depthStream, &m_colorStream };
            if (::openni::OpenNI::waitForAnyStream(pStreams, 2, &streamIndex, timeout)
                == ::openni::STATUS_TIME_OUT)
            {
                return SENSEKIT_STATUS_TIMEOUT;
            }

            if (streamIndex == -1)
                return SENSEKIT_STATUS_TIMEOUT;

            sensekit_frame_t* nextBuffer = nullptr;

            if (streamIndex == 0)
            {
                ::openni::VideoFrameRef ref;
                if (m_depthStream.readFrame(&ref) == ::openni::STATUS_OK)
                {
                    const int16_t* oniFrameData = static_cast<const int16_t*>(ref.getData());

                    int16_t* frameData = m_currentDepthFrame->frame.data;
                    int dataSize = MIN(ref.getDataSize(), m_depthBufferLength);

                    memcpy(frameData, oniFrameData, dataSize);

                    ++m_frameIndex;

                    get_pluginService().cycle_bin_buffers(m_depthBinHandle, &nextBuffer);
                    set_new_depth_buffer(nextBuffer);
                }
            }
            else if (streamIndex == 1)
            {
                ::openni::VideoFrameRef ref;
                if (m_colorStream.readFrame(&ref) == ::openni::STATUS_OK)
                {
                    const uint8_t* oniFrameData = static_cast<const uint8_t*>(ref.getData());

                    uint8_t* frameData = m_currentColorFrame->frame.data;

                    int dataSize = MIN(ref.getDataSize(), m_colorBufferLength);
                    memcpy(frameData, oniFrameData, dataSize);

                    ++m_frameIndex;

                    get_pluginService().cycle_bin_buffers(m_colorBinHandle, &nextBuffer);
                    set_new_color_buffer(nextBuffer);
                }
            }

            return SENSEKIT_STATUS_SUCCESS;
        }
    }
}
<commit_msg>More description messages for device connect/disconnect<commit_after>#include "OpenNIPlugin.h"
#include <iostream>
#include <StreamTypes.h>
#include "../../SenseKit/sensekit_internal.h"

#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif

#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif

using std::cout;
using std::endl;

EXPORT_PLUGIN(sensekit::openni::OpenNIPlugin);

namespace sensekit
{
    namespace openni
    {
        void OpenNIPlugin::init_openni()
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            ::openni::OpenNI::addDeviceConnectedListener(this);
            ::openni::OpenNI::addDeviceDisconnectedListener(this);

            cout << "Initializing openni" << endl;
            rc = ::openni::OpenNI::initialize();
        }

        void OpenNIPlugin::onDeviceConnected(const ::openni::DeviceInfo* info)
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            cout << "device connected, opening device" << endl;
            rc = m_device.open(info->getUri());

            if (rc != ::openni::STATUS_OK)
            {
                cout << "Failed to open" << endl;
                ::openni::OpenNI::shutdown();
            }

            m_deviceInfo = m_device.getDeviceInfo();

            open_sensor_streams();
        }

        void OpenNIPlugin::onDeviceDisconnected(const ::openni::DeviceInfo* info)
        {
            cout << "device disconnected" << endl;
            get_pluginService().destroy_stream(m_depthHandle);
            get_pluginService().destroy_stream(m_colorHandle);
            get_pluginService().destroy_stream_set(m_streamSetHandle);
            close_sensor_streams();
        }

        OpenNIPlugin::~OpenNIPlugin()
        {
            get_pluginService().destroy_stream(m_depthHandle);
            get_pluginService().destroy_stream(m_colorHandle);
            get_pluginService().destroy_stream_set(m_streamSetHandle);
            close_sensor_streams();

            cout << "closing device" << endl;
            m_device.close();
            cout << "shutting down openni" << endl;
            ::openni::OpenNI::shutdown();
        }

        sensekit_status_t OpenNIPlugin::open_sensor_streams()
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            cout << "opening depth stream" << endl;
            rc = m_depthStream.create(m_device, ::openni::SENSOR_DEPTH);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting depth stream." << endl;
                rc = m_depthStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start depth stream" << endl;
                    m_depthStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open depth stream" << endl;
            }

            if (!m_depthStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            cout << "opening color stream" << endl;
            rc = m_colorStream.create(m_device, ::openni::SENSOR_COLOR);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting color stream." << endl;
                rc = m_colorStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start color stream" << endl;
                    m_colorStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open color stream" << endl;
            }

            if (!m_colorStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            sensekit_frame_t* nextBuffer = nullptr;

            stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this);

            get_pluginService().create_stream_set(m_streamSetHandle);

            sensekit_stream_desc_t depthDesc;
            depthDesc.type = SENSEKIT_STREAM_DEPTH;
            depthDesc.subType = DEPTH_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              depthDesc,
                                              pluginCallbacks,
                                              &m_depthHandle);

            sensekit_stream_desc_t colorDesc;
            colorDesc.type = SENSEKIT_STREAM_COLOR;
            colorDesc.subType = COLOR_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              colorDesc,
                                              pluginCallbacks,
                                              &m_colorHandle);

            m_depthMode = m_depthStream.getVideoMode();
            m_colorMode = m_colorStream.getVideoMode();

            m_depthBufferLength  = m_depthMode.getResolutionX() * m_depthMode.getResolutionY() * 2;
            m_colorBufferLength = m_colorMode.getResolutionX() * m_colorMode.getResolutionY() * 3;

            get_pluginService()
                .create_stream_bin(m_depthHandle,
                                   sizeof(sensekit_depthframe_wrapper_t) + m_depthBufferLength,
                                   &m_depthBinHandle,
                                   &nextBuffer);

            set_new_depth_buffer(nextBuffer);

            get_pluginService()
                .create_stream_bin(m_colorHandle,
                                   sizeof(sensekit_colorframe_wrapper_t) + m_colorBufferLength,
                                   &m_colorBinHandle,
                                   &nextBuffer);

            set_new_color_buffer(nextBuffer);

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_parameter(sensekit_streamconnection_t streamConnection,
                                         sensekit_parameter_id id, size_t byteLength,
                                         sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::get_parameter_size(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t& byteLength)
        {}

        void OpenNIPlugin::get_parameter_data(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t byteLength,
                                              sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::connection_added(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, m_depthBinHandle);
                cout << "openniplugin: new connection added, linked to global depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, m_colorBinHandle);
                cout << "openniplugin: new connection added, linked to global color" << endl;
                break;
            }
        }

        void OpenNIPlugin::connection_removed(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from color" << endl;
                break;
            }
        }

        sensekit_status_t OpenNIPlugin::close_sensor_streams()
        {
            cout << "stopping depth stream" << endl;
            m_depthStream.stop();
            cout << "stopping color stream" << endl;
            m_colorStream.stop();
            cout << "destroying depth stream" << endl;
            m_depthStream.destroy();
            cout << "destroying color stream" << endl;
            m_colorStream.destroy();

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_new_depth_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentDepthBuffer = nextBuffer;
            m_currentDepthFrame = nullptr;
            if (m_currentDepthBuffer != nullptr)
            {
                m_currentDepthBuffer->frameIndex = m_frameIndex;
                m_currentDepthFrame = static_cast<sensekit_depthframe_wrapper_t*>(m_currentDepthBuffer->data);
                if (m_currentDepthFrame != nullptr)
                {
                    m_currentDepthFrame->frame.data = reinterpret_cast<int16_t *>(&(m_currentDepthFrame->frame_data));

                    sensekit_depthframe_metadata_t metadata;

                    metadata.width = m_depthMode.getResolutionX();
                    metadata.height = m_depthMode.getResolutionY();
                    metadata.bytesPerPixel = 2;

                    m_currentDepthFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::set_new_color_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentColorBuffer = nextBuffer;
            m_currentColorFrame = nullptr;
            if (m_currentColorBuffer != nullptr)
            {
                m_currentColorBuffer->frameIndex = m_frameIndex;
                m_currentColorFrame = static_cast<sensekit_colorframe_wrapper_t*>(m_currentColorBuffer->data);
                if (m_currentColorFrame != nullptr)
                {
                    m_currentColorFrame->frame.data = reinterpret_cast<uint8_t *>(&(m_currentColorFrame->frame_data));

                    sensekit_colorframe_metadata_t metadata;

                    metadata.width = m_colorMode.getResolutionX();
                    metadata.height = m_colorMode.getResolutionY();
                    metadata.bytesPerPixel = 3;

                    m_currentColorFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::temp_update()
        {
            if (m_currentColorBuffer != nullptr
                && m_currentDepthBuffer != nullptr)
            {
                read_streams();
            }
        }

        sensekit_status_t OpenNIPlugin::read_streams()
        {
            int streamIndex = -1;
            int timeout = ::openni::TIMEOUT_NONE;

            ::openni::VideoStream* pStreams[] =  { &m_depthStream, &m_colorStream };
            if (::openni::OpenNI::waitForAnyStream(pStreams, 2, &streamIndex, timeout)
                == ::openni::STATUS_TIME_OUT)
            {
                return SENSEKIT_STATUS_TIMEOUT;
            }

            if (streamIndex == -1)
                return SENSEKIT_STATUS_TIMEOUT;

            sensekit_frame_t* nextBuffer = nullptr;

            if (streamIndex == 0)
            {
                ::openni::VideoFrameRef ref;
                if (m_depthStream.readFrame(&ref) == ::openni::STATUS_OK)
                {
                    const int16_t* oniFrameData = static_cast<const int16_t*>(ref.getData());

                    int16_t* frameData = m_currentDepthFrame->frame.data;
                    int dataSize = MIN(ref.getDataSize(), m_depthBufferLength);

                    memcpy(frameData, oniFrameData, dataSize);

                    ++m_frameIndex;

                    get_pluginService().cycle_bin_buffers(m_depthBinHandle, &nextBuffer);
                    set_new_depth_buffer(nextBuffer);
                }
            }
            else if (streamIndex == 1)
            {
                ::openni::VideoFrameRef ref;
                if (m_colorStream.readFrame(&ref) == ::openni::STATUS_OK)
                {
                    const uint8_t* oniFrameData = static_cast<const uint8_t*>(ref.getData());

                    uint8_t* frameData = m_currentColorFrame->frame.data;

                    int dataSize = MIN(ref.getDataSize(), m_colorBufferLength);
                    memcpy(frameData, oniFrameData, dataSize);

                    ++m_frameIndex;

                    get_pluginService().cycle_bin_buffers(m_colorBinHandle, &nextBuffer);
                    set_new_color_buffer(nextBuffer);
                }
            }

            return SENSEKIT_STATUS_SUCCESS;
        }
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "kit.h"

#include "devicesupport/devicemanager.h"
#include "kitinformation.h"
#include "kitmanager.h"
#include "project.h"
#include "toolchainmanager.h"

#include <utils/qtcassert.h>

#include <QApplication>
#include <QIcon>
#include <QStyle>
#include <QTextStream>
#include <QUuid>

namespace {

const char ID_KEY[] = "PE.Profile.Id";
const char DISPLAYNAME_KEY[] = "PE.Profile.Name";
const char AUTODETECTED_KEY[] = "PE.Profile.AutoDetected";
const char DATA_KEY[] = "PE.Profile.Data";
const char ICON_KEY[] = "PE.Profile.Icon";

} // namespace

namespace ProjectExplorer {

// --------------------------------------------------------------------
// Helper:
// --------------------------------------------------------------------

static QString cleanName(const QString &name)
{
    QString result = name;
    result.replace(QRegExp("\\W"), QLatin1String("_"));
    result.replace(QRegExp("_+"), "_"); // compact _
    result.remove(QRegExp("^_*")); // remove leading _
    result.remove(QRegExp("_+$")); // remove trailing _
    if (result.isEmpty())
        result = QLatin1String("unknown");
    return result;
}

// -------------------------------------------------------------------------
// KitPrivate
// -------------------------------------------------------------------------

namespace Internal {

class KitPrivate
{
public:
    KitPrivate(Core::Id id) :
        m_id(id),
        m_autodetected(false),
        m_isValid(true),
        m_nestedBlockingLevel(0),
        m_mustNotify(false)
    {
        if (!id.isValid())
            m_id = Core::Id(QUuid::createUuid().toString().toLatin1().constData());
    }

    QString m_displayName;
    Core::Id m_id;
    bool m_autodetected;
    bool m_isValid;
    QIcon m_icon;
    QString m_iconPath;
    int m_nestedBlockingLevel;
    bool m_mustNotify;

    QHash<Core::Id, QVariant> m_data;
};

} // namespace Internal

// -------------------------------------------------------------------------
// Kit:
// -------------------------------------------------------------------------

Kit::Kit(Core::Id id) :
    d(new Internal::KitPrivate(id))
{
    KitManager *stm = KitManager::instance();
    KitGuard g(this);
    foreach (KitInformation *sti, stm->kitInformation())
        setValue(sti->dataId(), sti->defaultValue(this));

    setDisplayName(QCoreApplication::translate("ProjectExplorer::Kit", "Unnamed"));
    setIconPath(QLatin1String(":///DESKTOP///"));
}

Kit::~Kit()
{
    delete d;
}

void Kit::blockNotification()
{
    ++d->m_nestedBlockingLevel;
}

void Kit::unblockNotification()
{
    --d->m_nestedBlockingLevel;
    if (d->m_nestedBlockingLevel > 0)
        return;
    if (d->m_mustNotify)
        kitUpdated();
    d->m_mustNotify = false;
}

Kit *Kit::clone(bool keepName) const
{
    Kit *k = new Kit;
    if (keepName)
        k->d->m_displayName = d->m_displayName;
    else
        k->d->m_displayName = QCoreApplication::translate("ProjectExplorer::Kit", "Clone of %1")
                .arg(d->m_displayName);
    k->d->m_autodetected = false;
    k->d->m_data = d->m_data;
    k->d->m_isValid = d->m_isValid;
    k->d->m_icon = d->m_icon;
    k->d->m_iconPath = d->m_iconPath;
    return k;
}

void Kit::copyFrom(const Kit *k)
{
    KitGuard g(this);
    d->m_data = k->d->m_data;
    d->m_iconPath = k->d->m_iconPath;
    d->m_icon = k->d->m_icon;
    d->m_autodetected = k->d->m_autodetected;
    d->m_displayName = k->d->m_displayName;
    d->m_mustNotify = true;
}

bool Kit::isValid() const
{
    return d->m_id.isValid() && d->m_isValid;
}

QList<Task> Kit::validate() const
{
    QList<Task> result;
    QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
    d->m_isValid = true;
    foreach (KitInformation *i, infoList) {
        QList<Task> tmp = i->validate(this);
        foreach (const Task &t, tmp) {
            if (t.type == Task::Error)
                d->m_isValid = false;
        }
        result.append(tmp);
    }
    qSort(result);
    return result;
}

void Kit::fix()
{
    KitGuard g(this);
    foreach (KitInformation *i, KitManager::instance()->kitInformation())
        i->fix(this);
}

QString Kit::displayName() const
{
    return d->m_displayName;
}

static QString candidateName(const QString &name, const QString &postfix)
{
    if (name.contains(postfix))
        return QString();
    return name + QLatin1Char('-') + postfix;
}

void Kit::setDisplayName(const QString &name)
{
    KitManager *km = KitManager::instance();
    QList<KitInformation *> kitInfo = km->kitInformation();

    QStringList nameList;
    foreach (Kit *k, km->kits()) {
        if (k == this)
            continue;
        nameList << k->displayName();
        foreach (KitInformation *ki, kitInfo) {
            const QString postfix = ki->displayNamePostfix(k);
            if (!postfix.isEmpty())
                nameList << candidateName(k->displayName(), postfix);
        }
    }

    QStringList candidateNames;
    candidateNames << name;

    foreach (KitInformation *ki, kitInfo) {
        const QString postfix = ki->displayNamePostfix(this);
        if (!postfix.isEmpty())
            candidateNames << candidateName(name, postfix);
    }

    QString uniqueName = Project::makeUnique(name, nameList);
    if (uniqueName != name) {
        foreach (const QString &candidate, candidateNames) {
            const QString tmp = Project::makeUnique(candidate, nameList);
            if (tmp == candidate) {
                uniqueName = tmp;
                break;
            }
        }
    }

    if (d->m_displayName == uniqueName)
        return;
    d->m_displayName = uniqueName;
    kitUpdated();
}

QString Kit::fileSystemFriendlyName() const
{
    QString name = cleanName(displayName());
    foreach (Kit *i, KitManager::instance()->kits()) {
        if (i == this)
            continue;
        if (name == cleanName(i->displayName())) {
            // append part of the kit id: That should be unique enough;-)
            // Leading { will be turned into _ which should be fine.
            name = cleanName(name + QLatin1Char('_') + (id().toString().left(7)));
            break;
        }
    }
    return name;
}

bool Kit::isAutoDetected() const
{
    return d->m_autodetected;
}

Core::Id Kit::id() const
{
    return d->m_id;
}

QIcon Kit::icon() const
{
    return d->m_icon;
}

QString Kit::iconPath() const
{
    return d->m_iconPath;
}

void Kit::setIconPath(const QString &path)
{
    if (d->m_iconPath == path)
        return;
    d->m_iconPath = path;
    if (path.isNull())
        d->m_icon = QIcon();
    else if (path == QLatin1String(":///DESKTOP///"))
        d->m_icon = qApp->style()->standardIcon(QStyle::SP_ComputerIcon);
    else
        d->m_icon = QIcon(path);
    kitUpdated();
}

QVariant Kit::value(const Core::Id &key, const QVariant &unset) const
{
    return d->m_data.value(key, unset);
}

bool Kit::hasValue(const Core::Id &key) const
{
    return d->m_data.contains(key);
}

void Kit::setValue(const Core::Id &key, const QVariant &value)
{
    if (d->m_data.value(key) == value)
        return;
    d->m_data.insert(key, value);
    kitUpdated();
}

void Kit::removeKey(const Core::Id &key)
{
    if (!d->m_data.contains(key))
        return;
    d->m_data.remove(key);
    kitUpdated();
}

bool Kit::isDataEqual(const Kit *other) const
{
    return d->m_data == other->d->m_data;
}

bool Kit::isEqual(const Kit *other) const
{
    return isDataEqual(other)
            && d->m_iconPath == other->d->m_iconPath
            && d->m_displayName == other->d->m_displayName;
}

QVariantMap Kit::toMap() const
{
    QVariantMap data;
    data.insert(QLatin1String(ID_KEY), QString::fromLatin1(d->m_id.name()));
    data.insert(QLatin1String(DISPLAYNAME_KEY), d->m_displayName);
    data.insert(QLatin1String(AUTODETECTED_KEY), d->m_autodetected);
    data.insert(QLatin1String(ICON_KEY), d->m_iconPath);

    QVariantMap extra;
    foreach (const Core::Id &key, d->m_data.keys())
        extra.insert(QString::fromLatin1(key.name().constData()), d->m_data.value(key));
    data.insert(QLatin1String(DATA_KEY), extra);

    return data;
}

void Kit::addToEnvironment(Utils::Environment &env) const
{
    QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
    foreach (KitInformation *ki, infoList)
        ki->addToEnvironment(this, env);
}

QString Kit::toHtml()
{
    QString rc;
    QTextStream str(&rc);
    str << "";
    str << "
" << displayName() << "
";
    str << "
";

    if (!isValid()) {
        QList<Task> issues = validate();
        str << "
";
        foreach (const Task &t, issues) {
            str << "";
            switch (t.type) {
            case Task::Error:
                str << QCoreApplication::translate("ProjectExplorer::Kit", "Error:");
                break;
            case Task::Warning:
                str << QCoreApplication::translate("ProjectExplorer::Kit", "Warning:");
                break;
            case Task::Unknown:
            default:
                break;
            }
            str << "" << t.description << "
";
        }
        str << "
";
    }

    QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
    foreach (KitInformation *ki, infoList) {
        KitInformation::ItemList list = ki->toUserOutput(this);
        foreach (const KitInformation::Item &j, list)
            str << "
" << j.first << ":	" << j.second << "
";
    }
    str << "
";
    return rc;
}

bool Kit::fromMap(const QVariantMap &data)
{
    KitGuard g(this);
    const QString id = data.value(QLatin1String(ID_KEY)).toString();
    if (id.isEmpty())
        return false;
    d->m_id = Core::Id(id);
    d->m_autodetected = data.value(QLatin1String(AUTODETECTED_KEY)).toBool();
    setDisplayName(data.value(QLatin1String(DISPLAYNAME_KEY)).toString());
    setIconPath(data.value(QLatin1String(ICON_KEY)).toString());

    QVariantMap extra = data.value(QLatin1String(DATA_KEY)).toMap();
    foreach (const QString &key, extra.keys())
        setValue(Core::Id(key), extra.value(key));

    return true;
}

void Kit::setAutoDetected(bool detected)
{
    d->m_autodetected = detected;
}

void Kit::kitUpdated()
{
    if (d->m_nestedBlockingLevel > 0) {
        d->m_mustNotify = true;
        return;
    }
    validate();
    KitManager::instance()->notifyAboutUpdate(this);
}

} // namespace ProjectExplorer
<commit_msg>Kits: Do not construct kits with names starting with -<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "kit.h"

#include "devicesupport/devicemanager.h"
#include "kitinformation.h"
#include "kitmanager.h"
#include "project.h"
#include "toolchainmanager.h"

#include <utils/qtcassert.h>

#include <QApplication>
#include <QIcon>
#include <QStyle>
#include <QTextStream>
#include <QUuid>

namespace {

const char ID_KEY[] = "PE.Profile.Id";
const char DISPLAYNAME_KEY[] = "PE.Profile.Name";
const char AUTODETECTED_KEY[] = "PE.Profile.AutoDetected";
const char DATA_KEY[] = "PE.Profile.Data";
const char ICON_KEY[] = "PE.Profile.Icon";

} // namespace

namespace ProjectExplorer {

// --------------------------------------------------------------------
// Helper:
// --------------------------------------------------------------------

static QString cleanName(const QString &name)
{
    QString result = name;
    result.replace(QRegExp("\\W"), QLatin1String("_"));
    result.replace(QRegExp("_+"), "_"); // compact _
    result.remove(QRegExp("^_*")); // remove leading _
    result.remove(QRegExp("_+$")); // remove trailing _
    if (result.isEmpty())
        result = QLatin1String("unknown");
    return result;
}

// -------------------------------------------------------------------------
// KitPrivate
// -------------------------------------------------------------------------

namespace Internal {

class KitPrivate
{
public:
    KitPrivate(Core::Id id) :
        m_id(id),
        m_autodetected(false),
        m_isValid(true),
        m_nestedBlockingLevel(0),
        m_mustNotify(false)
    {
        if (!id.isValid())
            m_id = Core::Id(QUuid::createUuid().toString().toLatin1().constData());
    }

    QString m_displayName;
    Core::Id m_id;
    bool m_autodetected;
    bool m_isValid;
    QIcon m_icon;
    QString m_iconPath;
    int m_nestedBlockingLevel;
    bool m_mustNotify;

    QHash<Core::Id, QVariant> m_data;
};

} // namespace Internal

// -------------------------------------------------------------------------
// Kit:
// -------------------------------------------------------------------------

Kit::Kit(Core::Id id) :
    d(new Internal::KitPrivate(id))
{
    KitManager *stm = KitManager::instance();
    KitGuard g(this);
    foreach (KitInformation *sti, stm->kitInformation())
        setValue(sti->dataId(), sti->defaultValue(this));

    setDisplayName(QCoreApplication::translate("ProjectExplorer::Kit", "Unnamed"));
    setIconPath(QLatin1String(":///DESKTOP///"));
}

Kit::~Kit()
{
    delete d;
}

void Kit::blockNotification()
{
    ++d->m_nestedBlockingLevel;
}

void Kit::unblockNotification()
{
    --d->m_nestedBlockingLevel;
    if (d->m_nestedBlockingLevel > 0)
        return;
    if (d->m_mustNotify)
        kitUpdated();
    d->m_mustNotify = false;
}

Kit *Kit::clone(bool keepName) const
{
    Kit *k = new Kit;
    if (keepName)
        k->d->m_displayName = d->m_displayName;
    else
        k->d->m_displayName = QCoreApplication::translate("ProjectExplorer::Kit", "Clone of %1")
                .arg(d->m_displayName);
    k->d->m_autodetected = false;
    k->d->m_data = d->m_data;
    k->d->m_isValid = d->m_isValid;
    k->d->m_icon = d->m_icon;
    k->d->m_iconPath = d->m_iconPath;
    return k;
}

void Kit::copyFrom(const Kit *k)
{
    KitGuard g(this);
    d->m_data = k->d->m_data;
    d->m_iconPath = k->d->m_iconPath;
    d->m_icon = k->d->m_icon;
    d->m_autodetected = k->d->m_autodetected;
    d->m_displayName = k->d->m_displayName;
    d->m_mustNotify = true;
}

bool Kit::isValid() const
{
    return d->m_id.isValid() && d->m_isValid;
}

QList<Task> Kit::validate() const
{
    QList<Task> result;
    QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
    d->m_isValid = true;
    foreach (KitInformation *i, infoList) {
        QList<Task> tmp = i->validate(this);
        foreach (const Task &t, tmp) {
            if (t.type == Task::Error)
                d->m_isValid = false;
        }
        result.append(tmp);
    }
    qSort(result);
    return result;
}

void Kit::fix()
{
    KitGuard g(this);
    foreach (KitInformation *i, KitManager::instance()->kitInformation())
        i->fix(this);
}

QString Kit::displayName() const
{
    return d->m_displayName;
}

static QString candidateName(const QString &name, const QString &postfix)
{
    if (name.contains(postfix))
        return QString();
    QString candidate = name;
    if (!candidate.isEmpty())
        candidate.append(QLatin1Char('-'));
    candidate.append(postfix);
    return candidate;
}

void Kit::setDisplayName(const QString &name)
{
    KitManager *km = KitManager::instance();
    QList<KitInformation *> kitInfo = km->kitInformation();

    QStringList nameList;
    foreach (Kit *k, km->kits()) {
        if (k == this)
            continue;
        nameList << k->displayName();
        foreach (KitInformation *ki, kitInfo) {
            const QString postfix = ki->displayNamePostfix(k);
            if (!postfix.isEmpty())
                nameList << candidateName(k->displayName(), postfix);
        }
    }

    QStringList candidateNames;
    candidateNames << name;

    foreach (KitInformation *ki, kitInfo) {
        const QString postfix = ki->displayNamePostfix(this);
        if (!postfix.isEmpty())
            candidateNames << candidateName(name, postfix);
    }

    QString uniqueName = Project::makeUnique(name, nameList);
    if (uniqueName != name) {
        foreach (const QString &candidate, candidateNames) {
            const QString tmp = Project::makeUnique(candidate, nameList);
            if (tmp == candidate) {
                uniqueName = tmp;
                break;
            }
        }
    }

    if (d->m_displayName == uniqueName)
        return;
    d->m_displayName = uniqueName;
    kitUpdated();
}

QString Kit::fileSystemFriendlyName() const
{
    QString name = cleanName(displayName());
    foreach (Kit *i, KitManager::instance()->kits()) {
        if (i == this)
            continue;
        if (name == cleanName(i->displayName())) {
            // append part of the kit id: That should be unique enough;-)
            // Leading { will be turned into _ which should be fine.
            name = cleanName(name + QLatin1Char('_') + (id().toString().left(7)));
            break;
        }
    }
    return name;
}

bool Kit::isAutoDetected() const
{
    return d->m_autodetected;
}

Core::Id Kit::id() const
{
    return d->m_id;
}

QIcon Kit::icon() const
{
    return d->m_icon;
}

QString Kit::iconPath() const
{
    return d->m_iconPath;
}

void Kit::setIconPath(const QString &path)
{
    if (d->m_iconPath == path)
        return;
    d->m_iconPath = path;
    if (path.isNull())
        d->m_icon = QIcon();
    else if (path == QLatin1String(":///DESKTOP///"))
        d->m_icon = qApp->style()->standardIcon(QStyle::SP_ComputerIcon);
    else
        d->m_icon = QIcon(path);
    kitUpdated();
}

QVariant Kit::value(const Core::Id &key, const QVariant &unset) const
{
    return d->m_data.value(key, unset);
}

bool Kit::hasValue(const Core::Id &key) const
{
    return d->m_data.contains(key);
}

void Kit::setValue(const Core::Id &key, const QVariant &value)
{
    if (d->m_data.value(key) == value)
        return;
    d->m_data.insert(key, value);
    kitUpdated();
}

void Kit::removeKey(const Core::Id &key)
{
    if (!d->m_data.contains(key))
        return;
    d->m_data.remove(key);
    kitUpdated();
}

bool Kit::isDataEqual(const Kit *other) const
{
    return d->m_data == other->d->m_data;
}

bool Kit::isEqual(const Kit *other) const
{
    return isDataEqual(other)
            && d->m_iconPath == other->d->m_iconPath
            && d->m_displayName == other->d->m_displayName;
}

QVariantMap Kit::toMap() const
{
    QVariantMap data;
    data.insert(QLatin1String(ID_KEY), QString::fromLatin1(d->m_id.name()));
    data.insert(QLatin1String(DISPLAYNAME_KEY), d->m_displayName);
    data.insert(QLatin1String(AUTODETECTED_KEY), d->m_autodetected);
    data.insert(QLatin1String(ICON_KEY), d->m_iconPath);

    QVariantMap extra;
    foreach (const Core::Id &key, d->m_data.keys())
        extra.insert(QString::fromLatin1(key.name().constData()), d->m_data.value(key));
    data.insert(QLatin1String(DATA_KEY), extra);

    return data;
}

void Kit::addToEnvironment(Utils::Environment &env) const
{
    QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
    foreach (KitInformation *ki, infoList)
        ki->addToEnvironment(this, env);
}

QString Kit::toHtml()
{
    QString rc;
    QTextStream str(&rc);
    str << "";
    str << "
" << displayName() << "
";
    str << "
";

    if (!isValid()) {
        QList<Task> issues = validate();
        str << "
";
        foreach (const Task &t, issues) {
            str << "";
            switch (t.type) {
            case Task::Error:
                str << QCoreApplication::translate("ProjectExplorer::Kit", "Error:");
                break;
            case Task::Warning:
                str << QCoreApplication::translate("ProjectExplorer::Kit", "Warning:");
                break;
            case Task::Unknown:
            default:
                break;
            }
            str << "" << t.description << "
";
        }
        str << "
";
    }

    QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
    foreach (KitInformation *ki, infoList) {
        KitInformation::ItemList list = ki->toUserOutput(this);
        foreach (const KitInformation::Item &j, list)
            str << "
" << j.first << ":	" << j.second << "
";
    }
    str << "
";
    return rc;
}

bool Kit::fromMap(const QVariantMap &data)
{
    KitGuard g(this);
    const QString id = data.value(QLatin1String(ID_KEY)).toString();
    if (id.isEmpty())
        return false;
    d->m_id = Core::Id(id);
    d->m_autodetected = data.value(QLatin1String(AUTODETECTED_KEY)).toBool();
    setDisplayName(data.value(QLatin1String(DISPLAYNAME_KEY)).toString());
    setIconPath(data.value(QLatin1String(ICON_KEY)).toString());

    QVariantMap extra = data.value(QLatin1String(DATA_KEY)).toMap();
    foreach (const QString &key, extra.keys())
        setValue(Core::Id(key), extra.value(key));

    return true;
}

void Kit::setAutoDetected(bool detected)
{
    d->m_autodetected = detected;
}

void Kit::kitUpdated()
{
    if (d->m_nestedBlockingLevel > 0) {
        d->m_mustNotify = true;
        return;
    }
    validate();
    KitManager::instance()->notifyAboutUpdate(this);
}

} // namespace ProjectExplorer
<|endoftext|>


<commit_before>/*
 // Copyright (c) 2015-2016-2016 Pierre Guillot.
 // For information on usage and redistribution, and for a DISCLAIMER OF ALL
 // WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/

#include <iostream>
#include "test.hpp"
extern "C"
{
#include "../thread/src/thd.h"
}

#define XPD_TEST_NLOOP  16
#define XPD_TEST_NTHD   4

static xpd::mutex gmutex;

class post_tester : private xpd::instance
{
public:

    ~post_tester()
    {
        if(m_patch)
        {
            xpd::instance::close(m_patch);
        }
    }

    bool load(std::string const& name)
    {
        m_patch = xpd::instance::load(name, "");
        return bool(m_patch);
    }

    bool prepare(const int nins, const int nouts, const int samplerate, const int nsamples)
    {
        xpd::instance::prepare(nins, nouts, samplerate, nsamples);
        m_blksize = nsamples;
        return xpd::instance::samplerate() == samplerate;
    }

    void send(std::vector<xpd::atom> const& vec)
    {
        xpd::instance::send(m_tfrom, xpd::symbol("list"), vec);
    }

    void receive(xpd::console::post const& post) xpd_final
    {
        m_counter++;
    }

    size_t counter() const xpd_noexcept
    {
        return m_counter;
    }

    static void test(post_tester* inst)
    {
        gmutex.lock();
        for(size_t i = 0; i < XPD_TEST_NLOOP; i++)
        {
            inst->perform(inst->m_blksize, 0, NULL, 0, NULL);
        }
        gmutex.unlock();
    }

private:
    xpd::patch m_patch;
    xpd::tie   m_tfrom;
    xpd::tie   m_tto;
    size_t     m_counter;
    size_t     m_blksize;
};

TEST_CASE("instance", "[instance post]")
{
    post_tester inst[XPD_TEST_NTHD];
    thd_thread  thd[XPD_TEST_NTHD];

    SECTION("post")
    {
        for(size_t i = 0; i < XPD_TEST_NTHD; ++i)
        {
            REQUIRE(inst[i].load("test_post.pd"));
            REQUIRE(inst[i].prepare(0, 0, 44100, 256));
            thd_thread_detach(thd+i, (thd_thread_method)(&post_tester::test), inst+i);
        }

        for(size_t i = 0; i < XPD_TEST_NTHD; ++i)
        {
            thd_thread_join(thd+i);
            CHECK(inst[i].counter() == XPD_TEST_NLOOP);
        }
    }
}

#undef XPD_TEST_NLOOP

<commit_msg>go to all-in-one instance test<commit_after><|endoftext|>


<commit_before>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2008 projectM Team
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * See 'LICENSE.txt' included within this release
 *
 */

#include "video_init.h"
#include <projectM.hpp>
#include "sdltoprojectM.h"
#include "ConfigFile.h"
#include "getConfigFilename.h"

// FIXME: portable includes?
// i just added what works for me -fatray
#include <GL/gl.h>
#include <assert.h>

projectM *globalPM= NULL;

// window stuff
int wvw, wvh, fvw, fvh;
bool fullscreen;

void renderLoop();

// texture test
bool doTextureTest = false;
void textureTest();

// memleak test
bool doMemleakTest = false;
int memLeakIterations = 100;

int main(int argc, char **argv) {

	// fix `fullscreen quit kills mouse` issue.
	atexit(SDL_Quit);

	std::string config_filename = getConfigFilename();
	ConfigFile config(config_filename);

	// window dimensions from configfile
	wvw = config.read<int>("Window Width", 512);
	wvh = config.read<int>("Window Height", 512);
	fullscreen = config.read("Fullscreen", true);

	init_display(wvw, wvh, &fvw, &fvh, fullscreen);

	SDL_WM_SetCaption(PROJECTM_TITLE, NULL);

	// memleak test
	while (doMemleakTest) {
		static int k = 0;
		std::cerr << "[iter " << k++ << "]" << std::endl;
		globalPM = new projectM(config_filename);
		assert(globalPM);
		delete (globalPM);
		if (k >= memLeakIterations)
			break;
	}

	globalPM = new projectM(config_filename);

	// if started fullscreen, give PM new viewport dimensions
	if (fullscreen)
		globalPM->projectM_resetGL(fvw, fvh);

	renderLoop();

	// not reached
	return 1;
}

void renderLoop() {
	while (1) {
		projectMEvent evt;
		projectMKeycode key;
		projectMModifier mod;

		/** Process SDL events */
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			/** Translate into projectM codes and process */
			evt = sdl2pmEvent(event);
			key = sdl2pmKeycode(event.key.keysym.sym);
			mod = sdl2pmModifier(event.key.keysym.mod);

			switch (evt) {
			case PROJECTM_KEYDOWN:
				switch (key) {
				case PROJECTM_K_ESCAPE:
					delete(globalPM);
					exit(0);
					break;
				case PROJECTM_K_f: {
					fullscreen = !fullscreen;
					if (fullscreen) {
						resize_display(fvw, fvh, fullscreen);
						globalPM->projectM_resetGL(fvw, fvh);
					} else {
						resize_display(wvw, wvh, fullscreen);
						globalPM->projectM_resetGL(wvw, wvh);
					}
					break;
				}
				case PROJECTM_K_q:
					exit(1);
					break;
				default:
					globalPM->key_handler(evt, key, mod);
				}
				break;

			case PROJECTM_VIDEORESIZE:
				wvw = event.resize.w;
				wvh = event.resize.h;
				resize_display(wvw, wvh, 0);
				globalPM->projectM_resetGL(wvw, wvh);
				break;

			default:
				// not for us, give it to projectM
				globalPM->key_handler(evt, key, mod);
				break;
			}
		}

		globalPM->renderFrame();

		if (doTextureTest)
			textureTest();

		SDL_GL_SwapBuffers();
	}
}

void textureTest() {
	static int textureHandle = globalPM->initRenderToTexture();
	static int frame = 0;
	frame++;

	glClear(GL_COLOR_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	if (fullscreen)
		glViewport(0, 0, fvw, fvh);
	else
		glViewport(0, 0, wvw, wvh);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-1, 1, -1, 1, 2, 10);

	glEnable(GL_DEPTH_TEST);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(cos(frame*0.023), cos(frame*0.017), -5+sin(frame*0.022)*2);
	glRotatef(sin(frame*0.0043)*360, sin(frame*0.0017)*360, sin(frame *0.0032)
			*360, 1);

	glEnable(GL_TEXTURE_2D);
	glMatrixMode(GL_TEXTURE);
	glLoadIdentity();

	glBindTexture(GL_TEXTURE_2D, textureHandle);
	glColor4d(1.0, 1.0, 1.0, 1.0);

	glBegin(GL_QUADS);
	glTexCoord2d(0, 1);
	glVertex3d(-0.8, 0.8, 0);
	glTexCoord2d(0, 0);
	glVertex3d(-0.8, -0.8, 0);
	glTexCoord2d(1, 0);
	glVertex3d(0.8, -0.8, 0);
	glTexCoord2d(1, 1);
	glVertex3d(0.8, 0.8, 0);
	glEnd();

	glDisable(GL_TEXTURE_2D);

	glMatrixMode(GL_MODELVIEW);
	glDisable(GL_DEPTH_TEST);
}

<commit_msg>projectM-test random sound data<commit_after>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2008 projectM Team
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * See 'LICENSE.txt' included within this release
 *
 */

#include "video_init.h"
#include <projectM.hpp>
#include "sdltoprojectM.h"
#include "ConfigFile.h"
#include "getConfigFilename.h"
#include <stdlib.h>

// FIXME: portable includes?
// i just added what works for me -fatray
#include <GL/gl.h>
#include <assert.h>

projectM *globalPM= NULL;

// window stuff
int wvw, wvh, fvw, fvh;
bool fullscreen;

void renderLoop();

// texture test
bool doTextureTest = false;
void textureTest();

// memleak test
bool doMemleakTest = false;
int memLeakIterations = 100;

int main(int argc, char **argv) {

	// fix `fullscreen quit kills mouse` issue.
	atexit(SDL_Quit);

	std::string config_filename = getConfigFilename();
	ConfigFile config(config_filename);

	// window dimensions from configfile
	wvw = config.read<int>("Window Width", 512);
	wvh = config.read<int>("Window Height", 512);
	fullscreen = config.read("Fullscreen", true);

	init_display(wvw, wvh, &fvw, &fvh, fullscreen);

	SDL_WM_SetCaption(PROJECTM_TITLE, NULL);

	// memleak test
	while (doMemleakTest) {
		static int k = 0;
		std::cerr << "[iter " << k++ << "]" << std::endl;
		globalPM = new projectM(config_filename);
		assert(globalPM);
		delete (globalPM);
		if (k >= memLeakIterations)
			break;
	}

	globalPM = new projectM(config_filename);

	// if started fullscreen, give PM new viewport dimensions
	if (fullscreen)
		globalPM->projectM_resetGL(fvw, fvh);

	renderLoop();

	// not reached
	return 1;
}

float fakePCM[512];

void renderLoop() {
	while (1) {
		projectMEvent evt;
		projectMKeycode key;
		projectMModifier mod;

		/** Process SDL events */
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			/** Translate into projectM codes and process */
			evt = sdl2pmEvent(event);
			key = sdl2pmKeycode(event.key.keysym.sym);
			mod = sdl2pmModifier(event.key.keysym.mod);

			switch (evt) {
			case PROJECTM_KEYDOWN:
				switch (key) {
				case PROJECTM_K_ESCAPE:
					delete(globalPM);
					exit(0);
					break;
				case PROJECTM_K_f: {
					fullscreen = !fullscreen;
					if (fullscreen) {
						resize_display(fvw, fvh, fullscreen);
						globalPM->projectM_resetGL(fvw, fvh);
					} else {
						resize_display(wvw, wvh, fullscreen);
						globalPM->projectM_resetGL(wvw, wvh);
					}
					break;
				}
				case PROJECTM_K_q:
					exit(1);
					break;
				default:
					globalPM->key_handler(evt, key, mod);
				}
				break;

			case PROJECTM_VIDEORESIZE:
				wvw = event.resize.w;
				wvh = event.resize.h;
				resize_display(wvw, wvh, 0);
				globalPM->projectM_resetGL(wvw, wvh);
				break;

			default:
				// not for us, give it to projectM
				globalPM->key_handler(evt, key, mod);
				break;
			}
		}
 fakePCM[0]=0;
        for (int x = 1; x< 512;x++)
        {
                fakePCM[x] = fakePCM[x-1] + (rand()%200 - 100) *.002;
        }

        globalPM->pcm()->addPCMfloat(fakePCM, 512);

		globalPM->renderFrame();

		if (doTextureTest)
			textureTest();

		SDL_GL_SwapBuffers();
	}
}

void textureTest() {
	static int textureHandle = globalPM->initRenderToTexture();
	static int frame = 0;
	frame++;

	glClear(GL_COLOR_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	if (fullscreen)
		glViewport(0, 0, fvw, fvh);
	else
		glViewport(0, 0, wvw, wvh);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-1, 1, -1, 1, 2, 10);

	glEnable(GL_DEPTH_TEST);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(cos(frame*0.023), cos(frame*0.017), -5+sin(frame*0.022)*2);
	glRotatef(sin(frame*0.0043)*360, sin(frame*0.0017)*360, sin(frame *0.0032)
			*360, 1);

	glEnable(GL_TEXTURE_2D);
	glMatrixMode(GL_TEXTURE);
	glLoadIdentity();

	glBindTexture(GL_TEXTURE_2D, textureHandle);
	glColor4d(1.0, 1.0, 1.0, 1.0);

	glBegin(GL_QUADS);
	glTexCoord2d(0, 1);
	glVertex3d(-0.8, 0.8, 0);
	glTexCoord2d(0, 0);
	glVertex3d(-0.8, -0.8, 0);
	glTexCoord2d(1, 0);
	glVertex3d(0.8, -0.8, 0);
	glTexCoord2d(1, 1);
	glVertex3d(0.8, 0.8, 0);
	glEnd();

	glDisable(GL_TEXTURE_2D);

	glMatrixMode(GL_MODELVIEW);
	glDisable(GL_DEPTH_TEST);
}

<|endoftext|>


<commit_before>#include "DNSDataParser.hpp"

audioObject::audioObject ()
: distance (0)
, angle (0) {
}

speakerData::speakerData ()
: speakerid ("")
, objects{} {
}

dataParser::dataParser ()
: _filereader ()
, _filewriter () {
}

speakerData dataParser::parseClientData (std::string jsonstring,
std::string client_id,
std::map<std::string, std::vector<float>>& objects) {
    Jzon::Node rootNode = _filereader.parseString (jsonstring);
    speakerData ret_speaker;

    for (Jzon::NamedNode node : rootNode) {
        if (node.first == client_id) {
            ret_speaker.speakerid = node.first;
            for (Jzon::NamedNode sub_node : node.second) {
                audioObject object;
                std::string key          = sub_node.first;
                object.distance          = sub_node.second.get ("distance").toFloat ();
                object.angle             = sub_node.second.get ("angle").toFloat ();
                ret_speaker.objects[key] = object;
            }
        } else {
            for (Jzon::NamedNode sub_node : node.second) {
                std::string key = sub_node.first;
                int distance = sub_node.second.get ("distance").toInt ();
                if (distance != -1) {
                    objects[key].push_back (distance);
                }
            }
        }
    }

    return ret_speaker;
}

std::map<std::string, std::string> dataParser::parseAudioSourceData (std::string jsonstring) {
    std::map<std::string, std::string> ret;
    Jzon::Node root_node = _filereader.parseString (jsonstring);

    for (Jzon::NamedNode sub_node : root_node) {
        std::string uri, name;
        name = sub_node.first;
        uri  = sub_node.second.toString ();

        if (30 < name.length ()) { // truncate string to MAX 30
            name.erase (30, std::string::npos);
        }
        for (char& c : name) { // replace any non alphanumerical characters
            if (!isalnum (c)) {
                c = '_';
            }
        }

        ret[name] = uri;
    }

    return ret;
}

std::string dataParser::composeClientData (speakerData speaker) {
    std::string ret_str;
    Jzon::Node root_node, speaker_node, object_node;

    for (auto object : speaker.objects) {
        object_node.add ("distance", object.second.distance);
        object_node.add ("angle", object.second.angle);
        speaker_node.add (object.first, object_node);
    }
    root_node.add (speaker.speakerid, speaker_node);
    _filewriter.writeString (root_node, ret_str);
    return ret_str;
}
<commit_msg>add support for '.' dots in the object names<commit_after>#include "DNSDataParser.hpp"

audioObject::audioObject ()
: distance (0)
, angle (0) {
}

speakerData::speakerData ()
: speakerid ("")
, objects{} {
}

dataParser::dataParser ()
: _filereader ()
, _filewriter () {
}

speakerData dataParser::parseClientData (std::string jsonstring,
std::string client_id,
std::map<std::string, std::vector<float>>& objects) {
    Jzon::Node rootNode = _filereader.parseString (jsonstring);
    speakerData ret_speaker;

    for (Jzon::NamedNode node : rootNode) {
        if (node.first == client_id) {
            ret_speaker.speakerid = node.first;
            for (Jzon::NamedNode sub_node : node.second) {
                audioObject object;
                std::string key          = sub_node.first;
                object.distance          = sub_node.second.get ("distance").toFloat ();
                object.angle             = sub_node.second.get ("angle").toFloat ();
                ret_speaker.objects[key] = object;
            }
        } else {
            for (Jzon::NamedNode sub_node : node.second) {
                std::string key = sub_node.first;
                int distance = sub_node.second.get ("distance").toInt ();
                if (distance != -1) {
                    objects[key].push_back (distance);
                }
            }
        }
    }

    return ret_speaker;
}

std::map<std::string, std::string> dataParser::parseAudioSourceData (std::string jsonstring) {
    std::map<std::string, std::string> ret;
    Jzon::Node root_node = _filereader.parseString (jsonstring);

    for (Jzon::NamedNode sub_node : root_node) {
        std::string uri, name;
        name = sub_node.first;
        uri  = sub_node.second.toString ();

        if (30 < name.length ()) { // truncate string to MAX 30
            name.erase (30, std::string::npos);
        }

        char last_c = '.'; // set '.' to dissalow the name "."
        for (char& c : name) {
            // dissalow any special characters
            if (!isalnum (c)) {
                // disallow multiple consecutive dots
                if (!(c == '.' && last_c != '.')) {
                    c = '_';
                }
                last_c = c;
            }
        }

        ret[name] = uri;
    }

    return ret;
}

std::string dataParser::composeClientData (speakerData speaker) {
    std::string ret_str;
    Jzon::Node root_node, speaker_node, object_node;

    for (auto object : speaker.objects) {
        object_node.add ("distance", object.second.distance);
        object_node.add ("angle", object.second.angle);
        speaker_node.add (object.first, object_node);
    }
    root_node.add (speaker.speakerid, speaker_node);
    _filewriter.writeString (root_node, ret_str);
    return ret_str;
}
<|endoftext|>


<commit_before>/***********************************************************************
 row.cpp - Implements the Row class.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ 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.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "row.h"
#include "result.h"
#include "exceptions.h"

namespace mysqlpp {

Row::Row(const MYSQL_ROW& d, const ResUse* r,
		unsigned long* jj, bool te) :
OptionalExceptions(te),
res_(r),
initialized_(false)
{
	if (!d || !r) {
		if (throw_exceptions()) {
			throw BadQuery("ROW or RES is NULL");
		}
		else {
			return;
		}
	}
	data_.clear();
	is_nulls_.clear();
	initialized_ = true;
	for (unsigned int i = 0; i < size(); i++) {
		data_.insert(data_.end(),
				(d[i] ?  std::string(d[i], jj[i]) : std::string("NULL")));
		is_nulls_.insert(is_nulls_.end(), d[i] ? false : true);
	}
}

Row::~Row()
{
	data_.clear();
	is_nulls_.clear();
	initialized_ = false;
}

Row::size_type Row::size() const
{
	return res_->num_fields();
}

const ColData Row::at(size_type i) const
{
	if (initialized_) {
		const std::string& s = data_.at(i);
		return ColData(s.c_str(), s.length(), res_->types(i),
				is_nulls_[i]);
	}
	else {
		if (throw_exceptions())
			throw std::out_of_range("Row not initialized");
		else
			return ColData();
	}
}

const ColData Row::operator [](const char* field) const
{
	size_type si = res_->field_num(std::string(field));
	if (si < size()) {
		return at(si);
	}
	else {
		throw BadFieldName(field);
	}
}

value_list_ba<FieldNames, do_nothing_type0>
Row::field_list(const char* d) const
{
	return value_list_ba<FieldNames, do_nothing_type0>
			(parent().names(), d, do_nothing);
}

template <class Manip>
value_list_ba<FieldNames, Manip>
Row::field_list(const char *d, Manip m) const
{
	return value_list_ba<FieldNames, Manip>(parent().names(), d, m);
}

template <class Manip>
value_list_b<FieldNames, Manip>
Row::field_list(const char *d, Manip m, const std::vector<bool>& vb) const
{
	return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(const char* d, const std::vector<bool>& vb) const
{
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, d, quote);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(const std::vector<bool>& vb) const
{
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, ",", quote);
}

template <class Manip> value_list_b<FieldNames, Manip>
Row::field_list(const char* d, Manip m, bool t0, bool t1, bool t2,
		bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9,
		bool ta, bool tb, bool tc) const
{
	std::vector<bool> vb;
	create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4,
			t5, t6, t7, t8, t9, ta, tb, tc);
	return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(const char *d, bool t0, bool t1, bool t2, bool t3,
		bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta,
		bool tb, bool tc) const
{
	std::vector<bool> vb;
	create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4,
			t5, t6, t7, t8, t9, ta, tb, tc);
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, d, quote);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(bool t0, bool t1, bool t2, bool t3, bool t4, bool t5,
		bool t6, bool t7, bool t8, bool t9, bool ta, bool tb,
		bool tc) const
{
	std::vector<bool> vb;
	create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4,
			t5, t6, t7, t8, t9, ta, tb, tc);
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, ",", quote);
}

equal_list_ba<FieldNames, Row, quote_type0>
Row::equal_list(const char* d, const char* e) const
{
	return equal_list_ba<FieldNames, Row, quote_type0>(
			parent().names(), *this, d, e, quote);
}

template <class Manip>
equal_list_ba<FieldNames, Row, Manip>
Row::equal_list(const char* d, const char* e, Manip m) const
{
	return equal_list_ba<FieldNames, Row, Manip>(
			parent().names(), *this, d, e, m);
}

} // end namespace mysqlpp

<commit_msg>Minor speed optimizations in the Row() ctor that copies data from a MYSQL_ROW structure, and in Row::size().  Patch by Korolyov Ilya <breeze@begun.ru>.<commit_after>/***********************************************************************
 row.cpp - Implements the Row class.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ 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.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "row.h"
#include "result.h"
#include "exceptions.h"

namespace mysqlpp {

Row::Row(const MYSQL_ROW& d, const ResUse* r,
		unsigned long* jj, bool te) :
OptionalExceptions(te),
res_(r),
initialized_(false)
{
	if (!d || !r) {
		if (throw_exceptions()) {
			throw BadQuery("ROW or RES is NULL");
		}
		else {
			return;
		}
	}

	data_.clear();
	is_nulls_.clear();
	initialized_ = true;

	size_type num_fields = size();
	for (size_type i = 0; i < num_fields; ++i) {
		data_.insert(data_.end(),
				(d[i] ?  std::string(d[i], jj[i]) : std::string("NULL")));
		is_nulls_.insert(is_nulls_.end(), d[i] ? false : true);
	}
}

Row::~Row()
{
	data_.clear();
	is_nulls_.clear();
	initialized_ = false;
}

Row::size_type Row::size() const
{
	return data_.size();
}

const ColData Row::at(size_type i) const
{
	if (initialized_) {
		const std::string& s = data_.at(i);
		return ColData(s.c_str(), s.length(), res_->types(i),
				is_nulls_[i]);
	}
	else {
		if (throw_exceptions())
			throw std::out_of_range("Row not initialized");
		else
			return ColData();
	}
}

const ColData Row::operator [](const char* field) const
{
	size_type si = res_->field_num(std::string(field));
	if (si < size()) {
		return at(si);
	}
	else {
		throw BadFieldName(field);
	}
}

value_list_ba<FieldNames, do_nothing_type0>
Row::field_list(const char* d) const
{
	return value_list_ba<FieldNames, do_nothing_type0>
			(parent().names(), d, do_nothing);
}

template <class Manip>
value_list_ba<FieldNames, Manip>
Row::field_list(const char *d, Manip m) const
{
	return value_list_ba<FieldNames, Manip>(parent().names(), d, m);
}

template <class Manip>
value_list_b<FieldNames, Manip>
Row::field_list(const char *d, Manip m, const std::vector<bool>& vb) const
{
	return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(const char* d, const std::vector<bool>& vb) const
{
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, d, quote);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(const std::vector<bool>& vb) const
{
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, ",", quote);
}

template <class Manip> value_list_b<FieldNames, Manip>
Row::field_list(const char* d, Manip m, bool t0, bool t1, bool t2,
		bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9,
		bool ta, bool tb, bool tc) const
{
	std::vector<bool> vb;
	create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4,
			t5, t6, t7, t8, t9, ta, tb, tc);
	return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(const char *d, bool t0, bool t1, bool t2, bool t3,
		bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta,
		bool tb, bool tc) const
{
	std::vector<bool> vb;
	create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4,
			t5, t6, t7, t8, t9, ta, tb, tc);
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, d, quote);
}

value_list_b<FieldNames, quote_type0>
Row::field_list(bool t0, bool t1, bool t2, bool t3, bool t4, bool t5,
		bool t6, bool t7, bool t8, bool t9, bool ta, bool tb,
		bool tc) const
{
	std::vector<bool> vb;
	create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4,
			t5, t6, t7, t8, t9, ta, tb, tc);
	return value_list_b<FieldNames, quote_type0>(parent().names(),
			vb, ",", quote);
}

equal_list_ba<FieldNames, Row, quote_type0>
Row::equal_list(const char* d, const char* e) const
{
	return equal_list_ba<FieldNames, Row, quote_type0>(
			parent().names(), *this, d, e, quote);
}

template <class Manip>
equal_list_ba<FieldNames, Row, Manip>
Row::equal_list(const char* d, const char* e, Manip m) const
{
	return equal_list_ba<FieldNames, Row, Manip>(
			parent().names(), *this, d, e, m);
}

} // end namespace mysqlpp

<|endoftext|>


<commit_before>/***********************************************************************
 row.cpp - Implements the Row class.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ 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.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "row.h"
#include "result.h"
#include "exceptions.h"

namespace mysqlpp {

Row::size_type Row::size() const
{
	return res->num_fields();
}

const ColData Row::operator[] (size_type i) const
{
	if (!initialized) {
		if (throw_exceptions)
			throw BadQuery("Row not initialized");
		else
			return ColData();
	}

	return ColData(data.at(i).c_str(), res->types(i), is_nulls[i]);
}

const ColData Row::lookup_by_name(const char* i) const
{
	int si = res->field_num(std::string(i));
	if (si < res->num_fields()) {
		return (*this)[si];
	}
	else {
		throw BadFieldName(i);
	}
}

} // end namespace mysqlpp

<commit_msg>Whitespace change<commit_after>/***********************************************************************
 row.cpp - Implements the Row class.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ 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.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "row.h"
#include "result.h"
#include "exceptions.h"

namespace mysqlpp {

Row::size_type Row::size() const
{
	return res->num_fields();
}

const ColData Row::operator [](size_type i) const
{
	if (!initialized) {
		if (throw_exceptions)
			throw BadQuery("Row not initialized");
		else
			return ColData();
	}

	return ColData(data.at(i).c_str(), res->types(i), is_nulls[i]);
}

const ColData Row::lookup_by_name(const char* i) const
{
	int si = res->field_num(std::string(i));
	if (si < res->num_fields()) {
		return (*this)[si];
	}
	else {
		throw BadFieldName(i);
	}
}

} // end namespace mysqlpp

<|endoftext|>


<commit_before>// FIXME: The first two includes should probably be swapped!
#include "HalideRuntime.h"
#include "runtime_internal.h"
#include "printer.h"

namespace Halide { namespace Runtime { namespace Internal {

WEAK void default_error_handler(void *user_context, const char *msg) {
    char buf[4096];
    char *dst = halide_string_to_string(buf, buf + 4095, "Error: ");
    dst = halide_string_to_string(dst, buf + 4095, msg);
    // We still have one character free. Add a newline if there
    // isn't one already.
    if (dst[-1] != '\n') {
        dst[0] = '\n';
        dst[1] = 0;
    }
    halide_print(user_context, buf);
    abort();
}

WEAK void (*halide_error_handler)(void *, const char *) = default_error_handler;

}}} // namespace Halide::Runtime::Internal

extern "C" {

WEAK void halide_error(void *user_context, const char *msg) {
    (*halide_error_handler)(user_context, msg);
}

WEAK void (*halide_set_error_handler(void (*handler)(void *, const char *)))(void *, const char *) {
    void (*result)(void *, const char *) = halide_error_handler;
    halide_error_handler = handler;
    return result;
}

WEAK int halide_error_bounds_inference_call_failed(void *user_context, const char *extern_stage_name, int result) {
    error(user_context)
        << "Bounds inference call to external stage " << extern_stage_name
        << " returned non-zero value: " << result;
    return result;
}

WEAK int halide_error_extern_stage_failed(void *user_context, const char *extern_stage_name, int result) {
    error(user_context)
        << "Call to external stage " << extern_stage_name
        << " returned non-zero value: " << result;
    return result;
}

WEAK int halide_error_explicit_bounds_too_small(void *user_context, const char *func_name, const char *var_name,
                                                int min_bound, int max_bound, int min_required, int max_required) {
    error(user_context)
        << "Bounds given for " << var_name << " in " << func_name
        << " (from " << min_bound << " to " << max_bound
        << ") do not cover required region (from " << min_required
        << " to " << max_required << ")";
    return halide_error_code_explicit_bounds_too_small;
}

WEAK int halide_error_bad_elem_size(void *user_context, const char *func_name,
                                    const char *type_name, int elem_size_given, int correct_elem_size) {
    error(user_context)
        << func_name << " has type " << type_name
        << " but elem_size of the buffer passed in is "
        << elem_size_given << " instead of " << correct_elem_size;
    return halide_error_code_bad_elem_size;
}

WEAK int halide_error_access_out_of_bounds(void *user_context, const char *func_name,
                                           int dimension, int min_touched, int max_touched,
                                           int min_valid, int max_valid) {
    if (min_touched < min_valid) {
        error(user_context)
            << func_name << " is accessed at " << min_touched
            << ", which is before the min (" << min_valid
            << ") in dimension " << dimension;
    } else if (max_touched > max_valid) {
        error(user_context)
            << func_name << " is accessed at " << max_touched
            << ", which is beyond the max (" << max_valid
            << ") in dimension " << dimension;
    }
    return halide_error_code_access_out_of_bounds;
}

WEAK int halide_error_buffer_allocation_too_large(void *user_context, const char *buffer_name, int64_t allocation_size, int64_t max_size) {
    error(user_context)
        << "Total allocation for buffer " << buffer_name
        << " is " << allocation_size
        << ", which exceeds the maximum size of " << max_size;
    return halide_error_code_buffer_allocation_too_large;
}

WEAK int halide_error_buffer_extents_too_large(void *user_context, const char *buffer_name, int64_t actual_size, int64_t max_size) {
    error(user_context)
        << "Product of extents for buffer " << buffer_name
        << " is " << actual_size
        << ", which exceeds the maximum size of " << max_size;
    return halide_error_code_buffer_extents_too_large;
}

WEAK int halide_error_constraints_make_required_region_smaller(void *user_context, const char *buffer_name,
                                                               int dimension,
                                                               int constrained_min, int constrained_extent,
                                                               int required_min, int required_extent) {
    int required_max = required_min + required_extent - 1;
    int constrained_max = constrained_min + required_extent - 1;
    error(user_context)
        << "Applying the constraints on " << buffer_name
        << " to the required region made it smaller. "
        << "Required size: " << required_min << " to " << required_max << ". "
        << "Constrained size: " << constrained_min << " to " << constrained_max << ".";
    return halide_error_code_constraints_make_required_region_smaller;
}

WEAK int halide_error_constraint_violated(void *user_context, const char *var, int val,
                                          const char *constrained_var, int constrained_val) {
    error(user_context)
        << "Constraint violated: " << var << " (" << val
        << ") == " << constrained_var << " (" << constrained_var << ")";
    return halide_error_code_constraint_violated;
}

WEAK int halide_error_param_too_small_i64(void *user_context, const char *param_name,
                                          int64_t val, int64_t min_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at least " << min_val;
    return halide_error_code_param_too_small;
}

WEAK int halide_error_param_too_small_u64(void *user_context, const char *param_name,
                                          uint64_t val, uint64_t min_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at least " << min_val;
    return halide_error_code_param_too_small;
}

WEAK int halide_error_param_too_small_f64(void *user_context, const char *param_name,
                                          double val, double min_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at least " << min_val;
    return halide_error_code_param_too_small;
}

WEAK int halide_error_param_too_large_i64(void *user_context, const char *param_name,
                                          int64_t val, int64_t max_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at most " << max_val;
    return halide_error_code_param_too_large;
}

WEAK int halide_error_param_too_large_u64(void *user_context, const char *param_name,
                                          uint64_t val, uint64_t max_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at most " << max_val;
    return halide_error_code_param_too_large;
}

WEAK int halide_error_param_too_large_f64(void *user_context, const char *param_name,
                                          double val, double max_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at most " << max_val;
    return halide_error_code_param_too_large;
}

WEAK int halide_error_out_of_memory(void *user_context) {
    // The error message builder uses malloc, so we can't use it here.
    halide_error(user_context, "Out of memory (halide_malloc returned NULL)");
    return halide_error_code_out_of_memory;
}

WEAK int halide_error_buffer_argument_is_null(void *user_context, const char *buffer_name) {
    error(user_context)
        << "Buffer argument " << buffer_name << " is NULL";
    return halide_error_code_buffer_argument_is_null;
}

WEAK int halide_error_debug_to_file_failed(void *user_context, const char *func,
                                           const char *filename, int error_code) {
    error(user_context)
        << "Failed to dump function " << func
        << " to file " << filename
        << " with error " << error_code;
    return halide_error_code_debug_to_file_failed;
}

}
<commit_msg>For uniformity with other runtime source files swap the ``runtime_internal.h`` and ``HalideRuntime.h`` includes in ``posix_error_handler.cpp``. This should be a non functional change because if ``HalideRuntime.h`` is included while compiling the runtime ``runtime_internal.h`` should automatically get included first.<commit_after>#include "runtime_internal.h"
#include "HalideRuntime.h"
#include "printer.h"

namespace Halide { namespace Runtime { namespace Internal {

WEAK void default_error_handler(void *user_context, const char *msg) {
    char buf[4096];
    char *dst = halide_string_to_string(buf, buf + 4095, "Error: ");
    dst = halide_string_to_string(dst, buf + 4095, msg);
    // We still have one character free. Add a newline if there
    // isn't one already.
    if (dst[-1] != '\n') {
        dst[0] = '\n';
        dst[1] = 0;
    }
    halide_print(user_context, buf);
    abort();
}

WEAK void (*halide_error_handler)(void *, const char *) = default_error_handler;

}}} // namespace Halide::Runtime::Internal

extern "C" {

WEAK void halide_error(void *user_context, const char *msg) {
    (*halide_error_handler)(user_context, msg);
}

WEAK void (*halide_set_error_handler(void (*handler)(void *, const char *)))(void *, const char *) {
    void (*result)(void *, const char *) = halide_error_handler;
    halide_error_handler = handler;
    return result;
}

WEAK int halide_error_bounds_inference_call_failed(void *user_context, const char *extern_stage_name, int result) {
    error(user_context)
        << "Bounds inference call to external stage " << extern_stage_name
        << " returned non-zero value: " << result;
    return result;
}

WEAK int halide_error_extern_stage_failed(void *user_context, const char *extern_stage_name, int result) {
    error(user_context)
        << "Call to external stage " << extern_stage_name
        << " returned non-zero value: " << result;
    return result;
}

WEAK int halide_error_explicit_bounds_too_small(void *user_context, const char *func_name, const char *var_name,
                                                int min_bound, int max_bound, int min_required, int max_required) {
    error(user_context)
        << "Bounds given for " << var_name << " in " << func_name
        << " (from " << min_bound << " to " << max_bound
        << ") do not cover required region (from " << min_required
        << " to " << max_required << ")";
    return halide_error_code_explicit_bounds_too_small;
}

WEAK int halide_error_bad_elem_size(void *user_context, const char *func_name,
                                    const char *type_name, int elem_size_given, int correct_elem_size) {
    error(user_context)
        << func_name << " has type " << type_name
        << " but elem_size of the buffer passed in is "
        << elem_size_given << " instead of " << correct_elem_size;
    return halide_error_code_bad_elem_size;
}

WEAK int halide_error_access_out_of_bounds(void *user_context, const char *func_name,
                                           int dimension, int min_touched, int max_touched,
                                           int min_valid, int max_valid) {
    if (min_touched < min_valid) {
        error(user_context)
            << func_name << " is accessed at " << min_touched
            << ", which is before the min (" << min_valid
            << ") in dimension " << dimension;
    } else if (max_touched > max_valid) {
        error(user_context)
            << func_name << " is accessed at " << max_touched
            << ", which is beyond the max (" << max_valid
            << ") in dimension " << dimension;
    }
    return halide_error_code_access_out_of_bounds;
}

WEAK int halide_error_buffer_allocation_too_large(void *user_context, const char *buffer_name, int64_t allocation_size, int64_t max_size) {
    error(user_context)
        << "Total allocation for buffer " << buffer_name
        << " is " << allocation_size
        << ", which exceeds the maximum size of " << max_size;
    return halide_error_code_buffer_allocation_too_large;
}

WEAK int halide_error_buffer_extents_too_large(void *user_context, const char *buffer_name, int64_t actual_size, int64_t max_size) {
    error(user_context)
        << "Product of extents for buffer " << buffer_name
        << " is " << actual_size
        << ", which exceeds the maximum size of " << max_size;
    return halide_error_code_buffer_extents_too_large;
}

WEAK int halide_error_constraints_make_required_region_smaller(void *user_context, const char *buffer_name,
                                                               int dimension,
                                                               int constrained_min, int constrained_extent,
                                                               int required_min, int required_extent) {
    int required_max = required_min + required_extent - 1;
    int constrained_max = constrained_min + required_extent - 1;
    error(user_context)
        << "Applying the constraints on " << buffer_name
        << " to the required region made it smaller. "
        << "Required size: " << required_min << " to " << required_max << ". "
        << "Constrained size: " << constrained_min << " to " << constrained_max << ".";
    return halide_error_code_constraints_make_required_region_smaller;
}

WEAK int halide_error_constraint_violated(void *user_context, const char *var, int val,
                                          const char *constrained_var, int constrained_val) {
    error(user_context)
        << "Constraint violated: " << var << " (" << val
        << ") == " << constrained_var << " (" << constrained_var << ")";
    return halide_error_code_constraint_violated;
}

WEAK int halide_error_param_too_small_i64(void *user_context, const char *param_name,
                                          int64_t val, int64_t min_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at least " << min_val;
    return halide_error_code_param_too_small;
}

WEAK int halide_error_param_too_small_u64(void *user_context, const char *param_name,
                                          uint64_t val, uint64_t min_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at least " << min_val;
    return halide_error_code_param_too_small;
}

WEAK int halide_error_param_too_small_f64(void *user_context, const char *param_name,
                                          double val, double min_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at least " << min_val;
    return halide_error_code_param_too_small;
}

WEAK int halide_error_param_too_large_i64(void *user_context, const char *param_name,
                                          int64_t val, int64_t max_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at most " << max_val;
    return halide_error_code_param_too_large;
}

WEAK int halide_error_param_too_large_u64(void *user_context, const char *param_name,
                                          uint64_t val, uint64_t max_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at most " << max_val;
    return halide_error_code_param_too_large;
}

WEAK int halide_error_param_too_large_f64(void *user_context, const char *param_name,
                                          double val, double max_val) {
    error(user_context)
        << "Parameter " << param_name
        << " is " << val
        << " but must be at most " << max_val;
    return halide_error_code_param_too_large;
}

WEAK int halide_error_out_of_memory(void *user_context) {
    // The error message builder uses malloc, so we can't use it here.
    halide_error(user_context, "Out of memory (halide_malloc returned NULL)");
    return halide_error_code_out_of_memory;
}

WEAK int halide_error_buffer_argument_is_null(void *user_context, const char *buffer_name) {
    error(user_context)
        << "Buffer argument " << buffer_name << " is NULL";
    return halide_error_code_buffer_argument_is_null;
}

WEAK int halide_error_debug_to_file_failed(void *user_context, const char *func,
                                           const char *filename, int error_code) {
    error(user_context)
        << "Failed to dump function " << func
        << " to file " << filename
        << " with error " << error_code;
    return halide_error_code_debug_to_file_failed;
}

}
<|endoftext|>