<commit_before>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   ScriptMetaTypeDefines.cpp
 *  @brief  Registration of Naali Core API to Javascript.
 */

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "ScriptMetaTypeDefines.h"

#include "SceneAPI.h"
#include "Entity.h"
#include "IAssetTransfer.h"
#include "IAssetUploadTransfer.h"
#include "IAssetStorage.h"
#include "AssetCache.h"
#include "KeyEvent.h"
#include "MouseEvent.h"
#include "UiProxyWidget.h"
#include "FrameAPI.h"
#include "ConsoleAPI.h"
#include "SceneManager.h"
#include "AudioAPI.h"
#include "SoundChannel.h"
#include "InputContext.h"
#include "RenderServiceInterface.h"
//#include "CommunicationsService.h"
#include "NaaliMainWindow.h"
#include "NaaliGraphicsView.h"
#include "EntityAction.h"
#include "InputFwd.h"
#include "ConfigAPI.h"
#include "LoggingFunctions.h"
#include "AssetAPI.h"

#include <QUiLoader>
#include <QFile>

/// Qt defines
Q_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*)
Q_SCRIPT_DECLARE_QMETAOBJECT(QWidget, QWidget*)
Q_SCRIPT_DECLARE_QMETAOBJECT(QTimer, QObject*);

///\todo Remove these two and move to Input API once NaaliCore is merged.
/// Naali input defines
Q_DECLARE_METATYPE(MouseEvent*)
Q_DECLARE_METATYPE(KeyEvent*)
Q_DECLARE_METATYPE(GestureEvent*)
Q_DECLARE_METATYPE(InputContext*)

/// Asset API defines
Q_DECLARE_METATYPE(AssetPtr);
Q_DECLARE_METATYPE(AssetTransferPtr);
Q_DECLARE_METATYPE(IAssetTransfer*);
Q_DECLARE_METATYPE(AssetUploadTransferPtr);
Q_DECLARE_METATYPE(IAssetUploadTransfer*);
Q_DECLARE_METATYPE(AssetStoragePtr);
Q_DECLARE_METATYPE(IAssetStorage*);
Q_DECLARE_METATYPE(AssetCache*);
Q_DECLARE_METATYPE(AssetMap);

QScriptValue qScriptValueFromAssetMap(QScriptEngine *engine, const AssetMap &assetMap)
{
    QScriptValue v = engine->newArray(assetMap.size());
    int idx = 0;
    for(AssetMap::const_iterator iter = assetMap.begin(); iter != assetMap.end(); ++iter)
    {
        QScriptValue elem = qScriptValueFromBoostSharedPtr(engine, iter->second);
        v.setProperty(idx++, elem);
    }

    return v;
}

/// Deliberately a null function. Currently we don't need setting asset maps from the script side.
void qScriptValueToAssetMap(const QScriptValue &value, AssetMap &assetMap)
{
}

/// Naali Ui defines
Q_DECLARE_METATYPE(UiProxyWidget*);
Q_DECLARE_METATYPE(NaaliMainWindow*);
Q_DECLARE_METATYPE(NaaliGraphicsView*);
Q_SCRIPT_DECLARE_QMETAOBJECT(UiProxyWidget, QWidget*)

/// Naali Scene defines.
Q_DECLARE_METATYPE(SceneAPI*);
Q_DECLARE_METATYPE(Scene::SceneManager*);
Q_DECLARE_METATYPE(Scene::Entity*);
Q_DECLARE_METATYPE(EntityAction*);
Q_DECLARE_METATYPE(EntityAction::ExecutionType);
Q_DECLARE_METATYPE(AttributeChange*);
Q_DECLARE_METATYPE(IComponent*);
Q_DECLARE_METATYPE(AttributeChange::Type);

/// Naali core API object defines.
Q_DECLARE_METATYPE(Foundation::Framework*);
Q_DECLARE_METATYPE(FrameAPI*);
Q_DECLARE_METATYPE(ConsoleAPI*);
Q_DECLARE_METATYPE(Command*);
Q_DECLARE_METATYPE(DelayedSignal*);
Q_DECLARE_METATYPE(DebugAPI*);

/// Naali Audio API object.
Q_DECLARE_METATYPE(AudioAPI*);
Q_DECLARE_METATYPE(SoundChannel*);

/// Naali Config API object.
Q_DECLARE_METATYPE(ConfigAPI*);

/// Naali renderer defines
Q_DECLARE_METATYPE(RaycastResult*);

/// Communications metatype
//Q_DECLARE_METATYPE(Communications::InWorldVoice::SessionInterface*);
//Q_DECLARE_METATYPE(Communications::InWorldVoice::ParticipantInterface*);

QScriptValue findChild(QScriptContext *ctx, QScriptEngine *eng)
{
    if(ctx->argumentCount() == 2)
    {
        QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
        QString childName = qscriptvalue_cast<QString>(ctx->argument(1));
        if(object)
        {
            QObject *obj = object->findChild<QObject*>(childName);
            if (obj)
                return eng->newQObject(obj);
        }
    }
    return QScriptValue();
}

// Helper function. Added because new'ing a QPixmap in script seems to lead into growing memory use
QScriptValue setPixmapToLabel(QScriptContext *ctx, QScriptEngine *eng)
{
    if(ctx->argumentCount() == 2)
    {
        QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
        QString filename = qscriptvalue_cast<QString>(ctx->argument(1));

        QLabel *label = dynamic_cast<QLabel *>(object);
        if (label && QFile::exists(filename))
            label->setPixmap(QPixmap(filename));
    }
    return QScriptValue();
}

void ExposeQtMetaTypes(QScriptEngine *engine)
{
    assert(engine);
    if (!engine)
        return;

    QScriptValue object = engine->scriptValueFromQMetaObject<QPushButton>();
    engine->globalObject().setProperty("QPushButton", object);
    object = engine->scriptValueFromQMetaObject<QWidget>();
    engine->globalObject().setProperty("QWidget", object);
    object = engine->scriptValueFromQMetaObject<QTimer>();
    engine->globalObject().setProperty("QTimer", object);
    engine->globalObject().setProperty("findChild", engine->newFunction(findChild));
    engine->globalObject().setProperty("setPixmapToLabel", engine->newFunction(setPixmapToLabel));
/*
    engine->importExtension("qt.core");
    engine->importExtension("qt.gui");
    engine->importExtension("qt.network");
    engine->importExtension("qt.uitools");
    engine->importExtension("qt.xml");
    engine->importExtension("qt.xmlpatterns");
*/
//  Our deps contain these plugins as well, but we don't use them (for now at least).
//    engine->importExtension("qt.opengl");
//    engine->importExtension("qt.phonon");
//    engine->importExtension("qt.webkit"); //cvetan hacked this to build with msvc, patch is somewhere

}

Q_DECLARE_METATYPE(SoundChannelPtr);
Q_DECLARE_METATYPE(InputContextPtr);

void ExposeCoreApiMetaTypes(QScriptEngine *engine)
{
    // Input metatypes.
    qScriptRegisterQObjectMetaType<MouseEvent*>(engine);
    qScriptRegisterQObjectMetaType<KeyEvent*>(engine);
    qScriptRegisterQObjectMetaType<GestureEvent*>(engine);
    qScriptRegisterQObjectMetaType<InputContext*>(engine);
    qRegisterMetaType<InputContextPtr>("InputContextPtr");
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<InputContext>,
                            qScriptValueToBoostSharedPtr<InputContext>);
    qRegisterMetaType<KeyEvent::EventType>("KeyEvent::EventType");
    qRegisterMetaType<MouseEvent::EventType>("MouseEvent::EventType");
    qRegisterMetaType<MouseEvent::MouseButton>("MouseEvent::MouseButton");
    qRegisterMetaType<GestureEvent::EventType>("GestureEvent::EventType");

    // Scene metatypes.
    qScriptRegisterQObjectMetaType<SceneAPI*>(engine);
    qScriptRegisterQObjectMetaType<Scene::SceneManager*>(engine);
    qScriptRegisterQObjectMetaType<Scene::Entity*>(engine);
    qScriptRegisterQObjectMetaType<EntityAction*>(engine);
    qScriptRegisterQObjectMetaType<AttributeChange*>(engine);
    qScriptRegisterQObjectMetaType<IComponent*>(engine);
    //qRegisterMetaType<AttributeChange::Type>("AttributeChange::Type");
    qScriptRegisterMetaType(engine, toScriptValueEnum<AttributeChange::Type>, fromScriptValueEnum<AttributeChange::Type>);
    //qRegisterMetaType<EntityAction::ExecutionType>("EntityAction::ExecutionType");
    qScriptRegisterMetaType(engine, toScriptValueEnum<EntityAction::ExecutionType>, fromScriptValueEnum<EntityAction::ExecutionType>);

    // Framework metatype
    qScriptRegisterQObjectMetaType<Foundation::Framework*>(engine);

    // Console metatypes.
    qScriptRegisterQObjectMetaType<ConsoleAPI*>(engine);
    qScriptRegisterQObjectMetaType<Command*>(engine);

    // Frame metatypes.
    qScriptRegisterQObjectMetaType<FrameAPI*>(engine);
    qScriptRegisterQObjectMetaType<DelayedSignal*>(engine);

    // Config metatypes.
    qScriptRegisterQObjectMetaType<ConfigAPI*>(engine);

    // Asset API
    qRegisterMetaType<AssetPtr>("AssetPtr");
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAsset>, qScriptValueToBoostSharedPtr<IAsset>);

    qRegisterMetaType<AssetTransferPtr>("AssetTransferPtr");
    qScriptRegisterQObjectMetaType<IAssetTransfer*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetTransfer>, qScriptValueToBoostSharedPtr<IAssetTransfer>);

    qRegisterMetaType<AssetUploadTransferPtr>("AssetUploadTransferPtr");
    qScriptRegisterQObjectMetaType<IAssetUploadTransfer*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetUploadTransfer>, qScriptValueToBoostSharedPtr<IAssetUploadTransfer>);

    qRegisterMetaType<AssetStoragePtr>("AssetStoragePtr");
    qScriptRegisterQObjectMetaType<IAssetStorage*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetStorage>, qScriptValueToBoostSharedPtr<IAssetStorage>);

    qScriptRegisterQObjectMetaType<AssetCache*>(engine);

    qRegisterMetaType<AssetMap>("AssetMap");
    qRegisterMetaType<AssetMap>("AssetMap");
    qScriptRegisterMetaType<AssetMap>(engine, qScriptValueFromAssetMap, qScriptValueToAssetMap);

    // Ui metatypes.
    qScriptRegisterQObjectMetaType<NaaliMainWindow*>(engine);
    qScriptRegisterQObjectMetaType<NaaliGraphicsView*>(engine);
    qScriptRegisterQObjectMetaType<UiProxyWidget*>(engine);
    qScriptRegisterQObjectMetaType<QGraphicsScene*>(engine);

    // Add support to create proxy widgets in javascript side.
    QScriptValue object = engine->scriptValueFromQMetaObject<UiProxyWidget>();
    engine->globalObject().setProperty("UiProxyWidget", object);

    // Sound metatypes.
    qRegisterMetaType<sound_id_t>("sound_id_t");
    qRegisterMetaType<SoundChannel::SoundState>("SoundState");
    qRegisterMetaType<SoundChannelPtr>("SoundChannelPtr");
    qScriptRegisterQObjectMetaType<SoundChannel*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<SoundChannel>, qScriptValueToBoostSharedPtr<SoundChannel>);

    qRegisterMetaType<SoundChannel::SoundState>("SoundChannel::SoundState");
    qRegisterMetaType<SoundChannel::SoundType>("SoundType");
    qRegisterMetaType<SoundChannel::SoundType>("SoundChannel::SoundType");

    // Renderer metatypes
    qScriptRegisterQObjectMetaType<RaycastResult*>(engine);

    // Communications metatypes
//    qScriptRegisterQObjectMetaType<Communications::InWorldVoice::SessionInterface*>(engine);
//    qScriptRegisterQObjectMetaType<Communications::InWorldVoice::ParticipantInterface*>(engine);
}

<commit_msg>Remove duplicate code typo in previous commit.<commit_after>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   ScriptMetaTypeDefines.cpp
 *  @brief  Registration of Naali Core API to Javascript.
 */

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "ScriptMetaTypeDefines.h"

#include "SceneAPI.h"
#include "Entity.h"
#include "IAssetTransfer.h"
#include "IAssetUploadTransfer.h"
#include "IAssetStorage.h"
#include "AssetCache.h"
#include "KeyEvent.h"
#include "MouseEvent.h"
#include "UiProxyWidget.h"
#include "FrameAPI.h"
#include "ConsoleAPI.h"
#include "SceneManager.h"
#include "AudioAPI.h"
#include "SoundChannel.h"
#include "InputContext.h"
#include "RenderServiceInterface.h"
//#include "CommunicationsService.h"
#include "NaaliMainWindow.h"
#include "NaaliGraphicsView.h"
#include "EntityAction.h"
#include "InputFwd.h"
#include "ConfigAPI.h"
#include "LoggingFunctions.h"
#include "AssetAPI.h"

#include <QUiLoader>
#include <QFile>

/// Qt defines
Q_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*)
Q_SCRIPT_DECLARE_QMETAOBJECT(QWidget, QWidget*)
Q_SCRIPT_DECLARE_QMETAOBJECT(QTimer, QObject*);

///\todo Remove these two and move to Input API once NaaliCore is merged.
/// Naali input defines
Q_DECLARE_METATYPE(MouseEvent*)
Q_DECLARE_METATYPE(KeyEvent*)
Q_DECLARE_METATYPE(GestureEvent*)
Q_DECLARE_METATYPE(InputContext*)

/// Asset API defines
Q_DECLARE_METATYPE(AssetPtr);
Q_DECLARE_METATYPE(AssetTransferPtr);
Q_DECLARE_METATYPE(IAssetTransfer*);
Q_DECLARE_METATYPE(AssetUploadTransferPtr);
Q_DECLARE_METATYPE(IAssetUploadTransfer*);
Q_DECLARE_METATYPE(AssetStoragePtr);
Q_DECLARE_METATYPE(IAssetStorage*);
Q_DECLARE_METATYPE(AssetCache*);
Q_DECLARE_METATYPE(AssetMap);

QScriptValue qScriptValueFromAssetMap(QScriptEngine *engine, const AssetMap &assetMap)
{
    QScriptValue v = engine->newArray(assetMap.size());
    int idx = 0;
    for(AssetMap::const_iterator iter = assetMap.begin(); iter != assetMap.end(); ++iter)
    {
        QScriptValue elem = qScriptValueFromBoostSharedPtr(engine, iter->second);
        v.setProperty(idx++, elem);
    }

    return v;
}

/// Deliberately a null function. Currently we don't need setting asset maps from the script side.
void qScriptValueToAssetMap(const QScriptValue &value, AssetMap &assetMap)
{
}

/// Naali Ui defines
Q_DECLARE_METATYPE(UiProxyWidget*);
Q_DECLARE_METATYPE(NaaliMainWindow*);
Q_DECLARE_METATYPE(NaaliGraphicsView*);
Q_SCRIPT_DECLARE_QMETAOBJECT(UiProxyWidget, QWidget*)

/// Naali Scene defines.
Q_DECLARE_METATYPE(SceneAPI*);
Q_DECLARE_METATYPE(Scene::SceneManager*);
Q_DECLARE_METATYPE(Scene::Entity*);
Q_DECLARE_METATYPE(EntityAction*);
Q_DECLARE_METATYPE(EntityAction::ExecutionType);
Q_DECLARE_METATYPE(AttributeChange*);
Q_DECLARE_METATYPE(IComponent*);
Q_DECLARE_METATYPE(AttributeChange::Type);

/// Naali core API object defines.
Q_DECLARE_METATYPE(Foundation::Framework*);
Q_DECLARE_METATYPE(FrameAPI*);
Q_DECLARE_METATYPE(ConsoleAPI*);
Q_DECLARE_METATYPE(Command*);
Q_DECLARE_METATYPE(DelayedSignal*);
Q_DECLARE_METATYPE(DebugAPI*);

/// Naali Audio API object.
Q_DECLARE_METATYPE(AudioAPI*);
Q_DECLARE_METATYPE(SoundChannel*);

/// Naali Config API object.
Q_DECLARE_METATYPE(ConfigAPI*);

/// Naali renderer defines
Q_DECLARE_METATYPE(RaycastResult*);

/// Communications metatype
//Q_DECLARE_METATYPE(Communications::InWorldVoice::SessionInterface*);
//Q_DECLARE_METATYPE(Communications::InWorldVoice::ParticipantInterface*);

QScriptValue findChild(QScriptContext *ctx, QScriptEngine *eng)
{
    if(ctx->argumentCount() == 2)
    {
        QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
        QString childName = qscriptvalue_cast<QString>(ctx->argument(1));
        if(object)
        {
            QObject *obj = object->findChild<QObject*>(childName);
            if (obj)
                return eng->newQObject(obj);
        }
    }
    return QScriptValue();
}

// Helper function. Added because new'ing a QPixmap in script seems to lead into growing memory use
QScriptValue setPixmapToLabel(QScriptContext *ctx, QScriptEngine *eng)
{
    if(ctx->argumentCount() == 2)
    {
        QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
        QString filename = qscriptvalue_cast<QString>(ctx->argument(1));

        QLabel *label = dynamic_cast<QLabel *>(object);
        if (label && QFile::exists(filename))
            label->setPixmap(QPixmap(filename));
    }
    return QScriptValue();
}

void ExposeQtMetaTypes(QScriptEngine *engine)
{
    assert(engine);
    if (!engine)
        return;

    QScriptValue object = engine->scriptValueFromQMetaObject<QPushButton>();
    engine->globalObject().setProperty("QPushButton", object);
    object = engine->scriptValueFromQMetaObject<QWidget>();
    engine->globalObject().setProperty("QWidget", object);
    object = engine->scriptValueFromQMetaObject<QTimer>();
    engine->globalObject().setProperty("QTimer", object);
    engine->globalObject().setProperty("findChild", engine->newFunction(findChild));
    engine->globalObject().setProperty("setPixmapToLabel", engine->newFunction(setPixmapToLabel));
/*
    engine->importExtension("qt.core");
    engine->importExtension("qt.gui");
    engine->importExtension("qt.network");
    engine->importExtension("qt.uitools");
    engine->importExtension("qt.xml");
    engine->importExtension("qt.xmlpatterns");
*/
//  Our deps contain these plugins as well, but we don't use them (for now at least).
//    engine->importExtension("qt.opengl");
//    engine->importExtension("qt.phonon");
//    engine->importExtension("qt.webkit"); //cvetan hacked this to build with msvc, patch is somewhere

}

Q_DECLARE_METATYPE(SoundChannelPtr);
Q_DECLARE_METATYPE(InputContextPtr);

void ExposeCoreApiMetaTypes(QScriptEngine *engine)
{
    // Input metatypes.
    qScriptRegisterQObjectMetaType<MouseEvent*>(engine);
    qScriptRegisterQObjectMetaType<KeyEvent*>(engine);
    qScriptRegisterQObjectMetaType<GestureEvent*>(engine);
    qScriptRegisterQObjectMetaType<InputContext*>(engine);
    qRegisterMetaType<InputContextPtr>("InputContextPtr");
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<InputContext>,
                            qScriptValueToBoostSharedPtr<InputContext>);
    qRegisterMetaType<KeyEvent::EventType>("KeyEvent::EventType");
    qRegisterMetaType<MouseEvent::EventType>("MouseEvent::EventType");
    qRegisterMetaType<MouseEvent::MouseButton>("MouseEvent::MouseButton");
    qRegisterMetaType<GestureEvent::EventType>("GestureEvent::EventType");

    // Scene metatypes.
    qScriptRegisterQObjectMetaType<SceneAPI*>(engine);
    qScriptRegisterQObjectMetaType<Scene::SceneManager*>(engine);
    qScriptRegisterQObjectMetaType<Scene::Entity*>(engine);
    qScriptRegisterQObjectMetaType<EntityAction*>(engine);
    qScriptRegisterQObjectMetaType<AttributeChange*>(engine);
    qScriptRegisterQObjectMetaType<IComponent*>(engine);
    //qRegisterMetaType<AttributeChange::Type>("AttributeChange::Type");
    qScriptRegisterMetaType(engine, toScriptValueEnum<AttributeChange::Type>, fromScriptValueEnum<AttributeChange::Type>);
    //qRegisterMetaType<EntityAction::ExecutionType>("EntityAction::ExecutionType");
    qScriptRegisterMetaType(engine, toScriptValueEnum<EntityAction::ExecutionType>, fromScriptValueEnum<EntityAction::ExecutionType>);

    // Framework metatype
    qScriptRegisterQObjectMetaType<Foundation::Framework*>(engine);

    // Console metatypes.
    qScriptRegisterQObjectMetaType<ConsoleAPI*>(engine);
    qScriptRegisterQObjectMetaType<Command*>(engine);

    // Frame metatypes.
    qScriptRegisterQObjectMetaType<FrameAPI*>(engine);
    qScriptRegisterQObjectMetaType<DelayedSignal*>(engine);

    // Config metatypes.
    qScriptRegisterQObjectMetaType<ConfigAPI*>(engine);

    // Asset API
    qRegisterMetaType<AssetPtr>("AssetPtr");
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAsset>, qScriptValueToBoostSharedPtr<IAsset>);

    qRegisterMetaType<AssetTransferPtr>("AssetTransferPtr");
    qScriptRegisterQObjectMetaType<IAssetTransfer*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetTransfer>, qScriptValueToBoostSharedPtr<IAssetTransfer>);

    qRegisterMetaType<AssetUploadTransferPtr>("AssetUploadTransferPtr");
    qScriptRegisterQObjectMetaType<IAssetUploadTransfer*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetUploadTransfer>, qScriptValueToBoostSharedPtr<IAssetUploadTransfer>);

    qRegisterMetaType<AssetStoragePtr>("AssetStoragePtr");
    qScriptRegisterQObjectMetaType<IAssetStorage*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetStorage>, qScriptValueToBoostSharedPtr<IAssetStorage>);

    qScriptRegisterQObjectMetaType<AssetCache*>(engine);

    qRegisterMetaType<AssetMap>("AssetMap");
    qScriptRegisterMetaType<AssetMap>(engine, qScriptValueFromAssetMap, qScriptValueToAssetMap);

    // Ui metatypes.
    qScriptRegisterQObjectMetaType<NaaliMainWindow*>(engine);
    qScriptRegisterQObjectMetaType<NaaliGraphicsView*>(engine);
    qScriptRegisterQObjectMetaType<UiProxyWidget*>(engine);
    qScriptRegisterQObjectMetaType<QGraphicsScene*>(engine);

    // Add support to create proxy widgets in javascript side.
    QScriptValue object = engine->scriptValueFromQMetaObject<UiProxyWidget>();
    engine->globalObject().setProperty("UiProxyWidget", object);

    // Sound metatypes.
    qRegisterMetaType<sound_id_t>("sound_id_t");
    qRegisterMetaType<SoundChannel::SoundState>("SoundState");
    qRegisterMetaType<SoundChannelPtr>("SoundChannelPtr");
    qScriptRegisterQObjectMetaType<SoundChannel*>(engine);
    qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<SoundChannel>, qScriptValueToBoostSharedPtr<SoundChannel>);

    qRegisterMetaType<SoundChannel::SoundState>("SoundChannel::SoundState");
    qRegisterMetaType<SoundChannel::SoundType>("SoundType");
    qRegisterMetaType<SoundChannel::SoundType>("SoundChannel::SoundType");

    // Renderer metatypes
    qScriptRegisterQObjectMetaType<RaycastResult*>(engine);

    // Communications metatypes
//    qScriptRegisterQObjectMetaType<Communications::InWorldVoice::SessionInterface*>(engine);
//    qScriptRegisterQObjectMetaType<Communications::InWorldVoice::ParticipantInterface*>(engine);
}

<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "stan/prob/distributions_uniform.hpp"

TEST(ProbDistributions,Uniform) {
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log(0.2,0.0,1.0)));
  EXPECT_FLOAT_EQ(2.0, exp(stan::prob::uniform_log(0.2,-0.25,0.25)));
  EXPECT_FLOAT_EQ(0.1, exp(stan::prob::uniform_log(101.0,100.0,110.0)));
  // lower boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log(0.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log(-1.0,0.0,1.0)));
  // upper boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log(1.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log(2.0,0.0,1.0)));
}
TEST(ProbDistributions,UniformPropto) {
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(0.2,0.0,1.0)));
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(0.2,-0.25,0.25)));
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(101.0,100.0,110.0)));
  // lower boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(0.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log<true>(-1.0,0.0,1.0)));
  // upper boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(1.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log<true>(2.0,0.0,1.0)));
}
TEST(ProbDistributions,UniformDefaultPolicy) {
  // lower bound higher than the upper bound
  EXPECT_THROW (stan::prob::uniform_log(0.0,1.0,0.0), std::domain_error);
  // lower and upper boundary the same
  EXPECT_THROW (stan::prob::uniform_log(0.0, 0.0, 0.0), std::domain_error);
  EXPECT_THROW (stan::prob::uniform_log(1.0, 0.0, 0.0), std::domain_error);
  EXPECT_THROW (stan::prob::uniform_log(-1.0, 0.0, 0.0), std::domain_error);
}
TEST(ProbDistributions,UniformErrorNoPolicy) {
  using boost::math::policies::policy;
  using boost::math::policies::evaluation_error;
  using boost::math::policies::domain_error;
  using boost::math::policies::overflow_error;
  using boost::math::policies::domain_error;
  using boost::math::policies::pole_error;
  using boost::math::policies::errno_on_error;

  typedef policy<
    domain_error<errno_on_error>,
    pole_error<errno_on_error>,
    overflow_error<errno_on_error>,
    evaluation_error<errno_on_error>
    > pol;

  double y = 0;
  double result;
  // lower and uppper bounds same
  EXPECT_NO_THROW (result = stan::prob::uniform_log (y, 0.0, 0.0, pol()));
  EXPECT_EQ (33, errno);
}
<commit_msg>uniform: adding domain tests<commit_after>#include <gtest/gtest.h>
#include "stan/prob/distributions_uniform.hpp"

using boost::math::policies::policy;
using boost::math::policies::evaluation_error;
using boost::math::policies::domain_error;
using boost::math::policies::overflow_error;
using boost::math::policies::domain_error;
using boost::math::policies::pole_error;
using boost::math::policies::errno_on_error;

typedef policy<
  domain_error<errno_on_error>,
  pole_error<errno_on_error>,
  overflow_error<errno_on_error>,
  evaluation_error<errno_on_error>
  > errno_policy;

TEST(ProbDistributions,Uniform) {
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log(0.2,0.0,1.0)));
  EXPECT_FLOAT_EQ(2.0, exp(stan::prob::uniform_log(0.2,-0.25,0.25)));
  EXPECT_FLOAT_EQ(0.1, exp(stan::prob::uniform_log(101.0,100.0,110.0)));
  // lower boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log(0.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log(-1.0,0.0,1.0)));
  // upper boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log(1.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log(2.0,0.0,1.0)));
}
TEST(ProbDistributionsPropto,Uniform) {
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(0.2,0.0,1.0)));
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(0.2,-0.25,0.25)));
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(101.0,100.0,110.0)));
  // lower boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(0.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log<true>(-1.0,0.0,1.0)));
  // upper boundary
  EXPECT_FLOAT_EQ(1.0, exp(stan::prob::uniform_log<true>(1.0,0.0,1.0)));
  EXPECT_FLOAT_EQ(0.0, exp(stan::prob::uniform_log<true>(2.0,0.0,1.0)));
}
TEST(ProbDistributionsDefaultPolicy,UniformY) {
  double y = 0.0;
  EXPECT_NO_THROW(stan::prob::uniform_log(y,0.0,1.0));

  y = std::numeric_limits<double>::quiet_NaN();
  EXPECT_THROW(stan::prob::uniform_log(y,0.0,0.0), std::domain_error);
  y = std::numeric_limits<double>::infinity();
  EXPECT_THROW(stan::prob::uniform_log(y,0.0,0.0), std::domain_error);
  y = -std::numeric_limits<double>::infinity();
  EXPECT_THROW(stan::prob::uniform_log(y,0.0,0.0), std::domain_error);
}
TEST(ProbDistributionsDefaultPolicy,UniformLower) {
  double lb = 0.0;
  EXPECT_NO_THROW(stan::prob::uniform_log(0.0,lb,1.0));

  lb = std::numeric_limits<double>::quiet_NaN();
  EXPECT_THROW(stan::prob::uniform_log(0.0,lb,0.0), std::domain_error);
  lb = std::numeric_limits<double>::infinity();
  EXPECT_THROW(stan::prob::uniform_log(0.0,lb,0.0), std::domain_error);
  lb = -std::numeric_limits<double>::infinity();
  EXPECT_THROW(stan::prob::uniform_log(0.0,lb,0.0), std::domain_error);
}
TEST(ProbDistributionsDefaultPolicy,UniformUpper) {
  double ub = 10.0;
  EXPECT_NO_THROW(stan::prob::uniform_log(0.0,0.0,ub));

  ub = std::numeric_limits<double>::quiet_NaN();
  EXPECT_THROW(stan::prob::uniform_log(0.0,0.0,ub), std::domain_error);
  ub = std::numeric_limits<double>::infinity();
  EXPECT_THROW(stan::prob::uniform_log(0.0,0.0,ub), std::domain_error);
  ub = -std::numeric_limits<double>::infinity();
  EXPECT_THROW(stan::prob::uniform_log(0.0,0.0,ub), std::domain_error);
}
TEST(ProbDistributionsDefaultPolicy,UniformBounds) {
  // lower bound higher than the upper bound
  EXPECT_THROW(stan::prob::uniform_log(0.0,1.0,0.0), std::domain_error);
  // lower and upper boundary the same
  EXPECT_THROW(stan::prob::uniform_log(0.0, 0.0, 0.0), std::domain_error);
}
TEST(ProbDistributionsErrnoPolicy,UniformBounds) {
  double y = 0;
  double result;
  // lower and uppper bounds same
  EXPECT_NO_THROW(result = stan::prob::uniform_log(y, 0.0, 0.0, errno_policy()));
  EXPECT_EQ(33, errno);
}
TEST(ProbDistributionsErrnoPolicy,UniformY) {
  double y = 0.0;
  double result;
  result = stan::prob::uniform_log(y,0.0,1.0,errno_policy());
  EXPECT_FALSE(std::isnan(result));

  y = std::numeric_limits<double>::quiet_NaN();
  result = stan::prob::uniform_log(y,0.0,1.0,errno_policy());
  EXPECT_TRUE(std::isnan(result));

  y = std::numeric_limits<double>::infinity();
  result = stan::prob::uniform_log(y,0.0,1.0,errno_policy());
  EXPECT_TRUE(std::isnan(result));

  y = -std::numeric_limits<double>::infinity();
  result = stan::prob::uniform_log(y,0.0,1.0,errno_policy());
  EXPECT_TRUE(std::isnan(result));
}
TEST(ProbDistributionsErrnoPolicy,UniformLower) {
  double lb = 0.0;
  double result;
  result = stan::prob::uniform_log(0.0,lb,1.0,errno_policy());
  EXPECT_FALSE(std::isnan(result));

  lb = std::numeric_limits<double>::quiet_NaN();
  result = stan::prob::uniform_log(0.0,lb,0.0,errno_policy());
  EXPECT_TRUE(std::isnan(result));
  lb = std::numeric_limits<double>::infinity();
  result = stan::prob::uniform_log(0.0,lb,0.0,errno_policy());
  EXPECT_TRUE(std::isnan(result));
  lb = -std::numeric_limits<double>::infinity();
  result = stan::prob::uniform_log(0.0,lb,0.0,errno_policy());
  EXPECT_TRUE(std::isnan(result));
}
TEST(ProbDistributionsErrnoPolicy,UniformUpper) {
  double ub = 10.0;
  double result;
  result = stan::prob::uniform_log(0.0,0.0,ub,errno_policy());
  EXPECT_FALSE(std::isnan(result));

  ub = std::numeric_limits<double>::quiet_NaN();
  result = stan::prob::uniform_log(0.0,0.0,ub,errno_policy());
  EXPECT_TRUE(std::isnan(result));
  ub = std::numeric_limits<double>::infinity();
  result = stan::prob::uniform_log(0.0,0.0,ub,errno_policy());
  EXPECT_TRUE(std::isnan(result));
  ub = -std::numeric_limits<double>::infinity();
  result = stan::prob::uniform_log(0.0,0.0,ub,errno_policy());
  EXPECT_TRUE(std::isnan(result));
}
<|endoftext|>


<commit_before>#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <vconf.h>

#include "common.h"
#include <dlog.h>
#include <Ecore.h>
#include <Ecore_X.h>
#include <Ecore_Evas.h>

#include <wifi.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <tizen_error.h>

#include "udp_test.h"

#include <pthread.h>
#include <FBase.h>
#include <FApp.h>

#undef LOG_TAG
#define LOG_TAG "APP_RELAY_FW"

#define VCONF_PLAYER_SHUFFLE	"db/private/org.tizen.music-player/shuffle"
#define VCONF_PLAYER_PROGRESS	"memory/private/org.tizen.music-player/progress_pos"

#define VCONFKEY_APP_RELAY	"db/private/org.tizen.menu-screen/app_relay"

static GMainLoop* gMainLoop = NULL;
static int gSocketFd = -1;
static const char uuid[] = "00001101-0000-1000-8000-00805F9B34FB";

void _vconf_noti_callback(keynode_t *node, void* data)
{
	printf("%s:+++\n", __func__);

		struct appdata *ad = (struct appdata *)data;
		char *keyname = vconf_keynode_get_name(node);

		printf("key changed: %s\n", keyname);
#if 1
		if (strcmp(keyname, VCONFKEY_APP_RELAY) == 0)
		{
			Tizen::Base::String appId;
			//appId.Insert(L"tizen.musicplayer", 0);
			//Tizen::Base::String operationId;// = Tizen::Base::String(L"http://tizen.org/appcontrol/operation/view");
			//Tizen::App::AppControl *pAc = Tizen::App::AppManager::FindAppControlN(appId, operationId);

			//if (pAc) {
			//	printf("OK\n");
			//	delete pAc;
			//} else {
			//	printf("Fail\n");
			//}

			printf("Pause MP3 player\n");
		}
		/*
	  else if (strcmp(keyname, VCONF_PLAYER_SHUFFLE) == 0)
		{
			bool shuffle = vconf_keynode_get_bool(node);
			printf("shuffle=%d\n", shuffle);
		}
		else if (strcmp(keyname, VCONF_PLAYER_PROGRESS) == 0)
		{
			double progress = vconf_get_dbl(node);
			printf("prgress changed: %ld", progress);
		}
		else if (strcmp(keyname, MP_VCONFKEY_PLAYING_PID) == 0)
		{
			int playing_pid = vconf_keynode_get_int(node);
			if (playing_pid != getpid())
			{
				DEBUG_TRACE("other player activated : [pid:%d]", playing_pid);
				if (ad->player_state == PLAY_STATE_PLAYING) {
					ad->paused_by_other_player = TRUE;
					mp_play_control_play_pause(ad, false);
				}

				//mp_minicontroller_destroy(ad);
			}
		}
		*/
#else
	switch(vconf_keynode_get_type(node))
   {
	  case VCONF_TYPE_INT:
   printf("key = %s, value = %d(int)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_int(key));
   break;
	  case VCONF_TYPE_BOOL:
   printf("key = %s, value = %d(bool)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_bool(key));
   break;
	  case VCONF_TYPE_DOUBLE:
   printf("key = %s, value = %f(double)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_dbl(key));
   break;
	  case VCONF_TYPE_STRING:
   printf("key = %s, value = %s(string)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_str(key));
   break;
	  default:
   fprintf(stderr, "Unknown Type(%d)\n", vconf_keynode_get_type(key));
   break;
   }
   return;

#endif

}

Eina_Bool mp_app_mouse_event_cb(void *data, int type, void *event)
{
	printf("TEST\n");
	if (type == ECORE_EVENT_MOUSE_BUTTON_DOWN) {
		printf("ECORE_EVENT_MOUSE_BUTTON_DOWN\n");
	}
	else if (type == ECORE_EVENT_MOUSE_BUTTON_UP) {
		printf("ECORE_EVENT_MOUSE_BUTTON_UP\n");
	}

	return 0;
}

bool initEcore()
{
	printf("initEcore()\n");

	int ret, type;
	Eina_Bool did = EINA_FALSE;
	Ecore_Event_Handler *mouse_down = NULL;
	Ecore_Event_Handler *handler = NULL;
	Ecore_Event *event;

	ret = ecore_init();
	if (ret != 1)
		printf("ecore_init fail\n");

	ecore_event_init();
	type = ecore_event_type_new();
	if (type < 1)
		printf("type fail\n");

	handler = ecore_event_handler_add(type, mp_app_mouse_event_cb, &did);
	if (!handler)
		printf("Regi fail 1\n");

	event = ecore_event_add(type, NULL, NULL, NULL);
	if (!event)
		printf("add fail\n");

	mouse_down = ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, mp_app_mouse_event_cb, NULL);
	if (!mouse_down)
		printf("Regi fail 2\n");

	printf("%d %d\n", type, ECORE_EVENT_MOUSE_BUTTON_DOWN);

	printf("main_loop_bengin()\n");
	ecore_main_loop_begin();

	ret = ecore_shutdown();
	printf("unreached main_loop_bengin()\n");
}

bool initVconf()
{
	bool res = TRUE;

	printf("%s:+++\n", __func__);
#if 1
	//TODO: vconf function test
	int b_val = 0;
	vconf_get_bool("db/private/org.tizen.music-player/shuffle", &b_val);

	if(b_val)
		vconf_set_bool("db/private/org.tizen.music-player/shuffle", FALSE);
	else
		vconf_set_bool("db/private/org.tizen.music-player/shuffle", TRUE);

	printf("b_val=%d\n", !b_val);
#endif

	if (vconf_notify_key_changed(VCONF_PLAYER_SHUFFLE, _vconf_noti_callback, NULL) < 0)
	{
		printf("Error when register callback\n");
		res = FALSE;
	}

	if (vconf_notify_key_changed(VCONFKEY_APP_RELAY, _vconf_noti_callback, NULL) < 0)
	{
		printf("Error when register callback\n");
		res = FALSE;
	}

	printf("%s:---:res=%d\n", __func__, res);
	return res;
}

bool deinitVconf()
{
	bool res = TRUE;

	printf("%s:+++\n", __func__);

    vconf_ignore_key_changed(VCONF_PLAYER_SHUFFLE, _vconf_noti_callback);

	printf("%s:---:res=%d\n", __func__, res);

	return res;
}

int gReceiveCount = 0;

static const char *__test_convert_error_to_string(wifi_error_e err_type)
{
	switch (err_type) {
	case WIFI_ERROR_NONE:
		return "NONE";
	case WIFI_ERROR_INVALID_PARAMETER:
		return "INVALID_PARAMETER";
	case WIFI_ERROR_OUT_OF_MEMORY:
		return "OUT_OF_MEMORY";
	case WIFI_ERROR_INVALID_OPERATION:
		return "INVALID_OPERATION";
	case WIFI_ERROR_ADDRESS_FAMILY_NOT_SUPPORTED:
		return "ADDRESS_FAMILY_NOT_SUPPORTED";
	case WIFI_ERROR_OPERATION_FAILED:
		return "OPERATION_FAILED";
	case WIFI_ERROR_NO_CONNECTION:
		return "NO_CONNECTION";
	case WIFI_ERROR_NOW_IN_PROGRESS:
		return "NOW_IN_PROGRESS";
	case WIFI_ERROR_ALREADY_EXISTS:
		return "ALREADY_EXISTS";
	case WIFI_ERROR_OPERATION_ABORTED:
		return "OPERATION_ABORTED";
	case WIFI_ERROR_DHCP_FAILED:
		return "DHCP_FAILED";
	case WIFI_ERROR_INVALID_KEY:
		return "INVALID_KEY";
	case WIFI_ERROR_NO_REPLY:
		return "NO_REPLY";
	case WIFI_ERROR_SECURITY_RESTRICTED:
		return "SECURITY_RESTRICTED";
	}

	return "UNKNOWN";
}

int test_is_activated(void)
{
	int rv = 0;
	bool state = false;

	rv = wifi_is_activated(&state);

	if (rv != WIFI_ERROR_NONE) {
		printf("Fail to get Wi-Fi device state [%s]\n", __test_convert_error_to_string((wifi_error_e)rv));
		return -1;
	}

	printf("Success to get Wi-Fi device state : %s\n", (state) ? "TRUE" : "FALSE");

	return 1;
}

int main(int argc, char *argv[])
{
	int error, ret = 0;
//	const char default_device_name[] = "Tizen-RK";
//	const char *device_name = NULL;
	int rv;
	pthread_attr_t attr;
    pthread_t thread_t;

	gMainLoop = g_main_loop_new(NULL, FALSE);
	printf("App Relay Sever started\n");

#if 0
	if(argc < 2) {
		char errMsg[] = "No bluetooth device name, so its name is set as default.";
		printf("%s\n", errMsg);
		ALOGW("%s\n", errMsg);
		device_name = default_device_name;
	} else {
		device_name = argv[1];
	}
#endif

//	rv = test_is_activated();		// need review after

	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&thread_t, &attr, &udp_thread_start, NULL);

#if 1
	GIOChannel *channel = g_io_channel_unix_new(0);
	g_io_add_watch(channel, (GIOCondition)(G_IO_IN|G_IO_ERR|G_IO_HUP|G_IO_NVAL), udp_test_thread, NULL);
#endif

	// Initialize vconf environments
	initVconf();

	// Init ecore
	initEcore();

	// If succeed to accept a connection, start a main loop.
	g_main_loop_run(gMainLoop);

	// Deinitializing vconf
	deinitVconf();

	ALOGI("Server is terminated successfully\n");

	return ret;
}

//! End of a file
<commit_msg>Remove RKF<commit_after>#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <vconf.h>

#include "common.h"
#include <dlog.h>
#include <Ecore.h>
#include <Ecore_X.h>
#include <Ecore_Evas.h>

#include <wifi.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <tizen_error.h>

#include "udp_test.h"

#include <pthread.h>
#include <FBase.h>
#include <FApp.h>

#undef LOG_TAG
#define LOG_TAG "APP_RELAY_FW"

#define VCONF_PLAYER_SHUFFLE	"db/private/org.tizen.music-player/shuffle"
#define VCONF_PLAYER_PROGRESS	"memory/private/org.tizen.music-player/progress_pos"

#define VCONFKEY_APP_RELAY	"db/private/org.tizen.menu-screen/app_relay"

static GMainLoop* gMainLoop = NULL;
static int gSocketFd = -1;
static const char uuid[] = "00001101-0000-1000-8000-00805F9B34FB";

void _vconf_noti_callback(keynode_t *node, void* data)
{
	printf("%s:+++\n", __func__);

		struct appdata *ad = (struct appdata *)data;
		char *keyname = vconf_keynode_get_name(node);

		printf("key changed: %s\n", keyname);
#if 1
		if (strcmp(keyname, VCONFKEY_APP_RELAY) == 0)
		{
			Tizen::Base::String appId;
			//appId.Insert(L"tizen.musicplayer", 0);
			//Tizen::Base::String operationId;// = Tizen::Base::String(L"http://tizen.org/appcontrol/operation/view");
			//Tizen::App::AppControl *pAc = Tizen::App::AppManager::FindAppControlN(appId, operationId);

			//if (pAc) {
			//	printf("OK\n");
			//	delete pAc;
			//} else {
			//	printf("Fail\n");
			//}

			printf("Pause MP3 player\n");
		}
		/*
	  else if (strcmp(keyname, VCONF_PLAYER_SHUFFLE) == 0)
		{
			bool shuffle = vconf_keynode_get_bool(node);
			printf("shuffle=%d\n", shuffle);
		}
		else if (strcmp(keyname, VCONF_PLAYER_PROGRESS) == 0)
		{
			double progress = vconf_get_dbl(node);
			printf("prgress changed: %ld", progress);
		}
		else if (strcmp(keyname, MP_VCONFKEY_PLAYING_PID) == 0)
		{
			int playing_pid = vconf_keynode_get_int(node);
			if (playing_pid != getpid())
			{
				DEBUG_TRACE("other player activated : [pid:%d]", playing_pid);
				if (ad->player_state == PLAY_STATE_PLAYING) {
					ad->paused_by_other_player = TRUE;
					mp_play_control_play_pause(ad, false);
				}

				//mp_minicontroller_destroy(ad);
			}
		}
		*/
#else
	switch(vconf_keynode_get_type(node))
   {
	  case VCONF_TYPE_INT:
   printf("key = %s, value = %d(int)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_int(key));
   break;
	  case VCONF_TYPE_BOOL:
   printf("key = %s, value = %d(bool)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_bool(key));
   break;
	  case VCONF_TYPE_DOUBLE:
   printf("key = %s, value = %f(double)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_dbl(key));
   break;
	  case VCONF_TYPE_STRING:
   printf("key = %s, value = %s(string)\n",
	   vconf_keynode_get_name(key), vconf_keynode_get_str(key));
   break;
	  default:
   fprintf(stderr, "Unknown Type(%d)\n", vconf_keynode_get_type(key));
   break;
   }
   return;

#endif

}

Eina_Bool mp_app_mouse_event_cb(void *data, int type, void *event)
{
	printf("TEST\n");
	if (type == ECORE_EVENT_MOUSE_BUTTON_DOWN) {
		printf("ECORE_EVENT_MOUSE_BUTTON_DOWN\n");
	}
	else if (type == ECORE_EVENT_MOUSE_BUTTON_UP) {
		printf("ECORE_EVENT_MOUSE_BUTTON_UP\n");
	}

	return 0;
}

bool initEcore()
{
	printf("initEcore()\n");

	int ret, type;
	Eina_Bool did = EINA_FALSE;
	Ecore_Event_Handler *mouse_down = NULL;
	Ecore_Event_Handler *handler = NULL;
	Ecore_Event *event;

	ret = ecore_init();
	if (ret != 1)
		printf("ecore_init fail\n");

	ecore_event_init();
	type = ecore_event_type_new();
	if (type < 1)
		printf("type fail\n");

	handler = ecore_event_handler_add(type, mp_app_mouse_event_cb, &did);
	if (!handler)
		printf("Regi fail 1\n");

	event = ecore_event_add(type, NULL, NULL, NULL);
	if (!event)
		printf("add fail\n");

	mouse_down = ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, mp_app_mouse_event_cb, NULL);
	if (!mouse_down)
		printf("Regi fail 2\n");

	printf("%d %d\n", type, ECORE_EVENT_MOUSE_BUTTON_DOWN);

	printf("main_loop_bengin()\n");
	ecore_main_loop_begin();

	ret = ecore_shutdown();
	printf("unreached main_loop_bengin()\n");
}

bool initVconf()
{
	bool res = TRUE;

	printf("%s:+++\n", __func__);
#if 1
	//TODO: vconf function test
	int b_val = 0;
	vconf_get_bool("db/private/org.tizen.music-player/shuffle", &b_val);

	if(b_val)
		vconf_set_bool("db/private/org.tizen.music-player/shuffle", FALSE);
	else
		vconf_set_bool("db/private/org.tizen.music-player/shuffle", TRUE);

	printf("b_val=%d\n", !b_val);
#endif

	if (vconf_notify_key_changed(VCONF_PLAYER_SHUFFLE, _vconf_noti_callback, NULL) < 0)
	{
		printf("Error when register callback\n");
		res = FALSE;
	}

	if (vconf_notify_key_changed(VCONFKEY_APP_RELAY, _vconf_noti_callback, NULL) < 0)
	{
		printf("Error when register callback\n");
		res = FALSE;
	}

	printf("%s:---:res=%d\n", __func__, res);
	return res;
}

bool deinitVconf()
{
	bool res = TRUE;

	printf("%s:+++\n", __func__);

    vconf_ignore_key_changed(VCONF_PLAYER_SHUFFLE, _vconf_noti_callback);

	printf("%s:---:res=%d\n", __func__, res);

	return res;
}

int gReceiveCount = 0;

static const char *__test_convert_error_to_string(wifi_error_e err_type)
{
	switch (err_type) {
	case WIFI_ERROR_NONE:
		return "NONE";
	case WIFI_ERROR_INVALID_PARAMETER:
		return "INVALID_PARAMETER";
	case WIFI_ERROR_OUT_OF_MEMORY:
		return "OUT_OF_MEMORY";
	case WIFI_ERROR_INVALID_OPERATION:
		return "INVALID_OPERATION";
	case WIFI_ERROR_ADDRESS_FAMILY_NOT_SUPPORTED:
		return "ADDRESS_FAMILY_NOT_SUPPORTED";
	case WIFI_ERROR_OPERATION_FAILED:
		return "OPERATION_FAILED";
	case WIFI_ERROR_NO_CONNECTION:
		return "NO_CONNECTION";
	case WIFI_ERROR_NOW_IN_PROGRESS:
		return "NOW_IN_PROGRESS";
	case WIFI_ERROR_ALREADY_EXISTS:
		return "ALREADY_EXISTS";
	case WIFI_ERROR_OPERATION_ABORTED:
		return "OPERATION_ABORTED";
	case WIFI_ERROR_DHCP_FAILED:
		return "DHCP_FAILED";
	case WIFI_ERROR_INVALID_KEY:
		return "INVALID_KEY";
	case WIFI_ERROR_NO_REPLY:
		return "NO_REPLY";
	case WIFI_ERROR_SECURITY_RESTRICTED:
		return "SECURITY_RESTRICTED";
	}

	return "UNKNOWN";
}

int test_is_activated(void)
{
	int rv = 0;
	bool state = false;

	rv = wifi_is_activated(&state);

	if (rv != WIFI_ERROR_NONE) {
		printf("Fail to get Wi-Fi device state [%s]\n", __test_convert_error_to_string((wifi_error_e)rv));
		return -1;
	}

	printf("Success to get Wi-Fi device state : %s\n", (state) ? "TRUE" : "FALSE");

	return 1;
}

int main(int argc, char *argv[])
{
	int error, ret = 0;
//	const char default_device_name[] = "Tizen-RK";
//	const char *device_name = NULL;
	int rv;
	pthread_attr_t attr;
    pthread_t thread_t;

	gMainLoop = g_main_loop_new(NULL, FALSE);
	printf("App Relay Sever started\n");

//	rv = test_is_activated();		// need review after

	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	pthread_create(&thread_t, &attr, &udp_thread_start, NULL);

#if 1
	GIOChannel *channel = g_io_channel_unix_new(0);
	g_io_add_watch(channel, (GIOCondition)(G_IO_IN|G_IO_ERR|G_IO_HUP|G_IO_NVAL), udp_test_thread, NULL);
#endif

	// Initialize vconf environments
	initVconf();

	// Init ecore
	initEcore();

	// If succeed to accept a connection, start a main loop.
	g_main_loop_run(gMainLoop);

	// Deinitializing vconf
	deinitVconf();

	ALOGI("Server is terminated successfully\n");

	return ret;
}

//! End of a file
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>
#include <test/test_bitcoin.h>
#include <consensus/merkle.h>
#include <chainparams.h>
#include <miner.h>
#include <validation.h>

//Tests data
CAmount value(5000000000LL - 1000);
dev::u256 gasPrice(3);
dev::u256 gasLimit(655535);
std::vector<unsigned char> address(ParseHex("abababababababababababababababababababab"));
std::vector<unsigned char> data(ParseHex("6060604052346000575b60398060166000396000f30060606040525b600b5b5b565b0000a165627a7a72305820a5e02d6fa08a384e067a4c1f749729c502e7597980b427d287386aa006e49d6d0029"));

BOOST_FIXTURE_TEST_SUITE(qtumtxconverter_tests, TestingSetup)

BOOST_AUTO_TEST_CASE(parse_txcreate){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(1);
    tx2.vout[0].nValue = value;
    tx2.vout[0].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == 1);
    BOOST_CHECK(result[0].isCreation());
    BOOST_CHECK(result[0].data() == data);
    BOOST_CHECK(result[0].value() == value);
    BOOST_CHECK(result[0].gasPrice() == gasPrice);
    BOOST_CHECK(result[0].gas() == gasLimit * gasPrice);
    BOOST_CHECK(result[0].sender() == dev::Address(address));
    BOOST_CHECK(result[0].receiveAddress() == dev::Address());
    BOOST_CHECK(result[0].getNVout() == 0);
    BOOST_CHECK(result[0].getHashWith() == uintToh256(tx2.GetHash()));
}

BOOST_AUTO_TEST_CASE(parse_txcall){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(1);
    tx2.vout[0].nValue = value;
    tx2.vout[0].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == 1);
    BOOST_CHECK(!result[0].isCreation());
    BOOST_CHECK(result[0].data() == data);
    BOOST_CHECK(result[0].value() == value);
    BOOST_CHECK(result[0].gasPrice() == gasPrice);
    BOOST_CHECK(result[0].gas() == gasLimit * gasPrice);
    BOOST_CHECK(result[0].sender() == dev::Address(address));
    BOOST_CHECK(result[0].receiveAddress() == dev::Address(address));
    BOOST_CHECK(result[0].getNVout() == 0);
    BOOST_CHECK(result[0].getHashWith() == uintToh256(tx2.GetHash()));
}

BOOST_AUTO_TEST_CASE(parse_txcreate_many_vout){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(113);
    for(size_t i = 0; i < tx2.vout.size(); i++){
        tx2.vout[i].nValue = value;
        tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
    }

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == tx2.vout.size());
    for(size_t i = 0; i < tx2.vout.size(); i++){
        BOOST_CHECK(result[i].isCreation());
        BOOST_CHECK(result[i].data() == data);
        BOOST_CHECK(result[i].value() == value);
        BOOST_CHECK(result[i].gasPrice() == gasPrice);
        BOOST_CHECK(result[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(result[i].sender() == dev::Address(address));
        BOOST_CHECK(result[i].receiveAddress() == dev::Address());
        BOOST_CHECK(result[i].getNVout() == i);
        BOOST_CHECK(result[i].getHashWith() == uintToh256(tx2.GetHash()));
    }
}

BOOST_AUTO_TEST_CASE(parse_txcall_many_vout){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(113);
    for(size_t i = 0; i < tx2.vout.size(); i++){
        tx2.vout[i].nValue = value;
        tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
    }

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == tx2.vout.size());
    for(size_t i = 0; i < tx2.vout.size(); i++){
        BOOST_CHECK(!result[i].isCreation());
        BOOST_CHECK(result[i].data() == data);
        BOOST_CHECK(result[i].value() == value);
        BOOST_CHECK(result[i].gasPrice() == gasPrice);
        BOOST_CHECK(result[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(result[i].sender() == dev::Address(address));
        BOOST_CHECK(result[i].receiveAddress() == dev::Address(address));
        BOOST_CHECK(result[i].getNVout() == i);
        BOOST_CHECK(result[i].getHashWith() == uintToh256(tx2.GetHash()));
    }
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcreate_many){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(120);
    for(size_t i = 0; i < tx2.vout.size(); i++){
        if(i < 60){
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
        } else {
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CREATE;
        }
    }

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == tx2.vout.size() / 2);
    for(size_t i = 0; i < tx2.vout.size() / 2; i++){
        BOOST_CHECK(result[i].isCreation());
        BOOST_CHECK(result[i].data() == data);
        BOOST_CHECK(result[i].value() == value);
        BOOST_CHECK(result[i].gasPrice() == gasPrice);
        BOOST_CHECK(result[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(result[i].sender() == dev::Address(address));
        BOOST_CHECK(result[i].receiveAddress() == dev::Address());
        BOOST_CHECK(result[i].getNVout() == i);
        BOOST_CHECK(result[i].getHashWith() == uintToh256(tx2.GetHash()));
    }
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcreate_few){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(120);
    for(size_t i = 0; i < tx2.vout.size(); i++){
        if(i < 60){
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
        } else {
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << OP_CREATE;
        }
    }

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == tx2.vout.size() / 2);
    for(size_t i = 0; i < tx2.vout.size() / 2; i++){
        BOOST_CHECK(result[i].isCreation());
        BOOST_CHECK(result[i].data() == data);
        BOOST_CHECK(result[i].value() == value);
        BOOST_CHECK(result[i].gasPrice() == gasPrice);
        BOOST_CHECK(result[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(result[i].sender() == dev::Address(address));
        BOOST_CHECK(result[i].receiveAddress() == dev::Address());
        BOOST_CHECK(result[i].getNVout() == i);
        BOOST_CHECK(result[i].getHashWith() == uintToh256(tx2.GetHash()));
    }
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcall_many){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(120);
    for(size_t i = 0; i < tx2.vout.size(); i++){
        if(i < 60){
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
        } else {
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << address << OP_CALL;
        }
    }

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == tx2.vout.size() / 2);
    for(size_t i = 0; i < tx2.vout.size() / 2; i++){
        BOOST_CHECK(!result[i].isCreation());
        BOOST_CHECK(result[i].data() == data);
        BOOST_CHECK(result[i].value() == value);
        BOOST_CHECK(result[i].gasPrice() == gasPrice);
        BOOST_CHECK(result[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(result[i].sender() == dev::Address(address));
        BOOST_CHECK(result[i].receiveAddress() == dev::Address(address));
        BOOST_CHECK(result[i].getNVout() == i);
        BOOST_CHECK(result[i].getHashWith() == uintToh256(tx2.GetHash()));
    }
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcall_few){

    mempool.clear();

    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    tx1.vin.resize(1);
    tx1.vin[0].scriptSig = CScript() << OP_1;
    tx1.vin[0].prevout.hash = uint256();
    tx1.vin[0].prevout.n = 0;
    tx1.vout.resize(1);
    tx1.vout[0].nValue = value;
    tx1.vout[0].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;

    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));

    tx2.vin.resize(1);
    tx2.vin[0].scriptSig = CScript() << OP_1;
    tx2.vin[0].prevout.hash = hashParentTx;
    tx2.vin[0].prevout.n = 0;
    tx2.vout.resize(120);
    for(size_t i = 0; i < tx2.vout.size(); i++){
        if(i < 60){
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
        } else {
            tx2.vout[i].nValue = value;
            tx2.vout[i].scriptPubKey = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CALL;
        }
    }

    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();

    BOOST_CHECK(result.size() == tx2.vout.size() / 2);
    for(size_t i = 0; i < tx2.vout.size() / 2; i++){
        BOOST_CHECK(!result[i].isCreation());
        BOOST_CHECK(result[i].data() == data);
        BOOST_CHECK(result[i].value() == value);
        BOOST_CHECK(result[i].gasPrice() == gasPrice);
        BOOST_CHECK(result[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(result[i].sender() == dev::Address(address));
        BOOST_CHECK(result[i].receiveAddress() == dev::Address(address));
        BOOST_CHECK(result[i].getNVout() == i);
        BOOST_CHECK(result[i].getHashWith() == uintToh256(tx2.GetHash()));
    }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Refactoring code (qtumtxconverter_tests).<commit_after>#include <boost/test/unit_test.hpp>
#include <test/test_bitcoin.h>
#include <consensus/merkle.h>
#include <chainparams.h>
#include <miner.h>
#include <validation.h>

//Tests data
CAmount value(5000000000LL - 1000);
dev::u256 gasPrice(3);
dev::u256 gasLimit(655535);
std::vector<unsigned char> address(ParseHex("abababababababababababababababababababab"));
std::vector<unsigned char> data(ParseHex("6060604052346000575b60398060166000396000f30060606040525b600b5b5b565b0000a165627a7a72305820a5e02d6fa08a384e067a4c1f749729c502e7597980b427d287386aa006e49d6d0029"));

CMutableTransaction createTX(std::vector<CTxOut> vout, uint256 hashprev = uint256()){
    CMutableTransaction tx;
    tx.vin.resize(1);
    tx.vin[0].scriptSig = CScript() << OP_1;
    tx.vin[0].prevout.hash = hashprev;
    tx.vin[0].prevout.n = 0;
    tx.vout.resize(1);
    tx.vout = vout;
    return tx;
}

void checkResult(bool isCreation, std::vector<QtumTransaction> results, uint256 hash){
    for(size_t i = 0; i < results.size(); i++){
        if(isCreation){
            BOOST_CHECK(results[i].isCreation());
            BOOST_CHECK(results[i].receiveAddress() == dev::Address());
        } else {
            BOOST_CHECK(!results[i].isCreation());
            BOOST_CHECK(results[i].receiveAddress() == dev::Address(address));
        }
        BOOST_CHECK(results[i].data() == data);
        BOOST_CHECK(results[i].value() == value);
        BOOST_CHECK(results[i].gasPrice() == gasPrice);
        BOOST_CHECK(results[i].gas() == gasLimit * gasPrice);
        BOOST_CHECK(results[i].sender() == dev::Address(address));
        BOOST_CHECK(results[i].getNVout() == i);
        BOOST_CHECK(results[i].getHashWith() == uintToh256(hash));
    }
}

void runTest(bool isCreation, size_t n, CScript& script1, CScript script2 = CScript()){
    mempool.clear();
    TestMemPoolEntryHelper entry;
    CMutableTransaction tx1, tx2;
    std::vector<CTxOut> outs1 = {CTxOut(value, CScript() << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG)};
    tx1 = createTX(outs1);
    uint256 hashParentTx = tx1.GetHash(); // save this txid for later use
    mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx1));
    std::vector<CTxOut> outs2;
    for(size_t i = 0; i < n; i++){
        if(script2 == CScript()){
            outs2.push_back(CTxOut(value, script1));
        } else {
            if(i < n / 2){
                outs2.push_back(CTxOut(value, script1));
            } else {
                outs2.push_back(CTxOut(value, script2));
            }
        }
    }
    tx2 = createTX(outs2, hashParentTx);
    CTransaction transaction(tx2);
    QtumTxConverter converter(transaction, NULL);
    std::vector<QtumTransaction> result = converter.extractionQtumTransactions();
    if(script2 == CScript()){
        BOOST_CHECK(result.size() == n);
    } else {
        BOOST_CHECK(result.size() == n / 2);
    }
    checkResult(isCreation, result, tx2.GetHash());
}

BOOST_FIXTURE_TEST_SUITE(qtumtxconverter_tests, TestingSetup)

BOOST_AUTO_TEST_CASE(parse_txcreate){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
    runTest(true, 1, script1);
}

BOOST_AUTO_TEST_CASE(parse_txcall){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
    runTest(false, 1, script1);
}

BOOST_AUTO_TEST_CASE(parse_txcreate_many_vout){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
    runTest(true, 120, script1);
}

BOOST_AUTO_TEST_CASE(parse_txcall_many_vout){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
    runTest(false, 120, script1);
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcreate_many){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
    CScript script2 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CREATE;
    runTest(true, 120, script1, script2);
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcreate_few){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CREATE;
    CScript script2 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << OP_CREATE;
    runTest(true, 120, script1, script2);
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcall_many){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
    CScript script2 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << address << OP_CALL;
    runTest(false, 120, script1, script2);
}

BOOST_AUTO_TEST_CASE(parse_incorrect_txcall_few){
    CScript script1 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << address << OP_CALL;
    CScript script2 = CScript() << CScriptNum(1) << CScriptNum(int64_t(gasLimit)) << CScriptNum(int64_t(gasPrice)) << data << OP_CALL;
    runTest(false, 120, script1, script2);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>
#include "main.h"

void stoke::game::run()
{
    auto self = *this;

    // http server
    nextgen::network::server<nextgen::network::tcp_socket> s1(self->service, 80);

    // policy server
    nextgen::network::server<nextgen::network::tcp_socket> s2(self->service, 843);

    // realm server
    nextgen::network::server<nextgen::network::tcp_socket> s3(self->service, 6110);

    // game server
    nextgen::network::server<nextgen::network::tcp_socket> s4(self->service, 6111);

    // chat server
    nextgen::network::server<nextgen::network::tcp_socket> s5(self->service, 6112);

    s1.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::http_client client(socket);

        client.receive(
        [self, client](nextgen::network::http_message response)
        {

        },
        []()
        {

        });
    });

    s2.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::xml_client client(socket);

        client.receive(
        [self, client](nextgen::network::xml_message response)
        {

        },
        []()
        {

        });
    });

    s3.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::ngp_client client(socket);

        client.receive(
        [self, client](nextgen::network::ngp_message response)
        {

        },
        []()
        {

        });
    });

    s4.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::ngp_client client(socket);

        client.receive(
        [self, client](nextgen::network::ngp_message response)
        {

        },
        []()
        {

        });
    });

    s5.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::ngp_client client(socket);

        client.receive(
        [self, client](nextgen::network::ngp_message response)
        {

        },
        []()
        {

        });
    });

    nextgen::timer timer;
    timer.start();

    while(true)
    {
        try
        {
            if(timer.stop() > 1.0f)
            {
                timer.start();
            }

            self->service.update();

            boost::this_thread::sleep(boost::posix_time::milliseconds(5));
        }
        catch(boost::exception& e)
        {
            std::cout << "[stoke:game:run] " << "Unexpected exception caught in " << BOOST_CURRENT_FUNCTION << std::endl << boost::current_exception_diagnostic_information();
        }
    }
}

int main()
{
    social_satan::main::instance().run();
}
<commit_msg>Fixed names.<commit_after>
#include "main.h"

void stoke::game::run()
{
    auto self = *this;

    // http server
    nextgen::network::server<nextgen::network::tcp_socket> s1(self->service, 80);

    // policy server
    nextgen::network::server<nextgen::network::tcp_socket> s2(self->service, 843);

    // realm server
    nextgen::network::server<nextgen::network::tcp_socket> s3(self->service, 6110);

    // game server
    nextgen::network::server<nextgen::network::tcp_socket> s4(self->service, 6111);

    // chat server
    nextgen::network::server<nextgen::network::tcp_socket> s5(self->service, 6112);

    s1.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::http_client client(socket);

        client.receive(
        [self, client](nextgen::network::http_message response)
        {

        },
        []()
        {

        });
    });

    s2.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::xml_client client(socket);

        client.receive(
        [self, client](nextgen::network::xml_message response)
        {

        },
        []()
        {

        });
    });

    s3.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::ngp_client client(socket);

        client.receive(
        [self, client](nextgen::network::ngp_message response)
        {

        },
        []()
        {

        });
    });

    s4.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::ngp_client client(socket);

        client.receive(
        [self, client](nextgen::network::ngp_message response)
        {

        },
        []()
        {

        });
    });

    s5.accept(
    [self](nextgen::network::tcp_socket socket)
    {
        nextgen::network::ngp_client client(socket);

        client.receive(
        [self, client](nextgen::network::ngp_message response)
        {

        },
        []()
        {

        });
    });

    nextgen::timer timer;
    timer.start();

    while(true)
    {
        try
        {
            if(timer.stop() > 1.0f)
            {
                timer.start();
            }

            self->service.update();

            boost::this_thread::sleep(boost::posix_time::milliseconds(5));
        }
        catch(boost::exception& e)
        {
            std::cout << "[stoke:game:run] " << "Unexpected exception caught in " << BOOST_CURRENT_FUNCTION << std::endl << boost::current_exception_diagnostic_information();
        }
    }
}

int main()
{
    stoke::game::instance().run();
}
<|endoftext|>


<commit_before>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "halfling/halfling_engine.h"

#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	CrateDemo::GraphicsManager graphicsManager;
	CrateDemo::GameStateManager gameStateManager;

	Halfling::HalflingEngine engine(&graphicsManager, &gameStateManager);

	engine.Initialize(L"Crate Demo", 800, 600, false);
	engine.Run();

	engine.Shutdown();

	return 0;
}
<commit_msg>CRATE_DEMO: Pass hInstance to the engine<commit_after>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "halfling/halfling_engine.h"

#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	CrateDemo::GraphicsManager graphicsManager;
	CrateDemo::GameStateManager gameStateManager;

	Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager);

	engine.Initialize(L"Crate Demo", 800, 600, false);
	engine.Run();

	engine.Shutdown();

	return 0;
}
<|endoftext|>


<commit_before>/*=============================================================================

  Library: CTK

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "ctkServiceTrackerPrivate.h"
#include "ctkTrackedService_p.h"
#include "ctkServiceException.h"
#include "ctkPluginConstants.h"
#include "ctkPluginContext.h"

#include <QVarLengthArray>
#include <QDebug>

#include <stdexcept>
#include <limits>

template<class S, class T>
ctkServiceTracker<S,T>::~ctkServiceTracker()
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext* context,
                                          const ctkServiceReference& reference,
                                          ServiceTrackerCustomizer* customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, reference, customizer))
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext* context, const QString& clazz,
                                          ServiceTrackerCustomizer* customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, clazz, customizer))
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext* context, const ctkLDAPSearchFilter& filter,
                                          ServiceTrackerCustomizer* customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, filter, customizer))
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext *context, ctkServiceTrackerCustomizer<T> *customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, qobject_interface_iid<S>(), customizer))
{
  const char* clazz = qobject_interface_iid<S>();
  if (clazz == 0) throw ctkServiceException("The service interface class has no Q_DECLARE_INTERFACE macro");
}

template<class S, class T>
void ctkServiceTracker<S,T>::open()
{
  Q_D(ServiceTracker);
  QSharedPointer<TrackedService> t;
  {
    QMutexLocker lock(&d->mutex);
    if (d->trackedService)
    {
      return;
    }

    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::open: " << d->filter;
    }

    t = QSharedPointer<TrackedService>(
          new TrackedService(this, d->customizer));
    {
      QMutexLocker lockT(t.data());
      try {
        d->context->connectServiceListener(t.data(), "serviceChanged", d->listenerFilter);
        QList<ctkServiceReference> references;
        if (!d->trackClass.isEmpty())
        {
          references = d->getInitialReferences(d->trackClass, QString());
        }
        else
        {
          if (!d->trackReference.getPlugin().isNull())
          {
            references.push_back(d->trackReference);
          }
          else
          { /* user supplied filter */
            references = d->getInitialReferences(QString(),
                                              (d->listenerFilter.isNull()) ? d->filter.toString() : d->listenerFilter);
          }
        }
        /* set tracked with the initial references */
        t->setInitial(references);
      }
      catch (const std::invalid_argument& e)
      {
        throw std::runtime_error(std::string("unexpected std::invalid_argument exception: ")
            + e.what());
      }
    }
    d->trackedService = t;
  }
  /* Call tracked outside of synchronized region */
  t->trackInitial(); /* process the initial references */
}

template<class S, class T>
void ctkServiceTracker<S,T>::close()
{
  Q_D(ServiceTracker);
  QSharedPointer<TrackedService> outgoing;
  QList<ctkServiceReference> references;
  {
    QMutexLocker lock(&d->mutex);
    outgoing = d->trackedService;
    if (outgoing.isNull())
    {
      return;
    }
    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::close:" << d->filter;
    }
    outgoing->close();
    references = getServiceReferences();
    d->trackedService.clear();;
    try
    {
      d->context->disconnectServiceListener(outgoing.data(), "serviceChanged");
    }
    catch (const std::logic_error& /*e*/)
    {
      /* In case the context was stopped. */
    }
  }
  d->modified(); /* clear the cache */
  {
    QMutexLocker lockT(outgoing.data());
    outgoing->wakeAll(); /* wake up any waiters */
  }
  foreach (ctkServiceReference ref, references)
  {
    outgoing->untrack(ref, ctkServiceEvent());
  }

  if (d->DEBUG)
  {
    QMutexLocker lock(&d->mutex);
    if ((d->cachedReference.getPlugin().isNull()) && (d->cachedService == 0))
    {
      qDebug() << "ctkServiceTracker<S,T>::close[cached cleared]:"
          << d->filter;
    }
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::waitForService(unsigned long timeout)
{
  Q_D(ServiceTracker);
  T object = getService();
  while (object == 0)
  {
    QSharedPointer<TrackedService> t = d->tracked();
    if (t.isNull())
    { /* if ServiceTracker is not open */
      return 0;
    }
    {
      QMutexLocker lockT(t.data());
      if (t->size() == 0)
      {
        t->wait(timeout);
      }
    }
    object = getService();
    if (timeout > 0)
    {
      return object;
    }
  }
  return object;
}

template<class S, class T>
QList<ctkServiceReference> ctkServiceTracker<S,T>::getServiceReferences() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return QList<ctkServiceReference>();
  }
  {
    QMutexLocker lockT(t.data());
    if (t->size() == 0)
    {
      return QList<ctkServiceReference>();
    }
    return t->getTracked();
  }
}

template<class S, class T>
ctkServiceReference ctkServiceTracker<S,T>::getServiceReference() const
{
  Q_D(const ServiceTracker);
  ctkServiceReference reference(0);
  {
    QMutexLocker lock(&d->mutex);
    reference = d->cachedReference;
  }
  if (!reference.getPlugin().isNull())
  {
    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::getServiceReference[cached]:"
                   << d->filter;
    }
    return reference;
  }
  if (d->DEBUG)
  {
    qDebug() << "ctkServiceTracker<S,T>::getServiceReference:" << d->filter;
  }
  QList<ctkServiceReference> references = getServiceReferences();
  int length = references.size();
  if (length == 0)
  { /* if no service is being tracked */
    throw ctkServiceException("No service is being tracked");
  }
  int index = 0;
  if (length > 1)
  { /* if more than one service, select highest ranking */
    QVarLengthArray<int, 10> rankings(length);
    int count = 0;
    int maxRanking = std::numeric_limits<int>::min();
    for (int i = 0; i < length; i++)
    {
      bool ok = false;
      int ranking = references[i].getProperty(ctkPluginConstants::SERVICE_RANKING).toInt(&ok);
      if (!ok) ranking = 0;

      rankings[i] = ranking;
      if (ranking > maxRanking)
      {
        index = i;
        maxRanking = ranking;
        count = 1;
      }
      else
      {
        if (ranking == maxRanking)
        {
          count++;
        }
      }
    }
    if (count > 1)
    { /* if still more than one service, select lowest id */
      qlonglong minId = std::numeric_limits<qlonglong>::max();
      for (int i = 0; i < length; i++)
      {
        if (rankings[i] == maxRanking)
        {
          qlonglong id = references[i].getProperty(ctkPluginConstants::SERVICE_ID).toLongLong();
          if (id < minId)
          {
            index = i;
            minId = id;
          }
        }
      }
    }
  }

  {
    QMutexLocker lock(&d->mutex);
    d->cachedReference = references[index];
    return d->cachedReference;
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::getService(const ctkServiceReference& reference) const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return 0;
  }
  {
    QMutexLocker lockT(t.data());
    return t->getCustomizedObject(reference);
  }
}

template<class S, class T>
QList<T> ctkServiceTracker<S,T>::getServices() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return QList<QObject*>();
  }
  {
    QMutexLocker lockT(t.data());
    QList<ctkServiceReference> references = getServiceReferences();
    QList<QObject*> objects;
    foreach (ctkServiceReference ref, references)
    {
      objects << getService(ref);
    }
    return objects;
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::getService() const
{
  Q_D(const ServiceTracker);
  T service = d->cachedService;
  if (service != 0)
  {
    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::getService[cached]:"
                   << d->filter;
    }
    return service;
  }
  if (d->DEBUG)
  {
    qDebug() << "ctkServiceTracker<S,T>::getService:" << d->filter;
  }

  try
  {
    ctkServiceReference reference = getServiceReference();
    if (reference.getPlugin().isNull())
    {
      return 0;
    }
    return d->cachedService = getService(reference);
  }
  catch (const ctkServiceException&)
  {
    return 0;
  }
}

template<class S, class T>
void ctkServiceTracker<S,T>::remove(const ctkServiceReference& reference)
{
  Q_D(ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return;
  }
  t->untrack(reference, ctkServiceEvent());
}

template<class S, class T>
int ctkServiceTracker<S,T>::size() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return 0;
  }
  {
    QMutexLocker lockT(t.data());
    return t->size();
  }
}

template<class S, class T>
int ctkServiceTracker<S,T>::getTrackingCount() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return -1;
  }
  {
    QMutexLocker lockT(t.data());
    return t->getTrackingCount();
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::addingService(const ctkServiceReference& reference)
{
  Q_D(ServiceTracker);
  return qobject_cast<T>(d->context->getService(reference));
}

template<class S, class T>
void ctkServiceTracker<S,T>::modifiedService(const ctkServiceReference& reference, T service)
{
  Q_UNUSED(reference)
  Q_UNUSED(service)
  /* do nothing */
}

template<class S, class T>
void ctkServiceTracker<S,T>::removedService(const ctkServiceReference& reference, T service)
{
  Q_UNUSED(service)

  Q_D(ServiceTracker);
  d->context->ungetService(reference);
}
<commit_msg>Change QObject* to T in ctkServiceTracker.<commit_after>/*=============================================================================

  Library: CTK

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "ctkServiceTrackerPrivate.h"
#include "ctkTrackedService_p.h"
#include "ctkServiceException.h"
#include "ctkPluginConstants.h"
#include "ctkPluginContext.h"

#include <QVarLengthArray>
#include <QDebug>

#include <stdexcept>
#include <limits>

template<class S, class T>
ctkServiceTracker<S,T>::~ctkServiceTracker()
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext* context,
                                          const ctkServiceReference& reference,
                                          ServiceTrackerCustomizer* customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, reference, customizer))
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext* context, const QString& clazz,
                                          ServiceTrackerCustomizer* customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, clazz, customizer))
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext* context, const ctkLDAPSearchFilter& filter,
                                          ServiceTrackerCustomizer* customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, filter, customizer))
{
}

template<class S, class T>
ctkServiceTracker<S,T>::ctkServiceTracker(ctkPluginContext *context, ctkServiceTrackerCustomizer<T> *customizer)
  : d_ptr(new ServiceTrackerPrivate(this, context, qobject_interface_iid<S>(), customizer))
{
  const char* clazz = qobject_interface_iid<S>();
  if (clazz == 0) throw ctkServiceException("The service interface class has no Q_DECLARE_INTERFACE macro");
}

template<class S, class T>
void ctkServiceTracker<S,T>::open()
{
  Q_D(ServiceTracker);
  QSharedPointer<TrackedService> t;
  {
    QMutexLocker lock(&d->mutex);
    if (d->trackedService)
    {
      return;
    }

    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::open: " << d->filter;
    }

    t = QSharedPointer<TrackedService>(
          new TrackedService(this, d->customizer));
    {
      QMutexLocker lockT(t.data());
      try {
        d->context->connectServiceListener(t.data(), "serviceChanged", d->listenerFilter);
        QList<ctkServiceReference> references;
        if (!d->trackClass.isEmpty())
        {
          references = d->getInitialReferences(d->trackClass, QString());
        }
        else
        {
          if (!d->trackReference.getPlugin().isNull())
          {
            references.push_back(d->trackReference);
          }
          else
          { /* user supplied filter */
            references = d->getInitialReferences(QString(),
                                              (d->listenerFilter.isNull()) ? d->filter.toString() : d->listenerFilter);
          }
        }
        /* set tracked with the initial references */
        t->setInitial(references);
      }
      catch (const std::invalid_argument& e)
      {
        throw std::runtime_error(std::string("unexpected std::invalid_argument exception: ")
            + e.what());
      }
    }
    d->trackedService = t;
  }
  /* Call tracked outside of synchronized region */
  t->trackInitial(); /* process the initial references */
}

template<class S, class T>
void ctkServiceTracker<S,T>::close()
{
  Q_D(ServiceTracker);
  QSharedPointer<TrackedService> outgoing;
  QList<ctkServiceReference> references;
  {
    QMutexLocker lock(&d->mutex);
    outgoing = d->trackedService;
    if (outgoing.isNull())
    {
      return;
    }
    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::close:" << d->filter;
    }
    outgoing->close();
    references = getServiceReferences();
    d->trackedService.clear();;
    try
    {
      d->context->disconnectServiceListener(outgoing.data(), "serviceChanged");
    }
    catch (const std::logic_error& /*e*/)
    {
      /* In case the context was stopped. */
    }
  }
  d->modified(); /* clear the cache */
  {
    QMutexLocker lockT(outgoing.data());
    outgoing->wakeAll(); /* wake up any waiters */
  }
  foreach (ctkServiceReference ref, references)
  {
    outgoing->untrack(ref, ctkServiceEvent());
  }

  if (d->DEBUG)
  {
    QMutexLocker lock(&d->mutex);
    if ((d->cachedReference.getPlugin().isNull()) && (d->cachedService == 0))
    {
      qDebug() << "ctkServiceTracker<S,T>::close[cached cleared]:"
          << d->filter;
    }
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::waitForService(unsigned long timeout)
{
  Q_D(ServiceTracker);
  T object = getService();
  while (object == 0)
  {
    QSharedPointer<TrackedService> t = d->tracked();
    if (t.isNull())
    { /* if ServiceTracker is not open */
      return 0;
    }
    {
      QMutexLocker lockT(t.data());
      if (t->size() == 0)
      {
        t->wait(timeout);
      }
    }
    object = getService();
    if (timeout > 0)
    {
      return object;
    }
  }
  return object;
}

template<class S, class T>
QList<ctkServiceReference> ctkServiceTracker<S,T>::getServiceReferences() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return QList<ctkServiceReference>();
  }
  {
    QMutexLocker lockT(t.data());
    if (t->size() == 0)
    {
      return QList<ctkServiceReference>();
    }
    return t->getTracked();
  }
}

template<class S, class T>
ctkServiceReference ctkServiceTracker<S,T>::getServiceReference() const
{
  Q_D(const ServiceTracker);
  ctkServiceReference reference(0);
  {
    QMutexLocker lock(&d->mutex);
    reference = d->cachedReference;
  }
  if (!reference.getPlugin().isNull())
  {
    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::getServiceReference[cached]:"
                   << d->filter;
    }
    return reference;
  }
  if (d->DEBUG)
  {
    qDebug() << "ctkServiceTracker<S,T>::getServiceReference:" << d->filter;
  }
  QList<ctkServiceReference> references = getServiceReferences();
  int length = references.size();
  if (length == 0)
  { /* if no service is being tracked */
    throw ctkServiceException("No service is being tracked");
  }
  int index = 0;
  if (length > 1)
  { /* if more than one service, select highest ranking */
    QVarLengthArray<int, 10> rankings(length);
    int count = 0;
    int maxRanking = std::numeric_limits<int>::min();
    for (int i = 0; i < length; i++)
    {
      bool ok = false;
      int ranking = references[i].getProperty(ctkPluginConstants::SERVICE_RANKING).toInt(&ok);
      if (!ok) ranking = 0;

      rankings[i] = ranking;
      if (ranking > maxRanking)
      {
        index = i;
        maxRanking = ranking;
        count = 1;
      }
      else
      {
        if (ranking == maxRanking)
        {
          count++;
        }
      }
    }
    if (count > 1)
    { /* if still more than one service, select lowest id */
      qlonglong minId = std::numeric_limits<qlonglong>::max();
      for (int i = 0; i < length; i++)
      {
        if (rankings[i] == maxRanking)
        {
          qlonglong id = references[i].getProperty(ctkPluginConstants::SERVICE_ID).toLongLong();
          if (id < minId)
          {
            index = i;
            minId = id;
          }
        }
      }
    }
  }

  {
    QMutexLocker lock(&d->mutex);
    d->cachedReference = references[index];
    return d->cachedReference;
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::getService(const ctkServiceReference& reference) const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return 0;
  }
  {
    QMutexLocker lockT(t.data());
    return t->getCustomizedObject(reference);
  }
}

template<class S, class T>
QList<T> ctkServiceTracker<S,T>::getServices() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return QList<T>();
  }
  {
    QMutexLocker lockT(t.data());
    QList<ctkServiceReference> references = getServiceReferences();
    QList<T> objects;
    foreach (ctkServiceReference ref, references)
    {
      objects << getService(ref);
    }
    return objects;
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::getService() const
{
  Q_D(const ServiceTracker);
  T service = d->cachedService;
  if (service != 0)
  {
    if (d->DEBUG)
    {
      qDebug() << "ctkServiceTracker<S,T>::getService[cached]:"
                   << d->filter;
    }
    return service;
  }
  if (d->DEBUG)
  {
    qDebug() << "ctkServiceTracker<S,T>::getService:" << d->filter;
  }

  try
  {
    ctkServiceReference reference = getServiceReference();
    if (reference.getPlugin().isNull())
    {
      return 0;
    }
    return d->cachedService = getService(reference);
  }
  catch (const ctkServiceException&)
  {
    return 0;
  }
}

template<class S, class T>
void ctkServiceTracker<S,T>::remove(const ctkServiceReference& reference)
{
  Q_D(ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return;
  }
  t->untrack(reference, ctkServiceEvent());
}

template<class S, class T>
int ctkServiceTracker<S,T>::size() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return 0;
  }
  {
    QMutexLocker lockT(t.data());
    return t->size();
  }
}

template<class S, class T>
int ctkServiceTracker<S,T>::getTrackingCount() const
{
  Q_D(const ServiceTracker);
  QSharedPointer<TrackedService> t = d->tracked();
  if (t.isNull())
  { /* if ServiceTracker is not open */
    return -1;
  }
  {
    QMutexLocker lockT(t.data());
    return t->getTrackingCount();
  }
}

template<class S, class T>
T ctkServiceTracker<S,T>::addingService(const ctkServiceReference& reference)
{
  Q_D(ServiceTracker);
  return qobject_cast<T>(d->context->getService(reference));
}

template<class S, class T>
void ctkServiceTracker<S,T>::modifiedService(const ctkServiceReference& reference, T service)
{
  Q_UNUSED(reference)
  Q_UNUSED(service)
  /* do nothing */
}

template<class S, class T>
void ctkServiceTracker<S,T>::removedService(const ctkServiceReference& reference, T service)
{
  Q_UNUSED(service)

  Q_D(ServiceTracker);
  d->context->ungetService(reference);
}
<|endoftext|>