<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCPluginManager.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCPluginManager
//
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#pragma comment( lib, "ws2_32.lib" )

#ifdef NF_DEBUG_MODE

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif

#else

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif

#endif

bool NFCPluginManager::LoadPlugin()
{
    rapidxml::file<> fdoc( "Plugin.xml" );
    rapidxml::xml_document<>  doc;
    doc.parse<0>( fdoc.data() );

    rapidxml::xml_node<>* pRoot = doc.first_node();
    for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
    {
        const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
        const char* strMain = pPluginNode->first_attribute( "Main" )->value();

		mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));

    }

    rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
    if (!pPluginAppNode)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
    if (!strAppID)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    if (!NF_StrTo(strAppID, mnAppID))
    {
        NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
        return false;
    }

    return true;
}

void NFCPluginManager::Registered(NFIPlugin* plugin)
{
    std::string strPluginName = plugin->GetPluginName();
    if (!FindPlugin(strPluginName))
    {
        bool bFind = false;
        PluginNameMap::iterator it = mPluginNameMap.begin();
        for (it; it != mPluginNameMap.end(); ++it)
        {
            if (strPluginName == it->first)
            {
                bFind = true;
                break;
            }
        }

        if (bFind)
        {
            mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
            plugin->Install();
        }
    }

}

void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
    if (it != mPluginInstanceMap.end())
    {
        it->second->Uninstall();
		delete it->second;
        it->second = NULL;
        mPluginInstanceMap.erase(it);
    }
}

NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
    if (it != mPluginInstanceMap.end())
    {
        return it->second;
    }

    return NULL;
}

bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
    bool bRet = true;

    PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
    for (; it != mPluginInstanceMap.end(); ++it)
    {
        bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
        bRet = bRet && tembRet;
    }

	ExecuteEvent();

    return bRet;
}

void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
    if (!FindModule(strModuleName))
    {
        mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
    }
}

void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        mModuleInstanceMap.erase(it);
    }
}

NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        return it->second;
    }
    return NULL;
}

bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
    LoadPlugin();

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); ++it)
    {
        LoadPluginLibrary(it->first);
    }

#endif

#else
    //     PluginNameList::iterator it = mPluginNameList.begin();
    //     for (it; it != mPluginNameList.end(); it++)
    //     {
    //         const std::string& strPluginName = *it;
    //         CREATE_PLUGIN( this, strPluginName );
    //     }

    //     CREATE_PLUGIN(this, NFKernelPlugin)
    //     CREATE_PLUGIN(this, NFEventProcessPlugin)
    //     CREATE_PLUGIN(this, NFConfigPlugin)

#endif

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
    {
        itInstance->second->Init();
    }

    return true;
}

bool NFCPluginManager::AfterInit()
{
    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
    {
        itAfterInstance->second->AfterInit();
    }

    return true;
}

bool NFCPluginManager::CheckConfig()
{
    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

bool NFCPluginManager::BeforeShut()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
    {
        itBeforeInstance->second->BeforeShut();
    }

    return true;
}

bool NFCPluginManager::Shut()
{

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
    {
        itInstance->second->Shut();
    }

#ifdef NF_DYNAMIC_PLUGIN

    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); it++)
    {
        UnLoadPluginLibrary(it->first);
    }

#else

    //     DESTROY_PLUGIN(this, NFConfigPlugin)
    //     DESTROY_PLUGIN(this, NFEventProcessPlugin)
    //     DESTROY_PLUGIN(this, NFKernelPlugin)

#endif
	mPluginInstanceMap.clear();
    mPluginNameMap.clear();
	return true;
}

bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it == mPluginLibMap.end())
    {
        NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
        bool bLoad = pLib->Load();

        if (bLoad)
        {
            mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));

            DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
            if (!pFunc)
            {
                std::cout << "Find function DllStartPlugin Failed in [" << pLib->GetName() << "]" << std::endl;
                assert(0);
                return false;
            }

            pFunc(this);

            return true;
        }
        else
        {
#if NF_PLATFORM == NF_PLATFORM_LINUX
            char* error = dlerror();
            if (error)
            {
                printf(stderr, "Open shared lib %s failed, %s.\n", pLib->GetName(), error);
                assert(0);
                return false;
            }
#endif // NF_PLATFORM
            std::cout << "Load [" << pLib->GetName() << "] Failed" << std::endl;
            assert(0);
        }
    }

    return false;
}

bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it != mPluginLibMap.end())
    {
        NFCDynLib* pLib = it->second;

        DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");

        if (pFunc)
        {
            pFunc(this);
        }

        pLib->UnLoad();

        delete pLib;
        pLib = NULL;
        mPluginLibMap.erase(it);

        return true;
    }

    return false;
}

bool NFCPluginManager::ReInitialize()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
    {
        itBeforeInstance->second->BeforeShut();
    }

    PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
    for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
    {
        itShutDownInstance->second->Shut();
    }

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
    {
        itInstance->second->Init();
    }

    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
    {
        itAfterInstance->second->AfterInit();
    }

    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
	//ӵУÿִ֡
	mxQueue.Push(message);
}

bool NFCPluginManager::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
		{
			xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nSubMsgID, xMsg.data);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}
<commit_msg>fixed compile error for linux<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCPluginManager.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCPluginManager
//
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#pragma comment( lib, "ws2_32.lib" )

#ifdef NF_DEBUG_MODE

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif

#else

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif

#endif

bool NFCPluginManager::LoadPlugin()
{
    rapidxml::file<> fdoc( "Plugin.xml" );
    rapidxml::xml_document<>  doc;
    doc.parse<0>( fdoc.data() );

    rapidxml::xml_node<>* pRoot = doc.first_node();
    for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
    {
        const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
        const char* strMain = pPluginNode->first_attribute( "Main" )->value();

		mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));

    }

    rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
    if (!pPluginAppNode)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
    if (!strAppID)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    if (!NF_StrTo(strAppID, mnAppID))
    {
        NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
        return false;
    }

    return true;
}

void NFCPluginManager::Registered(NFIPlugin* plugin)
{
    std::string strPluginName = plugin->GetPluginName();
    if (!FindPlugin(strPluginName))
    {
        bool bFind = false;
        PluginNameMap::iterator it = mPluginNameMap.begin();
        for (it; it != mPluginNameMap.end(); ++it)
        {
            if (strPluginName == it->first)
            {
                bFind = true;
                break;
            }
        }

        if (bFind)
        {
            mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
            plugin->Install();
        }
    }

}

void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
    if (it != mPluginInstanceMap.end())
    {
        it->second->Uninstall();
		delete it->second;
        it->second = NULL;
        mPluginInstanceMap.erase(it);
    }
}

NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
    if (it != mPluginInstanceMap.end())
    {
        return it->second;
    }

    return NULL;
}

bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
    bool bRet = true;

    PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
    for (; it != mPluginInstanceMap.end(); ++it)
    {
        bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
        bRet = bRet && tembRet;
    }

	ExecuteEvent();

    return bRet;
}

void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
    if (!FindModule(strModuleName))
    {
        mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
    }
}

void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        mModuleInstanceMap.erase(it);
    }
}

NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        return it->second;
    }
    return NULL;
}

bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
    LoadPlugin();

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); ++it)
    {
        LoadPluginLibrary(it->first);
    }

#endif

#else
    //     PluginNameList::iterator it = mPluginNameList.begin();
    //     for (it; it != mPluginNameList.end(); it++)
    //     {
    //         const std::string& strPluginName = *it;
    //         CREATE_PLUGIN( this, strPluginName );
    //     }

    //     CREATE_PLUGIN(this, NFKernelPlugin)
    //     CREATE_PLUGIN(this, NFEventProcessPlugin)
    //     CREATE_PLUGIN(this, NFConfigPlugin)

#endif

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
    {
        itInstance->second->Init();
    }

    return true;
}

bool NFCPluginManager::AfterInit()
{
    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
    {
        itAfterInstance->second->AfterInit();
    }

    return true;
}

bool NFCPluginManager::CheckConfig()
{
    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

bool NFCPluginManager::BeforeShut()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
    {
        itBeforeInstance->second->BeforeShut();
    }

    return true;
}

bool NFCPluginManager::Shut()
{

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
    {
        itInstance->second->Shut();
    }

#ifdef NF_DYNAMIC_PLUGIN

    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); it++)
    {
        UnLoadPluginLibrary(it->first);
    }

#else

    //     DESTROY_PLUGIN(this, NFConfigPlugin)
    //     DESTROY_PLUGIN(this, NFEventProcessPlugin)
    //     DESTROY_PLUGIN(this, NFKernelPlugin)

#endif
	mPluginInstanceMap.clear();
    mPluginNameMap.clear();
	return true;
}

bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it == mPluginLibMap.end())
    {
        NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
        bool bLoad = pLib->Load();

        if (bLoad)
        {
            mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));

            DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
            if (!pFunc)
            {
                std::cout << "Find function DllStartPlugin Failed in [" << pLib->GetName() << "]" << std::endl;
                assert(0);
                return false;
            }

            pFunc(this);

            return true;
        }
        else
        {
#if NF_PLATFORM == NF_PLATFORM_LINUX
            char* error = dlerror();
            if (error)
            {
				std::cout << stderr << " Open shared lib failed " << pLib->GetName() << " " << error << std::endl;
                assert(0);
                return false;
            }
#endif // NF_PLATFORM
            std::cout << "Load [" << pLib->GetName() << "] Failed" << std::endl;
            assert(0);
        }
    }

    return false;
}

bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it != mPluginLibMap.end())
    {
        NFCDynLib* pLib = it->second;

        DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");

        if (pFunc)
        {
            pFunc(this);
        }

        pLib->UnLoad();

        delete pLib;
        pLib = NULL;
        mPluginLibMap.erase(it);

        return true;
    }

    return false;
}

bool NFCPluginManager::ReInitialize()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
    {
        itBeforeInstance->second->BeforeShut();
    }

    PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
    for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
    {
        itShutDownInstance->second->Shut();
    }

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
    {
        itInstance->second->Init();
    }

    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
    {
        itAfterInstance->second->AfterInit();
    }

    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
	//ӵУÿִ֡
	mxQueue.Push(message);
}

bool NFCPluginManager::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
		{
			xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nSubMsgID, xMsg.data);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}
<|endoftext|>


<commit_before>/**
 * @file Cognition.cpp
 *
 * @author Heinrich Mellmann
 * Implementation of the class Cognition
 */

#include "Cognition.h"

#include <PlatformInterface/Platform.h>

// tools
#include "Tools/Debug/Trace.h"

/////////////////////////////////////
// Modules
/////////////////////////////////////

// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"

#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"

#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"

// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV2/CameraMatrixCorrectorV2.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"

#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"

#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"

#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"

#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"

#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"

#include "Modules/Modeling/CompassProvider/CompassProvider.h"

// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Modeling/ObstacleLocator/UltraSoundObstacleLocator.h"
#include "Modules/Modeling/ObstacleLocator/UltrasonicObstacleLocator2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"

// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"

#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"

#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"

#include "Modules/Modeling/Simulation/SimulationTest.h"
#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"

// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"

using namespace std;

Cognition::Cognition()
  : ModuleManagerWithDebug("")
{
}

Cognition::~Cognition()
{
}

#define REGISTER_MODULE(module) \
  std::cout << "[Cognition] Register " << #module << std::endl;\
  registerModule<module>(std::string(#module))

void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
  std::cout << "[Cognition] Cognition register start" << std::endl;

  // register input module
  ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
  sensor->getModuleT()->init(platformInterface, platform);

  /*
  * to register a module use
  *   REGISTER_MODULE(ModuleClassName);
  *
  * Remark: to enable the module don't forget
  *         to set the value in modules.cfg
  */

  // -- BEGIN REGISTER MODULES --

  // infrastructure
  REGISTER_MODULE(ButtonEventMonitor);
  REGISTER_MODULE(WifiModeSetter);
  REGISTER_MODULE(TeamCommReceiver);
  REGISTER_MODULE(SimpleNetworkTimeProtocol);
  REGISTER_MODULE(GameController);
  REGISTER_MODULE(BatteryAlert);
  REGISTER_MODULE(LEDSetter);
  REGISTER_MODULE(UltraSoundControl);

  REGISTER_MODULE(CameraDebug);
  REGISTER_MODULE(CameraInfoSetter);
  REGISTER_MODULE(AdaptiveAutoExposure);
  REGISTER_MODULE(WhistleDetectorV1);
  REGISTER_MODULE(WhistleDetectorV2);

  // perception
  REGISTER_MODULE(CameraMatrixFinder);
  REGISTER_MODULE(KinematicChainProvider);
  REGISTER_MODULE(ArtificialHorizonCalculator);
  REGISTER_MODULE(BodyContourProvider);
  REGISTER_MODULE(CameraMatrixCorrectorV2);

  REGISTER_MODULE(HistogramProvider);
  REGISTER_MODULE(IntegralImageProvider);
  REGISTER_MODULE(FieldColorClassifier);
  REGISTER_MODULE(IntegralFieldDetector);
  REGISTER_MODULE(ScanLineEdgelDetector);
  REGISTER_MODULE(FieldDetector);
  REGISTER_MODULE(LineGraphProvider);
  REGISTER_MODULE(GoalFeatureDetector);
  REGISTER_MODULE(GoalFeatureDetectorV2);
  REGISTER_MODULE(GoalDetector);
  REGISTER_MODULE(GoalDetectorV2);
  REGISTER_MODULE(GoalCrossBarDetector);

  REGISTER_MODULE(NoGreenObstacleDetector);

  REGISTER_MODULE(RedBallDetector);
  REGISTER_MODULE(CNNBallDetector);

  REGISTER_MODULE(FakeCameraMatrixFinder);
  REGISTER_MODULE(FakeBallDetector);

  REGISTER_MODULE(VirtualVisionProcessor);
  REGISTER_MODULE(PerceptionsVisualizer);

  REGISTER_MODULE(RansacLineDetector);
  REGISTER_MODULE(RansacLineDetectorOnGraphs);
  REGISTER_MODULE(LineAugmenter);

  REGISTER_MODULE(CompassProvider);

  // modeling
  REGISTER_MODULE(SituationPriorProvider);
  REGISTER_MODULE(BodyStateProvider);
  REGISTER_MODULE(FieldCompass);
  REGISTER_MODULE(UltraSoundObstacleLocator);
  REGISTER_MODULE(UltrasonicObstacleLocator2020);
  REGISTER_MODULE(TeamCommReceiveEmulator);
  REGISTER_MODULE(TeamMessageStatisticsModule);
  REGISTER_MODULE(TeamMessagePlayersStateModule);
  REGISTER_MODULE(SoccerStrategyProvider);
  REGISTER_MODULE(PotentialFieldProvider);
  REGISTER_MODULE(GPS_SelfLocator);
  REGISTER_MODULE(MonteCarloSelfLocator);
  REGISTER_MODULE(OdometrySelfLocator);
  REGISTER_MODULE(WholeGoalLocator);
  REGISTER_MODULE(DummyActiveGoalLocator);
  REGISTER_MODULE(MultiKalmanBallLocator);

  REGISTER_MODULE(TeamBallLocatorMedian);
  REGISTER_MODULE(TeamBallLocatorCanopyCluster);

  /*
   * BEGIN ROLE DECISIONS
   */
  REGISTER_MODULE(RolesProvider);
  // first set the position of the roles
  REGISTER_MODULE(RoleDecisionPositionStatic);
  REGISTER_MODULE(RoleDecisionPositionForce);
  REGISTER_MODULE(RoleDecisionPositionPotentialField);
  REGISTER_MODULE(RoleDecisionPositionFormation);
  REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
  // then decide which player should have which role
  REGISTER_MODULE(RoleDecisionAssignmentStatic);
  REGISTER_MODULE(RoleDecisionAssignmentDistance);
  // finally, determine the dynamic role (striker, supporter, ...)
  REGISTER_MODULE(RoleDecisionDynamic);

  // old striker decisions
  REGISTER_MODULE(SimpleRoleDecision);
  REGISTER_MODULE(StableRoleDecision);
  REGISTER_MODULE(CleanRoleDecision);
  /*
   * END ROLE DECISIONS
   */

  REGISTER_MODULE(KickDirectionSimulator);
  REGISTER_MODULE(Simulation);
  REGISTER_MODULE(SimulationTest);
  REGISTER_MODULE(StaticDebugModelProvider);

  // behavior
  REGISTER_MODULE(BasicTestBehavior);
  REGISTER_MODULE(XABSLBehaviorControl);
  REGISTER_MODULE(PathPlanner);
  REGISTER_MODULE(PathPlanner2018);

  // This is to prevent accidental use of a non working Camera Matrix Corrector. A different name is shown in Robotcontrol
  //REGISTER_MODULE(CameraMatrixCorrectorV3);
  registerModule<CameraMatrixCorrectorV3>("FIXMECameraMatrixCorrectorV3", false);

  REGISTER_MODULE(TeamCommSender);

  // debug
  REGISTER_MODULE(GameLogger);
  REGISTER_MODULE(Debug);
  REGISTER_MODULE(FrameRateCheck);
  REGISTER_MODULE(DebugExecutor);

  // -- END REGISTER MODULES --

  // register output module
  ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
  actuator->getModuleT()->init(platformInterface, platform);

  // use the configuration in order to set whether a module is activated or not
  const naoth::Configuration& config = Platform::getInstance().theConfiguration;

  list<string>::const_iterator name = getExecutionList().begin();
  for(;name != getExecutionList().end(); ++name)
  {
    bool active = false;
    if(config.hasKey("modules", *name)) {
      active = config.getBool("modules", *name);
    }
    if(active) {
      std::cout << "[Cognition] activating module " << *name << std::endl;
    }
    setModuleEnabled(*name, active);
  }//end for

  // auto-generate the execution list
  //calculateExecutionList();

  std::cout << "[Cognition] register end" << std::endl;

  stopwatch.start();
}//end init

void Cognition::call()
{
  // BEGIN cognition frame rate measuring
  stopwatch.stop();
  stopwatch.start();
  PLOT("Cognition.Cycle", stopwatch.lastValue);
  // END cognition frame rate measuring

  STOPWATCH_START("Cognition.Execute");

  // execute all modules
  list<AbstractModuleCreator*>::const_iterator iter;
  for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
  {
    AbstractModuleCreator* module = *iter;
    if (module != NULL && module->isEnabled())
    {
      std::string name(module->getModule()->getName());
      GT_TRACE("executing " << name);
      module->execute();
    }
  }

  STOPWATCH_STOP("Cognition.Execute");

  // HACK: reset all the debug stuff before executing the modules
  STOPWATCH_START("Cognition.Debug.Init");
  getDebugDrawings().reset();
  getDebugImageDrawings().reset();
  getDebugImageDrawingsTop().reset();
  getDebugDrawings3D().reset();
  STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
<commit_msg>register new module in cognition<commit_after>/**
 * @file Cognition.cpp
 *
 * @author Heinrich Mellmann
 * Implementation of the class Cognition
 */

#include "Cognition.h"

#include <PlatformInterface/Platform.h>

// tools
#include "Tools/Debug/Trace.h"

/////////////////////////////////////
// Modules
/////////////////////////////////////

// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"

#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"

#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"

// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV2/CameraMatrixCorrectorV2.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"

#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"

#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"

#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"

#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"

#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"

#include "Modules/Modeling/CompassProvider/CompassProvider.h"

// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Modeling/ObstacleLocator/UltraSoundObstacleLocator.h"
#include "Modules/Modeling/ObstacleLocator/UltrasonicObstacleLocator2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"

// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"

#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"

#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"

#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"

#include "Modules/Modeling/Simulation/SimulationTest.h"
#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"

// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"

using namespace std;

Cognition::Cognition()
  : ModuleManagerWithDebug("")
{
}

Cognition::~Cognition()
{
}

#define REGISTER_MODULE(module) \
  std::cout << "[Cognition] Register " << #module << std::endl;\
  registerModule<module>(std::string(#module))

void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
  std::cout << "[Cognition] Cognition register start" << std::endl;

  // register input module
  ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
  sensor->getModuleT()->init(platformInterface, platform);

  /*
  * to register a module use
  *   REGISTER_MODULE(ModuleClassName);
  *
  * Remark: to enable the module don't forget
  *         to set the value in modules.cfg
  */

  // -- BEGIN REGISTER MODULES --

  // infrastructure
  REGISTER_MODULE(ButtonEventMonitor);
  REGISTER_MODULE(WifiModeSetter);
  REGISTER_MODULE(TeamCommReceiver);
  REGISTER_MODULE(SimpleNetworkTimeProtocol);
  REGISTER_MODULE(GameController);
  REGISTER_MODULE(BatteryAlert);
  REGISTER_MODULE(LEDSetter);
  REGISTER_MODULE(UltraSoundControl);

  REGISTER_MODULE(CameraDebug);
  REGISTER_MODULE(CameraInfoSetter);
  REGISTER_MODULE(AdaptiveAutoExposure);
  REGISTER_MODULE(WhistleDetectorV1);
  REGISTER_MODULE(WhistleDetectorV2);

  // perception
  REGISTER_MODULE(CameraMatrixFinder);
  REGISTER_MODULE(KinematicChainProvider);
  REGISTER_MODULE(ArtificialHorizonCalculator);
  REGISTER_MODULE(BodyContourProvider);
  REGISTER_MODULE(CameraMatrixCorrectorV2);

  REGISTER_MODULE(HistogramProvider);
  REGISTER_MODULE(IntegralImageProvider);
  REGISTER_MODULE(FieldColorClassifier);
  REGISTER_MODULE(IntegralFieldDetector);
  REGISTER_MODULE(ScanLineEdgelDetector);
  REGISTER_MODULE(FieldDetector);
  REGISTER_MODULE(LineGraphProvider);
  REGISTER_MODULE(GoalFeatureDetector);
  REGISTER_MODULE(GoalFeatureDetectorV2);
  REGISTER_MODULE(GoalDetector);
  REGISTER_MODULE(GoalDetectorV2);
  REGISTER_MODULE(GoalCrossBarDetector);

  REGISTER_MODULE(NoGreenObstacleDetector);

  REGISTER_MODULE(RedBallDetector);
  REGISTER_MODULE(CNNBallDetector);

  REGISTER_MODULE(FakeCameraMatrixFinder);
  REGISTER_MODULE(FakeBallDetector);

  REGISTER_MODULE(VirtualVisionProcessor);
  REGISTER_MODULE(PerceptionsVisualizer);

  REGISTER_MODULE(RansacLineDetector);
  REGISTER_MODULE(RansacLineDetectorOnGraphs);
  REGISTER_MODULE(LineAugmenter);

  REGISTER_MODULE(CompassProvider);

  // modeling
  REGISTER_MODULE(SituationPriorProvider);
  REGISTER_MODULE(BodyStateProvider);
  REGISTER_MODULE(FieldCompass);
  REGISTER_MODULE(UltraSoundObstacleLocator);
  REGISTER_MODULE(UltrasonicObstacleLocator2020);
  REGISTER_MODULE(TeamCommReceiveEmulator);
  REGISTER_MODULE(TeamMessageStatisticsModule);
  REGISTER_MODULE(TeamMessagePlayersStateModule);
  REGISTER_MODULE(SoccerStrategyProvider);
  REGISTER_MODULE(PotentialFieldProvider);
  REGISTER_MODULE(GPS_SelfLocator);
  REGISTER_MODULE(MonteCarloSelfLocator);
  REGISTER_MODULE(OdometrySelfLocator);
  REGISTER_MODULE(WholeGoalLocator);
  REGISTER_MODULE(DummyActiveGoalLocator);
  REGISTER_MODULE(MultiKalmanBallLocator);

  REGISTER_MODULE(TeamBallLocatorMedian);
  REGISTER_MODULE(TeamBallLocatorCanopyCluster);

  REGISTER_MODULE(MultiUnifiedObstacleLocator);
  /*
   * BEGIN ROLE DECISIONS
   */
  REGISTER_MODULE(RolesProvider);
  // first set the position of the roles
  REGISTER_MODULE(RoleDecisionPositionStatic);
  REGISTER_MODULE(RoleDecisionPositionForce);
  REGISTER_MODULE(RoleDecisionPositionPotentialField);
  REGISTER_MODULE(RoleDecisionPositionFormation);
  REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
  // then decide which player should have which role
  REGISTER_MODULE(RoleDecisionAssignmentStatic);
  REGISTER_MODULE(RoleDecisionAssignmentDistance);
  // finally, determine the dynamic role (striker, supporter, ...)
  REGISTER_MODULE(RoleDecisionDynamic);

  // old striker decisions
  REGISTER_MODULE(SimpleRoleDecision);
  REGISTER_MODULE(StableRoleDecision);
  REGISTER_MODULE(CleanRoleDecision);
  /*
   * END ROLE DECISIONS
   */

  REGISTER_MODULE(KickDirectionSimulator);
  REGISTER_MODULE(Simulation);
  REGISTER_MODULE(SimulationTest);
  REGISTER_MODULE(StaticDebugModelProvider);

  // behavior
  REGISTER_MODULE(BasicTestBehavior);
  REGISTER_MODULE(XABSLBehaviorControl);
  REGISTER_MODULE(PathPlanner);
  REGISTER_MODULE(PathPlanner2018);

  // This is to prevent accidental use of a non working Camera Matrix Corrector. A different name is shown in Robotcontrol
  //REGISTER_MODULE(CameraMatrixCorrectorV3);
  registerModule<CameraMatrixCorrectorV3>("FIXMECameraMatrixCorrectorV3", false);

  REGISTER_MODULE(TeamCommSender);

  // debug
  REGISTER_MODULE(GameLogger);
  REGISTER_MODULE(Debug);
  REGISTER_MODULE(FrameRateCheck);
  REGISTER_MODULE(DebugExecutor);

  // -- END REGISTER MODULES --

  // register output module
  ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
  actuator->getModuleT()->init(platformInterface, platform);

  // use the configuration in order to set whether a module is activated or not
  const naoth::Configuration& config = Platform::getInstance().theConfiguration;

  list<string>::const_iterator name = getExecutionList().begin();
  for(;name != getExecutionList().end(); ++name)
  {
    bool active = false;
    if(config.hasKey("modules", *name)) {
      active = config.getBool("modules", *name);
    }
    if(active) {
      std::cout << "[Cognition] activating module " << *name << std::endl;
    }
    setModuleEnabled(*name, active);
  }//end for

  // auto-generate the execution list
  //calculateExecutionList();

  std::cout << "[Cognition] register end" << std::endl;

  stopwatch.start();
}//end init

void Cognition::call()
{
  // BEGIN cognition frame rate measuring
  stopwatch.stop();
  stopwatch.start();
  PLOT("Cognition.Cycle", stopwatch.lastValue);
  // END cognition frame rate measuring

  STOPWATCH_START("Cognition.Execute");

  // execute all modules
  list<AbstractModuleCreator*>::const_iterator iter;
  for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
  {
    AbstractModuleCreator* module = *iter;
    if (module != NULL && module->isEnabled())
    {
      std::string name(module->getModule()->getName());
      GT_TRACE("executing " << name);
      module->execute();
    }
  }

  STOPWATCH_STOP("Cognition.Execute");

  // HACK: reset all the debug stuff before executing the modules
  STOPWATCH_START("Cognition.Debug.Init");
  getDebugDrawings().reset();
  getDebugImageDrawings().reset();
  getDebugImageDrawingsTop().reset();
  getDebugDrawings3D().reset();
  STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/JoynrMessage.h"

#include <iostream>
#include <string>
#include <utility>
#include <memory>
#include <chrono>

#include "joynr/Util.h"
#include "joynr/Variant.h"

namespace joynr
{
INIT_LOGGER(JoynrMessage);

static bool isJoynrMessageRegistered = Variant::registerType<JoynrMessage>("joynr.JoynrMessage");

const std::string& JoynrMessage::HEADER_CONTENT_TYPE()
{
    static const std::string headerContentType("contentType");
    return headerContentType;
}

const std::string& JoynrMessage::HEADER_MESSAGE_ID()
{
    static const std::string headerMessageId("msgId");
    return headerMessageId;
}

const std::string& JoynrMessage::HEADER_CREATOR_USER_ID()
{
    static const std::string headerCreatorUserId("creator");
    return headerCreatorUserId;
}

const std::string& JoynrMessage::HEADER_TO()
{
    static const std::string headerTo("to");
    return headerTo;
}
const std::string& JoynrMessage::HEADER_FROM()
{
    static const std::string headerFrom("from");
    return headerFrom;
}
const std::string& JoynrMessage::HEADER_EXPIRY_DATE()
{
    static const std::string headerExpiryDate("expiryDate");
    return headerExpiryDate;
}
const std::string& JoynrMessage::HEADER_REPLY_ADDRESS()
{
    static const std::string headerReplyAddress("replyChannelId");
    return headerReplyAddress;
}

const std::string JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY = "oneWay";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_REPLY = "reply";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST = "request";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION = "subscriptionPublication";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY = "subscriptionReply";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST = "subscriptionRequest";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST =
        "broadcastSubscriptionRequest";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_STOP = "subscriptionStop";

const std::string JoynrMessage::VALUE_CONTENT_TYPE_TEXT_PLAIN = "text/plain";
const std::string JoynrMessage::VALUE_CONTENT_TYPE_APPLICATION_JSON = "application/json";

JoynrMessage::JoynrMessage() : type(""), header(), payload()
{
    generateAndSetMsgIdHeaderIfAbsent();
}

JoynrMessage::JoynrMessage(const JoynrMessage& message)
        : type(message.type), header(message.header), payload(message.payload)
{
    generateAndSetMsgIdHeaderIfAbsent();
}

JoynrMessage& JoynrMessage::operator=(const JoynrMessage& message)
{
    type = message.type;
    header = message.header;
    payload = message.payload;
    generateAndSetMsgIdHeaderIfAbsent();
    return *this;
}

JoynrMessage::JoynrMessage(JoynrMessage&& message)
        : type(std::move(message.type)),
          header(std::move(message.header)),
          payload(std::move(message.payload))
{
    generateAndSetMsgIdHeaderIfAbsent();
}

JoynrMessage& JoynrMessage::operator=(JoynrMessage&& message)
{
    type = std::move(message.type);
    header = std::move(message.header);
    payload = std::move(message.payload);
    generateAndSetMsgIdHeaderIfAbsent();
    return *this;
}

void JoynrMessage::generateAndSetMsgIdHeaderIfAbsent()
{
    if (!containsHeader(HEADER_MESSAGE_ID())) {
        std::string msgId = util::createUuid();
        setHeaderForKey(HEADER_MESSAGE_ID(), msgId);
    }
}

bool JoynrMessage::operator==(const JoynrMessage& message) const
{
    return type == message.getType() && payload == message.payload && header == message.header;
}

std::string JoynrMessage::getType() const
{
    return type;
}

void JoynrMessage::setType(const std::string& type)
{
    this->type = type;
}

std::map<std::string, std::string> JoynrMessage::getHeader() const
{
    return header;
}

bool JoynrMessage::containsHeader(const std::string& key) const
{
    std::map<std::string, std::string>::const_iterator pos = header.find(key);
    if (pos == header.end()) {
        return false;
    }

    return true;
}

void JoynrMessage::setHeader(const std::map<std::string, std::string>& newHeaders)
{
    std::map<std::string, std::string>::const_iterator i = newHeaders.begin();
    while (i != newHeaders.end()) {
        if (!containsHeader(i->first)) {
            header.insert(std::pair<std::string, std::string>(i->first, i->second));
            JOYNR_LOG_DEBUG(logger, "insert header: {} = {}", i->second, i->first);
        }
        i++;
    }
}

std::string JoynrMessage::getHeaderForKey(const std::string& key) const
{
    // to avoid adding default-constructed value to the map, I use find instead of operator[]
    std::map<std::string, std::string>::const_iterator pos = header.find(key);
    if (pos == header.end()) {
        return std::string();
    }
    std::string value = pos->second;
    return value;
}

void JoynrMessage::setHeaderForKey(const std::string& key, const std::string& value)
{
    header[key] = value;
}

std::string JoynrMessage::getPayload() const
{
    return payload;
}

void JoynrMessage::setPayload(const std::string& payload)
{
    this->payload = payload;
}

void JoynrMessage::setPayload(std::string&& payload)
{
    this->payload = std::move(payload);
}

bool JoynrMessage::containsHeaderContentType() const
{
    return containsHeader(HEADER_CONTENT_TYPE());
}

std::string JoynrMessage::getHeaderContentType() const
{
    return getHeaderForKey(HEADER_CONTENT_TYPE());
}

void JoynrMessage::setHeaderContentType(const std::string& contentType)
{
    setHeaderForKey(HEADER_CONTENT_TYPE(), contentType);
}

bool JoynrMessage::containsHeaderMessageId() const
{
    return containsHeader(HEADER_MESSAGE_ID());
}

std::string JoynrMessage::getHeaderMessageId() const
{
    return getHeaderForKey(HEADER_MESSAGE_ID());
}

void JoynrMessage::setHeaderMessageId(const std::string& msgId)
{
    setHeaderForKey(HEADER_MESSAGE_ID(), msgId);
}

bool JoynrMessage::containsHeaderCreatorUserId() const
{
    return containsHeader(HEADER_CREATOR_USER_ID());
}

std::string JoynrMessage::getHeaderCreatorUserId() const
{
    return getHeaderForKey(HEADER_CREATOR_USER_ID());
}

void JoynrMessage::setHeaderCreatorUserId(const std::string& creatorUserId)
{
    JOYNR_LOG_TRACE(logger, "########## header creater user id: {}", HEADER_CREATOR_USER_ID());
    setHeaderForKey(HEADER_CREATOR_USER_ID(), creatorUserId);
}

bool JoynrMessage::containsHeaderTo() const
{
    return containsHeader(HEADER_TO());
}

std::string JoynrMessage::getHeaderTo() const
{
    return getHeaderForKey(HEADER_TO());
}

void JoynrMessage::setHeaderTo(const std::string& to)
{
    setHeaderForKey(HEADER_TO(), to);
}

bool JoynrMessage::containsHeaderFrom() const
{
    return containsHeader(HEADER_FROM());
}

std::string JoynrMessage::getHeaderFrom() const
{
    return getHeaderForKey(HEADER_FROM());
}

void JoynrMessage::setHeaderFrom(const std::string& from)
{
    setHeaderForKey(HEADER_FROM(), from);
}

bool JoynrMessage::containsHeaderExpiryDate() const
{
    return containsHeader(HEADER_EXPIRY_DATE());
}

JoynrTimePoint JoynrMessage::getHeaderExpiryDate() const
{
    std::string expiryDateString = getHeaderForKey(HEADER_EXPIRY_DATE());
    JoynrTimePoint expiryDate(std::chrono::milliseconds(std::stoll(expiryDateString)));
    return expiryDate;
}

void JoynrMessage::setHeaderExpiryDate(const JoynrTimePoint& expiryDate)
{
    setHeaderForKey(HEADER_EXPIRY_DATE(), std::to_string(expiryDate.time_since_epoch().count()));
}

bool JoynrMessage::containsHeaderReplyAddress() const
{
    return containsHeader(HEADER_REPLY_ADDRESS());
}

std::string JoynrMessage::getHeaderReplyAddress() const
{
    return getHeaderForKey(HEADER_REPLY_ADDRESS());
}

void JoynrMessage::setHeaderReplyAddress(const std::string& replyAddress)
{
    setHeaderForKey(HEADER_REPLY_ADDRESS(), replyAddress);
}

} // namespace joynr
<commit_msg>[C++] setHeader now overwrites existing values<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/JoynrMessage.h"

#include <iostream>
#include <string>
#include <utility>
#include <memory>
#include <chrono>

#include "joynr/Util.h"
#include "joynr/Variant.h"

namespace joynr
{
INIT_LOGGER(JoynrMessage);

static bool isJoynrMessageRegistered = Variant::registerType<JoynrMessage>("joynr.JoynrMessage");

const std::string& JoynrMessage::HEADER_CONTENT_TYPE()
{
    static const std::string headerContentType("contentType");
    return headerContentType;
}

const std::string& JoynrMessage::HEADER_MESSAGE_ID()
{
    static const std::string headerMessageId("msgId");
    return headerMessageId;
}

const std::string& JoynrMessage::HEADER_CREATOR_USER_ID()
{
    static const std::string headerCreatorUserId("creator");
    return headerCreatorUserId;
}

const std::string& JoynrMessage::HEADER_TO()
{
    static const std::string headerTo("to");
    return headerTo;
}
const std::string& JoynrMessage::HEADER_FROM()
{
    static const std::string headerFrom("from");
    return headerFrom;
}
const std::string& JoynrMessage::HEADER_EXPIRY_DATE()
{
    static const std::string headerExpiryDate("expiryDate");
    return headerExpiryDate;
}
const std::string& JoynrMessage::HEADER_REPLY_ADDRESS()
{
    static const std::string headerReplyAddress("replyChannelId");
    return headerReplyAddress;
}

const std::string JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY = "oneWay";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_REPLY = "reply";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST = "request";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION = "subscriptionPublication";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY = "subscriptionReply";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST = "subscriptionRequest";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST =
        "broadcastSubscriptionRequest";
const std::string JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_STOP = "subscriptionStop";

const std::string JoynrMessage::VALUE_CONTENT_TYPE_TEXT_PLAIN = "text/plain";
const std::string JoynrMessage::VALUE_CONTENT_TYPE_APPLICATION_JSON = "application/json";

JoynrMessage::JoynrMessage() : type(""), header(), payload()
{
    generateAndSetMsgIdHeaderIfAbsent();
}

JoynrMessage::JoynrMessage(const JoynrMessage& message)
        : type(message.type), header(message.header), payload(message.payload)
{
    generateAndSetMsgIdHeaderIfAbsent();
}

JoynrMessage& JoynrMessage::operator=(const JoynrMessage& message)
{
    type = message.type;
    header = message.header;
    payload = message.payload;
    generateAndSetMsgIdHeaderIfAbsent();
    return *this;
}

JoynrMessage::JoynrMessage(JoynrMessage&& message)
        : type(std::move(message.type)),
          header(std::move(message.header)),
          payload(std::move(message.payload))
{
    generateAndSetMsgIdHeaderIfAbsent();
}

JoynrMessage& JoynrMessage::operator=(JoynrMessage&& message)
{
    type = std::move(message.type);
    header = std::move(message.header);
    payload = std::move(message.payload);
    generateAndSetMsgIdHeaderIfAbsent();
    return *this;
}

void JoynrMessage::generateAndSetMsgIdHeaderIfAbsent()
{
    if (!containsHeader(HEADER_MESSAGE_ID())) {
        std::string msgId = util::createUuid();
        setHeaderForKey(HEADER_MESSAGE_ID(), msgId);
    }
}

bool JoynrMessage::operator==(const JoynrMessage& message) const
{
    return type == message.getType() && payload == message.payload && header == message.header;
}

std::string JoynrMessage::getType() const
{
    return type;
}

void JoynrMessage::setType(const std::string& type)
{
    this->type = type;
}

std::map<std::string, std::string> JoynrMessage::getHeader() const
{
    return header;
}

bool JoynrMessage::containsHeader(const std::string& key) const
{
    std::map<std::string, std::string>::const_iterator pos = header.find(key);
    if (pos == header.end()) {
        return false;
    }

    return true;
}

void JoynrMessage::setHeader(const std::map<std::string, std::string>& newHeaders)
{
    std::map<std::string, std::string>::const_iterator i = newHeaders.begin();
    while (i != newHeaders.end()) {
        if (!containsHeader(i->first)) {
            header.insert(std::pair<std::string, std::string>(i->first, i->second));
            JOYNR_LOG_DEBUG(logger, "insert header: {} = {}", i->second, i->first);
        } else {
            header[i->first] = i->second;
        }
        i++;
    }
}

std::string JoynrMessage::getHeaderForKey(const std::string& key) const
{
    // to avoid adding default-constructed value to the map, I use find instead of operator[]
    std::map<std::string, std::string>::const_iterator pos = header.find(key);
    if (pos == header.end()) {
        return std::string();
    }
    std::string value = pos->second;
    return value;
}

void JoynrMessage::setHeaderForKey(const std::string& key, const std::string& value)
{
    header[key] = value;
}

std::string JoynrMessage::getPayload() const
{
    return payload;
}

void JoynrMessage::setPayload(const std::string& payload)
{
    this->payload = payload;
}

void JoynrMessage::setPayload(std::string&& payload)
{
    this->payload = std::move(payload);
}

bool JoynrMessage::containsHeaderContentType() const
{
    return containsHeader(HEADER_CONTENT_TYPE());
}

std::string JoynrMessage::getHeaderContentType() const
{
    return getHeaderForKey(HEADER_CONTENT_TYPE());
}

void JoynrMessage::setHeaderContentType(const std::string& contentType)
{
    setHeaderForKey(HEADER_CONTENT_TYPE(), contentType);
}

bool JoynrMessage::containsHeaderMessageId() const
{
    return containsHeader(HEADER_MESSAGE_ID());
}

std::string JoynrMessage::getHeaderMessageId() const
{
    return getHeaderForKey(HEADER_MESSAGE_ID());
}

void JoynrMessage::setHeaderMessageId(const std::string& msgId)
{
    setHeaderForKey(HEADER_MESSAGE_ID(), msgId);
}

bool JoynrMessage::containsHeaderCreatorUserId() const
{
    return containsHeader(HEADER_CREATOR_USER_ID());
}

std::string JoynrMessage::getHeaderCreatorUserId() const
{
    return getHeaderForKey(HEADER_CREATOR_USER_ID());
}

void JoynrMessage::setHeaderCreatorUserId(const std::string& creatorUserId)
{
    JOYNR_LOG_TRACE(logger, "########## header creater user id: {}", HEADER_CREATOR_USER_ID());
    setHeaderForKey(HEADER_CREATOR_USER_ID(), creatorUserId);
}

bool JoynrMessage::containsHeaderTo() const
{
    return containsHeader(HEADER_TO());
}

std::string JoynrMessage::getHeaderTo() const
{
    return getHeaderForKey(HEADER_TO());
}

void JoynrMessage::setHeaderTo(const std::string& to)
{
    setHeaderForKey(HEADER_TO(), to);
}

bool JoynrMessage::containsHeaderFrom() const
{
    return containsHeader(HEADER_FROM());
}

std::string JoynrMessage::getHeaderFrom() const
{
    return getHeaderForKey(HEADER_FROM());
}

void JoynrMessage::setHeaderFrom(const std::string& from)
{
    setHeaderForKey(HEADER_FROM(), from);
}

bool JoynrMessage::containsHeaderExpiryDate() const
{
    return containsHeader(HEADER_EXPIRY_DATE());
}

JoynrTimePoint JoynrMessage::getHeaderExpiryDate() const
{
    std::string expiryDateString = getHeaderForKey(HEADER_EXPIRY_DATE());
    JoynrTimePoint expiryDate(std::chrono::milliseconds(std::stoll(expiryDateString)));
    return expiryDate;
}

void JoynrMessage::setHeaderExpiryDate(const JoynrTimePoint& expiryDate)
{
    setHeaderForKey(HEADER_EXPIRY_DATE(), std::to_string(expiryDate.time_since_epoch().count()));
}

bool JoynrMessage::containsHeaderReplyAddress() const
{
    return containsHeader(HEADER_REPLY_ADDRESS());
}

std::string JoynrMessage::getHeaderReplyAddress() const
{
    return getHeaderForKey(HEADER_REPLY_ADDRESS());
}

void JoynrMessage::setHeaderReplyAddress(const std::string& replyAddress)
{
    setHeaderForKey(HEADER_REPLY_ADDRESS(), replyAddress);
}

} // namespace joynr
<|endoftext|>


<commit_before>// FileReader.cpp
// Copyright (c) 2014 - 2015, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.

#include <string>
#include <fstream>
#include <unordered_map>

#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

#include "parser.h"
#include "compiler.h"

#define USE_MMAP true

#ifdef __MACH__
#include <mach/vm_statistics.h>
#define EXTRA_MMAP_FLAGS VM_FLAGS_SUPERPAGE_SIZE_2MB
#elif defined(MAP_HUGE_2MB)
#define EXTRA_MMAP_FLAGS MAP_HUGE_2MB
#else
#define EXTRA_MMAP_FLAGS 0
#endif

using string_view = std::experimental::string_view;
using namespace Parser;

namespace Lexer
{
	TType getNextToken(const util::FastVector<string_view>& lines, size_t* line, size_t* offset, const string_view& whole, Pin& pos, Token*);
}

namespace Compiler
{
	struct FileInnards
	{
		TokenList tokens;
		string_view fileContents;
		util::FastVector<string_view> lines;
		std::vector<size_t> importIndices;

		bool didLex = false;
		bool isLexing = false;
	};

	static std::unordered_map<std::string, FileInnards> fileList;

	static void readFile(std::string fullPath)
	{
		string_view fileContents;

		{
			auto p = prof::Profile("read file");

			// first, get the size of the file
			struct stat st;
			int ret = stat(fullPath.c_str(), &st);

			if(ret != 0)
			{
				perror("There was an error getting the file size");
				exit(-1);
			}

			size_t fileLength = st.st_size;

			int fd = open(fullPath.c_str(), O_RDONLY);
			if(fd == -1)
			{
				perror("There was an error getting opening the file");
				exit(-1);
			}

			// check if we should mmap
			// explanation: if we have EXTRA_MMAP_FLAGS, then we're getting 2MB pages -- in which case we should probably only do it
			// if we have at least 4mb worth of file.
			// if not, then just 2 * pagesize.
			#define MINIMUM_MMAP_THRESHOLD (EXTRA_MMAP_FLAGS ? (2 * 2 * 1024 * 1024) : 2 * getpagesize())
			#define _

			char* contents = 0;
			if(fileLength >= MINIMUM_MMAP_THRESHOLD && USE_MMAP)
			{
				// ok, do an mmap
				contents = (char*) mmap(0, fileLength, PROT_READ, MAP_PRIVATE | EXTRA_MMAP_FLAGS, fd, 0);
				if(contents == MAP_FAILED)
				{
					perror("There was an error getting reading the file");
					exit(-1);
				}
			}
			else
			{
				// read normally
				contents = new char[fileLength + 1];
				size_t didRead = read(fd, contents, fileLength);
				if(didRead != fileLength)
				{
					perror("There was an error getting reading the file");
					exit(-1);
				}
			}
			close(fd);

			fileContents = string_view(contents, fileLength);
		}

		// split into lines
		util::FastVector<string_view> rawlines;
		{
			auto p = prof::Profile("lines");
			string_view view = fileContents;

			while(true)
			{
				size_t ln = view.find('\n');

				if(ln != string_view::npos)
				{
					new (rawlines.getEmptySlotPtrAndAppend()) string_view(view.data(), ln + 1);
					view.remove_prefix(ln + 1);
				}
				else
				{
					break;
				}
			}

			p.finish();
		}

		Pin pos;
		FileInnards& innards = fileList[fullPath];
		{
			pos.fileID = getFileIDFromFilename(fullPath);

			innards.fileContents = std::move(fileContents);
			innards.lines = std::move(rawlines);
			innards.isLexing = true;
		}

		auto p = prof::Profile("lex");

		TokenList& ts = innards.tokens;
		{

			size_t curLine = 0;
			size_t curOffset = 0;

			bool flag = true;
			size_t i = 0;

			do {
				auto type = Lexer::getNextToken(innards.lines, &curLine, &curOffset, innards.fileContents,
					pos, ts.getEmptySlotPtrAndAppend());

				flag = (type != TType::EndOfFile);

				if(type == TType::Import)
					innards.importIndices.push_back(i);

				else if(type == TType::Invalid)
					parserError(pos, "Invalid token");

				i++;

			} while(flag);
		}

		p.finish();

		innards.didLex = true;
		innards.isLexing = false;

		/*
			file reading stats:

			~175ms reading with c++
			~20ms with read() -- split lines ~70ms
			~4ms with mmap() -- split lines ~87ms

			lexing stats:
			raw lexing takes up ~20ms
			adding to the vector takes ~65ms

			=> resizing ends up taking up 45ms of time
		*/
	}

	TokenList& getFileTokens(std::string fullPath)
	{
		if(fileList.find(fullPath) == fileList.end() || !fileList.at(fullPath).didLex)
		{
			readFile(fullPath);
			assert(fileList.find(fullPath) != fileList.end());
		}
		else if(fileList.at(fullPath).isLexing)
		{
			error("Cannot get token list of file '%s' while still lexing", fullPath.c_str());
		}

		return fileList.at(fullPath).tokens;
	}

	std::string getFileContents(std::string fullPath)
	{
		if(fileList.find(fullPath) == fileList.end())
		{
			readFile(fullPath);
			assert(fileList.find(fullPath) != fileList.end());
		}

		const auto& in = fileList.at(fullPath);
		return in.fileContents.to_string();
	}

	static std::vector<std::string> fileNames { "null" };
	static std::unordered_map<std::string, size_t> existingNames;
	const std::string& getFilenameFromID(size_t fileID)
	{
		iceAssert(fileID > 0 && fileID < fileNames.size());
		return fileNames[fileID];
	}

	size_t getFileIDFromFilename(const std::string& name)
	{
		if(existingNames.find(name) != existingNames.end())
		{
			return existingNames[name];
		}
		else
		{
			fileNames.push_back(name);
			existingNames[name] = fileNames.size() - 1;

			return fileNames.size() - 1;
		}
	}

	const util::FastVector<string_view>& getFileLines(size_t id)
	{
		std::string fp = getFilenameFromID(id);
		if(fileList.find(fp) == fileList.end())
		{
			readFile(fp);
			assert(fileList.find(fp) != fileList.end());
		}

		return fileList.at(fp).lines;
	}

	const std::vector<size_t>& getImportTokenLocationsForFile(const std::string& filename)
	{
		return fileList.at(filename).importIndices;
	}
}

<commit_msg>thx adrian<commit_after>// FileReader.cpp
// Copyright (c) 2014 - 2015, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.

#include <string>
#include <fstream>
#include <unordered_map>

#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

#include "parser.h"
#include "compiler.h"

#define USE_MMAP true

#ifdef __MACH__
#include <mach/vm_statistics.h>
#define EXTRA_MMAP_FLAGS VM_FLAGS_SUPERPAGE_SIZE_2MB
#elif defined(MAP_HUGE_2MB)
#define EXTRA_MMAP_FLAGS MAP_HUGE_2MB
#else
#define EXTRA_MMAP_FLAGS 0
#endif

using string_view = std::experimental::string_view;
using namespace Parser;

namespace Lexer
{
	TType getNextToken(const util::FastVector<string_view>& lines, size_t* line, size_t* offset, const string_view& whole, Pin& pos, Token*);
}

namespace Compiler
{
	struct FileInnards
	{
		TokenList tokens;
		string_view fileContents;
		util::FastVector<string_view> lines;
		std::vector<size_t> importIndices;

		bool didLex = false;
		bool isLexing = false;
	};

	static std::unordered_map<std::string, FileInnards> fileList;

	static void readFile(std::string fullPath)
	{
		string_view fileContents;

		{
			auto p = prof::Profile("read file");

			// first, get the size of the file
			struct stat st;
			int ret = stat(fullPath.c_str(), &st);

			if(ret != 0)
			{
				perror("There was an error getting the file size");
				exit(-1);
			}

			size_t fileLength = st.st_size;

			int fd = open(fullPath.c_str(), O_RDONLY);
			if(fd == -1)
			{
				perror("There was an error getting opening the file");
				exit(-1);
			}

			// check if we should mmap
			// explanation: if we have EXTRA_MMAP_FLAGS, then we're getting 2MB pages -- in which case we should probably only do it
			// if we have at least 4mb worth of file.
			// if not, then just 2 * pagesize.
			#define MINIMUM_MMAP_THRESHOLD (EXTRA_MMAP_FLAGS ? (2 * 2 * 1024 * 1024) : 2 * getpagesize())
			#define _

			char* contents = 0;
			if(fileLength >= MINIMUM_MMAP_THRESHOLD && USE_MMAP)
			{
				// ok, do an mmap
				contents = (char*) mmap(0, fileLength, PROT_READ, MAP_PRIVATE | EXTRA_MMAP_FLAGS, fd, 0);
				if(contents == MAP_FAILED)
				{
					perror("There was an error getting reading the file");
					exit(-1);
				}
			}
			else
			{
				// read normally
				contents = new char[fileLength + 1];
				size_t didRead = read(fd, contents, fileLength);
				if(didRead != fileLength)
				{
					perror("There was an error getting reading the file");
					exit(-1);
				}
			}
			close(fd);

			fileContents = string_view(contents, fileLength);
		}

		// split into lines
		util::FastVector<string_view> rawlines;
		{
			auto p = prof::Profile("lines");
			string_view view = fileContents;

			while(true)
			{
				size_t ln = view.find('\n');

				if(ln != string_view::npos)
				{
					new (rawlines.getEmptySlotPtrAndAppend()) string_view(view.data(), ln + 1);
					view.remove_prefix(ln + 1);
				}
				else
				{
					break;
				}
			}

			p.finish();
		}

		Pin pos;
		FileInnards& innards = fileList[fullPath];
		{
			pos.fileID = getFileIDFromFilename(fullPath);

			innards.fileContents = std::move(fileContents);
			innards.lines = std::move(rawlines);
			innards.isLexing = true;
		}

		auto p = prof::Profile("lex");

		TokenList& ts = innards.tokens;
		{

			size_t curLine = 0;
			size_t curOffset = 0;

			bool flag = true;
			size_t i = 0;

			do {
				auto type = Lexer::getNextToken(innards.lines, &curLine, &curOffset, innards.fileContents,
					pos, ts.getEmptySlotPtrAndAppend());

				flag = (type != TType::EndOfFile);

				if(type == TType::Import)
					innards.importIndices.push_back(i);

				else if(type == TType::Invalid)
					parserError(pos, "Invalid token");

				i++;

			} while(flag);
		}

		p.finish();

		innards.didLex = true;
		innards.isLexing = false;

		/*
			file reading stats:

			~175ms reading with c++
			~20ms with read() -- split lines ~70ms
			~4ms with mmap() -- split lines ~87ms

			lexing stats:
			raw lexing takes up ~20ms
			adding to the vector takes ~65ms

			=> resizing ends up taking up 45ms of time
		*/
	}

	TokenList& getFileTokens(std::string fullPath)
	{
		auto it = fileList.find(fullPath);
		if(it == fileList.end() || !(*it).second.didLex)
		{
			readFile(fullPath);
			assert(fileList.find(fullPath) != fileList.end());
		}
		else if((*it).second.isLexing)
		{
			error("Cannot get token list of file '%s' while still lexing", fullPath.c_str());
		}

		return (*it).second.tokens;
	}

	std::string getFileContents(std::string fullPath)
	{
		auto it = fileList.find(fullPath);
		if(it == fileList.end())
		{
			readFile(fullPath);
			assert(fileList.find(fullPath) != fileList.end());
		}

		const auto& in = (*it).second;
		return in.fileContents.to_string();
	}

	static std::vector<std::string> fileNames { "null" };
	static std::unordered_map<std::string, size_t> existingNames;
	const std::string& getFilenameFromID(size_t fileID)
	{
		iceAssert(fileID > 0 && fileID < fileNames.size());
		return fileNames[fileID];
	}

	size_t getFileIDFromFilename(const std::string& name)
	{
		if(existingNames.find(name) != existingNames.end())
		{
			return existingNames[name];
		}
		else
		{
			fileNames.push_back(name);
			existingNames[name] = fileNames.size() - 1;

			return fileNames.size() - 1;
		}
	}

	const util::FastVector<string_view>& getFileLines(size_t id)
	{
		std::string fp = getFilenameFromID(id);
		auto it = fileList.find(fp);

		if(it == fileList.end())
		{
			readFile(fp);
			assert(fileList.find(fp) != fileList.end());
		}

		return (*it).second.lines;
	}

	const std::vector<size_t>& getImportTokenLocationsForFile(const std::string& filename)
	{
		return fileList[filename].importIndices;
	}
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/first_run_dialog.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/message_loop.h"
#include "chrome/app/breakpad_linux.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/google_update_settings.h"
#include "grit/generated_resources.h"
#include "grit/google_chrome_strings.h"
#include "grit/locale_settings.h"

// static
bool FirstRunDialog::Show(Profile* profile) {
  int response = -1;
  new FirstRunDialog(profile, response);
  return (response == GTK_RESPONSE_ACCEPT);
}

FirstRunDialog::FirstRunDialog(Profile* profile, int& response)
    : dialog_(NULL), report_crashes_(NULL), make_default_(NULL),
      import_data_(NULL), import_profile_(NULL), profile_(profile),
      response_(response), importer_host_(new ImporterHost()) {
  dialog_ = gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_TITLE).c_str(),
      NULL,  // No parent
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_OK).c_str(),
      GTK_RESPONSE_ACCEPT,
      l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_CANCEL).c_str(),
      GTK_RESPONSE_REJECT,
      NULL);
  gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);
  int width, height;
  gtk_util::GetWidgetSizeFromResources(dialog_,
                                       IDS_FIRSTRUN_DIALOG_WIDTH_CHARS,
                                       IDS_FIRSTRUN_DIALOG_HEIGHT_LINES,
                                       &width, &height);
  gtk_window_set_default_size(GTK_WINDOW(dialog_), width, height);
  g_signal_connect(G_OBJECT(dialog_), "delete-event",
                   G_CALLBACK(gtk_widget_hide_on_delete), NULL);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), 18);

  GtkWidget* vbox = gtk_vbox_new(FALSE, 12);

#if defined(GOOGLE_CHROME_BUILD)
  // TODO(port): remove this warning before beta release when we have all the
  // privacy features working.
  GtkWidget* privacy_label = gtk_label_new(
      "This version of Google Chrome for Linux is not appropriate for "
      "general consumer use.  Certain privacy features are unavailable "
      "at this time as described in our privacy policy at");
  gtk_misc_set_alignment(GTK_MISC(privacy_label), 0, 0);
  gtk_label_set_line_wrap(GTK_LABEL(privacy_label), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), privacy_label, FALSE, FALSE, 0);

  GtkWidget* url_label = gtk_label_new(NULL);
  gtk_label_set_markup(GTK_LABEL(url_label),
      "<tt>http://www.google.com/chrome/intl/en/privacy_linux.html</tt>");
  // Set selectable to allow copy and paste.
  gtk_label_set_selectable(GTK_LABEL(url_label), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), url_label, FALSE, FALSE, 0);

  report_crashes_ = gtk_check_button_new();
  GtkWidget* check_label = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_OPTIONS_ENABLE_LOGGING).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(check_label), TRUE);
  gtk_container_add(GTK_CONTAINER(report_crashes_), check_label);
  gtk_box_pack_start(GTK_BOX(vbox), report_crashes_, FALSE, FALSE, 0);
#endif

  make_default_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_FR_CUSTOMIZE_DEFAULT_BROWSER).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), make_default_, FALSE, FALSE, 0);

  GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
  import_data_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_FR_CUSTOMIZE_IMPORT).c_str());
  gtk_box_pack_start(GTK_BOX(combo_hbox), import_data_, FALSE, FALSE, 0);
  import_profile_ = gtk_combo_box_new_text();
  gtk_box_pack_start(GTK_BOX(combo_hbox), import_profile_, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0);

  // Detect any supported browsers that we can import from and fill
  // up the combo box. If none found, disable import data checkbox.
  int profiles_count = importer_host_->GetAvailableProfileCount();
  if (profiles_count > 0) {
    for (int i = 0; i < profiles_count; i++) {
      std::wstring profile = importer_host_->GetSourceProfileNameAt(i);
      gtk_combo_box_append_text(GTK_COMBO_BOX(import_profile_),
                                WideToUTF8(profile).c_str());
    }
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(import_data_), TRUE);
    gtk_combo_box_set_active(GTK_COMBO_BOX(import_profile_), 0);
  } else {
    gtk_combo_box_append_text(GTK_COMBO_BOX(import_profile_),
        l10n_util::GetStringUTF8(IDS_IMPORT_NO_PROFILE_FOUND).c_str());
    gtk_combo_box_set_active(GTK_COMBO_BOX(import_profile_), 0);
    gtk_widget_set_sensitive(import_data_, FALSE);
    gtk_widget_set_sensitive(import_profile_, FALSE);
  }

  gtk_box_pack_start(GTK_BOX(content_area), vbox, FALSE, FALSE, 0);

  // TODO(port): it should be sufficient to just run the dialog:
  // int response = gtk_dialog_run(GTK_DIALOG(dialog));
  // but that spins a nested message loop and hoses us.  :(
  // http://code.google.com/p/chromium/issues/detail?id=12552
  // Instead, run a loop and extract the response manually.
  g_signal_connect(G_OBJECT(dialog_), "response",
                   G_CALLBACK(HandleOnResponseDialog), this);
  gtk_widget_show_all(dialog_);
  MessageLoop::current()->Run();
}

void FirstRunDialog::OnDialogResponse(GtkWidget* widget, int response) {
  bool import_started = false;
  gtk_widget_hide_all(dialog_);
  response_ = response;

  if (response == GTK_RESPONSE_ACCEPT) {
    // Mark that first run has ran.
    FirstRun::CreateSentinel();

    // Check if user has opted into reporting.
    if (report_crashes_ &&
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(report_crashes_))) {
      if (GoogleUpdateSettings::SetCollectStatsConsent(true)) {
        PrefService* local_state = g_browser_process->local_state();
        if (local_state)
          local_state->SetBoolean(prefs::kMetricsReportingEnabled, true);
        else
          NOTREACHED();
        InitCrashReporter();
      }
    } else {
      GoogleUpdateSettings::SetCollectStatsConsent(false);
    }

    // If selected set as default browser.
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(make_default_)))
      ShellIntegration::SetAsDefaultBrowser();

    // Import data if selected.
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(import_data_))) {
      const ProfileInfo& source_profile =
          importer_host_->GetSourceProfileInfoAt(
          gtk_combo_box_get_active(GTK_COMBO_BOX(import_profile_)));
      int items = SEARCH_ENGINES + HISTORY + FAVORITES + HOME_PAGE + PASSWORDS;
      // TODO(port): Should we do the actual import in a new process like
      // Windows?
      StartImportingWithUI(GTK_WINDOW(dialog_), items, importer_host_.get(),
                           source_profile, profile_, this, true);
      import_started = true;
    }
  }
  if (!import_started)
    FirstRunDone();
}

void FirstRunDialog::FirstRunDone() {
  // Set preference to show first run bubble and welcome page.
  FirstRun::SetShowFirstRunBubblePref();
  FirstRun::SetShowWelcomePagePref();

  gtk_widget_destroy(dialog_);
  MessageLoop::current()->Quit();
}
<commit_msg>linux: swap buttons on first run dialog<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/first_run_dialog.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/message_loop.h"
#include "chrome/app/breakpad_linux.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/google_update_settings.h"
#include "grit/generated_resources.h"
#include "grit/google_chrome_strings.h"
#include "grit/locale_settings.h"

// static
bool FirstRunDialog::Show(Profile* profile) {
  int response = -1;
  new FirstRunDialog(profile, response);
  return (response == GTK_RESPONSE_ACCEPT);
}

FirstRunDialog::FirstRunDialog(Profile* profile, int& response)
    : dialog_(NULL), report_crashes_(NULL), make_default_(NULL),
      import_data_(NULL), import_profile_(NULL), profile_(profile),
      response_(response), importer_host_(new ImporterHost()) {
  dialog_ = gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_TITLE).c_str(),
      NULL,  // No parent
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CANCEL,
      GTK_RESPONSE_REJECT,
      l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_OK).c_str(),
      GTK_RESPONSE_ACCEPT,
      NULL);
  gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);
  int width, height;
  gtk_util::GetWidgetSizeFromResources(dialog_,
                                       IDS_FIRSTRUN_DIALOG_WIDTH_CHARS,
                                       IDS_FIRSTRUN_DIALOG_HEIGHT_LINES,
                                       &width, &height);
  gtk_window_set_default_size(GTK_WINDOW(dialog_), width, height);
  g_signal_connect(G_OBJECT(dialog_), "delete-event",
                   G_CALLBACK(gtk_widget_hide_on_delete), NULL);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), 18);

  GtkWidget* vbox = gtk_vbox_new(FALSE, 12);

#if defined(GOOGLE_CHROME_BUILD)
  // TODO(port): remove this warning before beta release when we have all the
  // privacy features working.
  GtkWidget* privacy_label = gtk_label_new(
      "This version of Google Chrome for Linux is not appropriate for "
      "general consumer use.  Certain privacy features are unavailable "
      "at this time as described in our privacy policy at");
  gtk_misc_set_alignment(GTK_MISC(privacy_label), 0, 0);
  gtk_label_set_line_wrap(GTK_LABEL(privacy_label), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), privacy_label, FALSE, FALSE, 0);

  GtkWidget* url_label = gtk_label_new(NULL);
  gtk_label_set_markup(GTK_LABEL(url_label),
      "<tt>http://www.google.com/chrome/intl/en/privacy_linux.html</tt>");
  // Set selectable to allow copy and paste.
  gtk_label_set_selectable(GTK_LABEL(url_label), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), url_label, FALSE, FALSE, 0);

  report_crashes_ = gtk_check_button_new();
  GtkWidget* check_label = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_OPTIONS_ENABLE_LOGGING).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(check_label), TRUE);
  gtk_container_add(GTK_CONTAINER(report_crashes_), check_label);
  gtk_box_pack_start(GTK_BOX(vbox), report_crashes_, FALSE, FALSE, 0);
#endif

  make_default_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_FR_CUSTOMIZE_DEFAULT_BROWSER).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), make_default_, FALSE, FALSE, 0);

  GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
  import_data_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_FR_CUSTOMIZE_IMPORT).c_str());
  gtk_box_pack_start(GTK_BOX(combo_hbox), import_data_, FALSE, FALSE, 0);
  import_profile_ = gtk_combo_box_new_text();
  gtk_box_pack_start(GTK_BOX(combo_hbox), import_profile_, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0);

  // Detect any supported browsers that we can import from and fill
  // up the combo box. If none found, disable import data checkbox.
  int profiles_count = importer_host_->GetAvailableProfileCount();
  if (profiles_count > 0) {
    for (int i = 0; i < profiles_count; i++) {
      std::wstring profile = importer_host_->GetSourceProfileNameAt(i);
      gtk_combo_box_append_text(GTK_COMBO_BOX(import_profile_),
                                WideToUTF8(profile).c_str());
    }
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(import_data_), TRUE);
    gtk_combo_box_set_active(GTK_COMBO_BOX(import_profile_), 0);
  } else {
    gtk_combo_box_append_text(GTK_COMBO_BOX(import_profile_),
        l10n_util::GetStringUTF8(IDS_IMPORT_NO_PROFILE_FOUND).c_str());
    gtk_combo_box_set_active(GTK_COMBO_BOX(import_profile_), 0);
    gtk_widget_set_sensitive(import_data_, FALSE);
    gtk_widget_set_sensitive(import_profile_, FALSE);
  }

  gtk_box_pack_start(GTK_BOX(content_area), vbox, FALSE, FALSE, 0);

  // TODO(port): it should be sufficient to just run the dialog:
  // int response = gtk_dialog_run(GTK_DIALOG(dialog));
  // but that spins a nested message loop and hoses us.  :(
  // http://code.google.com/p/chromium/issues/detail?id=12552
  // Instead, run a loop and extract the response manually.
  g_signal_connect(G_OBJECT(dialog_), "response",
                   G_CALLBACK(HandleOnResponseDialog), this);
  gtk_widget_show_all(dialog_);
  MessageLoop::current()->Run();
}

void FirstRunDialog::OnDialogResponse(GtkWidget* widget, int response) {
  bool import_started = false;
  gtk_widget_hide_all(dialog_);
  response_ = response;

  if (response == GTK_RESPONSE_ACCEPT) {
    // Mark that first run has ran.
    FirstRun::CreateSentinel();

    // Check if user has opted into reporting.
    if (report_crashes_ &&
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(report_crashes_))) {
      if (GoogleUpdateSettings::SetCollectStatsConsent(true)) {
        PrefService* local_state = g_browser_process->local_state();
        if (local_state)
          local_state->SetBoolean(prefs::kMetricsReportingEnabled, true);
        else
          NOTREACHED();
        InitCrashReporter();
      }
    } else {
      GoogleUpdateSettings::SetCollectStatsConsent(false);
    }

    // If selected set as default browser.
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(make_default_)))
      ShellIntegration::SetAsDefaultBrowser();

    // Import data if selected.
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(import_data_))) {
      const ProfileInfo& source_profile =
          importer_host_->GetSourceProfileInfoAt(
          gtk_combo_box_get_active(GTK_COMBO_BOX(import_profile_)));
      int items = SEARCH_ENGINES + HISTORY + FAVORITES + HOME_PAGE + PASSWORDS;
      // TODO(port): Should we do the actual import in a new process like
      // Windows?
      StartImportingWithUI(GTK_WINDOW(dialog_), items, importer_host_.get(),
                           source_profile, profile_, this, true);
      import_started = true;
    }
  }
  if (!import_started)
    FirstRunDone();
}

void FirstRunDialog::FirstRunDone() {
  // Set preference to show first run bubble and welcome page.
  FirstRun::SetShowFirstRunBubblePref();
  FirstRun::SetShowWelcomePagePref();

  gtk_widget_destroy(dialog_);
  MessageLoop::current()->Quit();
}
<|endoftext|>