<commit_before>#include "GameScene.h"
#include "GameConfigBase.h"
#include "../json/json.h"
#include "msg_proto/web_data.pb.h"
#include "msg_proto/web_game.pb.h"
#include "fxredis.h"
#include "Player.h"
#include "PlayerSession.h"

class RedisSetPlayerTeamId : public IRedisQuery
{
public:
	RedisSetPlayerTeamId(UINT64 qwTeamId, UINT64 qwPlayerId) : m_qwTeamId(qwTeamId), m_qwPlayerId(qwPlayerId) {}
	~RedisSetPlayerTeamId() {}

	virtual int					GetDBId(void) { return 0; }
	virtual void				OnQuery(IRedisConnection *poDBConnection)
	{
		char szQuery[64] = { 0 };
		sprintf(szQuery, "SET %llu_%s %llu", m_qwPlayerId, RedisConstant::szPlayerTeamId, m_qwTeamId);
		poDBConnection->Query(szQuery);
	}
	virtual void OnResult(void) { }
	virtual void Release(void) { }

private:
	UINT64 m_qwTeamId;
	UINT64 m_qwPlayerId;
};

class RedisDelPlayerTeamId : public IRedisQuery
{
public:
	RedisDelPlayerTeamId(UINT64 qwPlayerId) : m_qwPlayerId(qwPlayerId) {}
	~RedisDelPlayerTeamId() {}

	virtual int					GetDBId(void) { return 0; }
	virtual void				OnQuery(IRedisConnection *poDBConnection)
	{
		char szQuery[64] = { 0 };
		sprintf(szQuery, "DEL %llu_%s", m_qwPlayerId, RedisConstant::szPlayerTeamId);
		poDBConnection->Query(szQuery);
	}
	virtual void OnResult(void) { }
	virtual void Release(void) { }

private:
	UINT64 m_qwPlayerId;
};

CGameSceneBase::CGameSceneBase()
{
}

CGameSceneBase::~CGameSceneBase()
{
}

bool CGameSceneBase::Init(unsigned int dwGameType, std::string szRoles, UINT64 qwTeamId)
{
	switch ((GameProto::EGameType)(dwGameType))
	{
		case GameProto::GT_Common:
		{
			if (CreateInstance(new CGameSceneCommon) == false)
			{
				return false;
			}
		}
		break;
		default:
			return false;
	}
	Json::Value jRoles;
	Json::Reader jReader;

	if (!jReader.parse(szRoles, jRoles))
	{
		return false;
	}
	if (!jRoles.isArray())
	{
		return false;
	}
	if (jRoles.size() > MAXCLIENTNUM)
	{
		Assert(0);
	}
	for (int i = 0; i < jRoles.size(); ++i)
	{
		Instance()->m_qwRoles[i] = jRoles[i].asInt64();
		if (Instance()->m_qwRoles[i])
		{
			RedisSetPlayerTeamId oRedisSetPlayerTeamId(qwTeamId, Instance()->m_qwRoles[i]);
			FxRedisGetModule()->QueryDirect(&oRedisSetPlayerTeamId);
		}
	}

	Instance()->m_dwGameType = dwGameType;
	Instance()->m_qwTeamId = qwTeamId;
	Instance()->m_dwGameStartTime = GetTimeHandler()->GetSecond();
	return Instance()->Init();
}

void CGameSceneBase::Run(double fTime)
{
	switch (GetSceneState())
	{
		case GameProto::ESS_None: break;
		case GameProto::ESS_Prepare: { Preparing(fTime); } break;
		case GameProto::ESS_GameReady: { GameReady(fTime); } break;
		case GameProto::ESS_Gaming: { Gaming(fTime); } break;
		case GameProto::ESS_Transact: { Transacting(fTime); } break;
		default: {Assert(0); } break;
	}
}

void CGameSceneBase::Preparing(double fTime)
{
	static UINT32 s_dwNotifyTime = m_dwGameStartTime + 5;

	INT32 dwLeftTime = m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() - GetTimeHandler()->GetSecond();
	if (dwLeftTime < 0)
	{
		ChangeState(GameProto::ESS_GameReady);
		return;
	}
	GameProto::GameNotifyPlayerPrepareTime oNotify;
	oNotify.set_dw_left_time(dwLeftTime);
	if (GetTimeHandler()->GetSecond() >= s_dwNotifyTime)
	{
		NotifyPlayer(oNotify);

		//֪ͨͻƵ 5 ÿһ ǰ 5һ
		if (s_dwNotifyTime >= m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() - 5)
		{
			s_dwNotifyTime += 1;
		}
		else
		{
			s_dwNotifyTime += 5;
		}
	}
}

void CGameSceneBase::GameReady(double fTime)
{
	static UINT32 s_dwNotifyTime = m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() + 1;

	INT32 dwLeftTime = m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() + CGameConfigBase::Instance()->GetGameReadyTime() - GetTimeHandler()->GetSecond();
	if (dwLeftTime < 0)
	{
		ChangeState(GameProto::ESS_Gaming);
		return;
	}
	GameProto::GameNotifyPlayerGameReadyTime oNotify;
	oNotify.set_dw_left_time(dwLeftTime);
	if (GetTimeHandler()->GetSecond() >= s_dwNotifyTime)
	{
		NotifyPlayer(oNotify);
		s_dwNotifyTime += 1;
	}
}

void CGameSceneBase::Gaming(double fTime)
{

}

void CGameSceneBase::Transacting(double fTime)
{

}

void CGameSceneBase::OnPrepare()
{
}

void CGameSceneBase::OnGameReady()
{
}

void CGameSceneBase::OnGameStart()
{
}

void CGameSceneBase::OnTransact()
{
}

void CGameSceneBase::GameEnd()
{
	LogExe(LogLv_Debug, "%s", "game end~~~~~");
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		if (m_qwRoles[i])
		{
			RedisDelPlayerTeamId oRedisDelPlayerTeamId(m_qwRoles[i]);
			FxRedisGetModule()->QueryDirect(&oRedisDelPlayerTeamId);
		}
	}
}

void CGameSceneBase::NotifyPlayer(google::protobuf::Message& refMsg)
{
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		CPlayerBase* pPlayerBase = GetPlayer(m_qwRoles[i]);
		if (!pPlayerBase)
		{
			continue;
		}
		if (!pPlayerBase->GetPlayerSession())
		{
			continue;
		}
		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(refMsg, pBuf, dwBufLen);
		pPlayerBase->GetPlayerSession()->Send(pBuf, dwBufLen);
	}
}

void CGameSceneBase::NotifyPlayerExcept(google::protobuf::Message& refMsg, UINT64 qwPlayerId)
{
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		if (m_qwRoles[i] == qwPlayerId)
		{
			continue;
		}
		CPlayerBase* pPlayerBase = GetPlayer(m_qwRoles[i]);
		if (!pPlayerBase)
		{
			continue;
		}
		if (!pPlayerBase->GetPlayerSession())
		{
			continue;
		}
		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(refMsg, pBuf, dwBufLen);
		pPlayerBase->GetPlayerSession()->Send(pBuf, dwBufLen);
	}
}

void CGameSceneBase::ChangeState(GameProto::EGameSceneState eGameSceneState)
{
	LogExe(LogLv_Info, "game change state : %d", (int)eGameSceneState);
	SetSceneState(eGameSceneState);

	GameProto::GameNotifyPlayerGameState oNotify;
	oNotify.set_state(eGameSceneState);
	NotifyPlayer(oNotify);

	switch (GetSceneState())
	{
		case GameProto::ESS_Prepare: OnPrepare(); break;
		case GameProto::ESS_GameReady: OnGameReady(); break;
		case GameProto::ESS_Gaming: OnGameStart(); break;
		case GameProto::ESS_Transact: OnTransact(); break;
		default:Assert(0); break;
	}
}

//////////////////////////////////////////////////////////////////////////
CGameSceneCommon::CGameSceneCommon()
{
	SetSceneState(GameProto::ESS_None);
}

CGameSceneCommon::~CGameSceneCommon()
{
}

bool CGameSceneCommon::Init()
{
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		if (m_qwRoles[i] != 0)
		{
			m_mapPlayers[m_qwRoles[i]].SetPlayerSession(NULL);
			m_mapPlayers[m_qwRoles[i]].SetPlayerId(m_qwRoles[i]);
		}
	}
	ChangeState(GameProto::ESS_Prepare);
	return true;
}

CPlayerBase* CGameSceneCommon::GetPlayer(UINT64 qwPlayerId)
{
	std::map<UINT64, CCommonPlayer>::iterator it = m_mapPlayers.find(qwPlayerId);
	if (it == m_mapPlayers.end())
	{
		return NULL;
	}
	return &(it->second);
}

void CGameSceneCommon::OnGameStart()
{
	for (std::map<UINT64, CCommonPlayer>::iterator it = m_mapPlayers.begin();
		it != m_mapPlayers.end(); ++it)
	{
		it->second.Init();
	}
}

void CGameSceneCommon::Gaming(double fTime)
{
	for (std::map<UINT64, CCommonPlayer>::iterator it = m_mapPlayers.begin();
		it != m_mapPlayers.end(); ++it)
	{
		it->second.Update(fTime);
	}
}

GameProto::EGameSceneState CGameSceneCommon::GetSceneState()
{
	return m_oSceneInfo.mutable_scene_info()->state();
}

void CGameSceneCommon::FillProtoScene(GameProto::GameNotifyPlayerGameSceneInfo& refInfo)
{
	refInfo.set_dw_game_type(m_dwGameType);
	*(refInfo.mutable_common_scene_info()) = m_oSceneInfo;

	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		GameProto::RoleData* pData = refInfo.add_players();
		if (m_qwRoles[i])
		{
			m_mapPlayers[i].FillPlayerData(*pData);
		}
	}
}

void CGameSceneCommon::SetSceneState(GameProto::EGameSceneState eGameSceneState)
{
	m_oSceneInfo.mutable_scene_info()->set_state(eGameSceneState);
}

<commit_msg>fix<commit_after>#include "GameScene.h"
#include "GameConfigBase.h"
#include "../json/json.h"
#include "msg_proto/web_data.pb.h"
#include "msg_proto/web_game.pb.h"
#include "fxredis.h"
#include "Player.h"
#include "PlayerSession.h"

class RedisSetPlayerTeamId : public IRedisQuery
{
public:
	RedisSetPlayerTeamId(UINT64 qwTeamId, UINT64 qwPlayerId) : m_qwTeamId(qwTeamId), m_qwPlayerId(qwPlayerId) {}
	~RedisSetPlayerTeamId() {}

	virtual int					GetDBId(void) { return 0; }
	virtual void				OnQuery(IRedisConnection *poDBConnection)
	{
		char szQuery[64] = { 0 };
		sprintf(szQuery, "SET %llu_%s %llu", m_qwPlayerId, RedisConstant::szPlayerTeamId, m_qwTeamId);
		poDBConnection->Query(szQuery);
	}
	virtual void OnResult(void) { }
	virtual void Release(void) { }

private:
	UINT64 m_qwTeamId;
	UINT64 m_qwPlayerId;
};

class RedisDelPlayerTeamId : public IRedisQuery
{
public:
	RedisDelPlayerTeamId(UINT64 qwPlayerId) : m_qwPlayerId(qwPlayerId) {}
	~RedisDelPlayerTeamId() {}

	virtual int					GetDBId(void) { return 0; }
	virtual void				OnQuery(IRedisConnection *poDBConnection)
	{
		char szQuery[64] = { 0 };
		sprintf(szQuery, "DEL %llu_%s", m_qwPlayerId, RedisConstant::szPlayerTeamId);
		poDBConnection->Query(szQuery);
	}
	virtual void OnResult(void) { }
	virtual void Release(void) { }

private:
	UINT64 m_qwPlayerId;
};

CGameSceneBase::CGameSceneBase()
{
}

CGameSceneBase::~CGameSceneBase()
{
}

bool CGameSceneBase::Init(unsigned int dwGameType, std::string szRoles, UINT64 qwTeamId)
{
	switch ((GameProto::EGameType)(dwGameType))
	{
		case GameProto::GT_Common:
		{
			if (CreateInstance(new CGameSceneCommon) == false)
			{
				return false;
			}
		}
		break;
		default:
			return false;
	}
	Json::Value jRoles;
	Json::Reader jReader;

	if (!jReader.parse(szRoles, jRoles))
	{
		return false;
	}
	if (!jRoles.isArray())
	{
		return false;
	}
	if (jRoles.size() > MAXCLIENTNUM)
	{
		Assert(0);
	}
	for (int i = 0; i < jRoles.size(); ++i)
	{
		Instance()->m_qwRoles[i] = jRoles[i].asInt64();
		if (Instance()->m_qwRoles[i])
		{
			RedisSetPlayerTeamId oRedisSetPlayerTeamId(qwTeamId, Instance()->m_qwRoles[i]);
			FxRedisGetModule()->QueryDirect(&oRedisSetPlayerTeamId);
		}
	}

	Instance()->m_dwGameType = dwGameType;
	Instance()->m_qwTeamId = qwTeamId;
	Instance()->m_dwGameStartTime = GetTimeHandler()->GetSecond();
	return Instance()->Init();
}

void CGameSceneBase::Run(double fTime)
{
	switch (GetSceneState())
	{
		case GameProto::ESS_None: break;
		case GameProto::ESS_Prepare: { Preparing(fTime); } break;
		case GameProto::ESS_GameReady: { GameReady(fTime); } break;
		case GameProto::ESS_Gaming: { Gaming(fTime); } break;
		case GameProto::ESS_Transact: { Transacting(fTime); } break;
		default: {Assert(0); } break;
	}
}

void CGameSceneBase::Preparing(double fTime)
{
	static UINT32 s_dwNotifyTime = m_dwGameStartTime + 5;

	INT32 dwLeftTime = m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() - GetTimeHandler()->GetSecond();
	if (dwLeftTime < 0)
	{
		ChangeState(GameProto::ESS_GameReady);
		return;
	}
	GameProto::GameNotifyPlayerPrepareTime oNotify;
	oNotify.set_dw_left_time(dwLeftTime);
	if (GetTimeHandler()->GetSecond() >= s_dwNotifyTime)
	{
		NotifyPlayer(oNotify);

		//֪ͨͻƵ 5 ÿһ ǰ 5һ
		if (s_dwNotifyTime >= m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() - 5)
		{
			s_dwNotifyTime += 1;
		}
		else
		{
			s_dwNotifyTime += 5;
		}
	}
}

void CGameSceneBase::GameReady(double fTime)
{
	static UINT32 s_dwNotifyTime = m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() + 1;

	INT32 dwLeftTime = m_dwGameStartTime + CGameConfigBase::Instance()->GetPrepareTime() + CGameConfigBase::Instance()->GetGameReadyTime() - GetTimeHandler()->GetSecond();
	if (dwLeftTime < 0)
	{
		ChangeState(GameProto::ESS_Gaming);
		return;
	}
	GameProto::GameNotifyPlayerGameReadyTime oNotify;
	oNotify.set_dw_left_time(dwLeftTime);
	if (GetTimeHandler()->GetSecond() >= s_dwNotifyTime)
	{
		NotifyPlayer(oNotify);
		s_dwNotifyTime += 1;
	}
}

void CGameSceneBase::Gaming(double fTime)
{

}

void CGameSceneBase::Transacting(double fTime)
{

}

void CGameSceneBase::OnPrepare()
{
}

void CGameSceneBase::OnGameReady()
{
}

void CGameSceneBase::OnGameStart()
{
}

void CGameSceneBase::OnTransact()
{
}

void CGameSceneBase::GameEnd()
{
	LogExe(LogLv_Debug, "%s", "game end~~~~~");
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		if (m_qwRoles[i])
		{
			RedisDelPlayerTeamId oRedisDelPlayerTeamId(m_qwRoles[i]);
			FxRedisGetModule()->QueryDirect(&oRedisDelPlayerTeamId);
		}
	}
}

void CGameSceneBase::NotifyPlayer(google::protobuf::Message& refMsg)
{
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		CPlayerBase* pPlayerBase = GetPlayer(m_qwRoles[i]);
		if (!pPlayerBase)
		{
			continue;
		}
		if (!pPlayerBase->GetPlayerSession())
		{
			continue;
		}
		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(refMsg, pBuf, dwBufLen);
		pPlayerBase->GetPlayerSession()->Send(pBuf, dwBufLen);
	}
}

void CGameSceneBase::NotifyPlayerExcept(google::protobuf::Message& refMsg, UINT64 qwPlayerId)
{
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		if (m_qwRoles[i] == qwPlayerId)
		{
			continue;
		}
		CPlayerBase* pPlayerBase = GetPlayer(m_qwRoles[i]);
		if (!pPlayerBase)
		{
			continue;
		}
		if (!pPlayerBase->GetPlayerSession())
		{
			continue;
		}
		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(refMsg, pBuf, dwBufLen);
		pPlayerBase->GetPlayerSession()->Send(pBuf, dwBufLen);
	}
}

void CGameSceneBase::ChangeState(GameProto::EGameSceneState eGameSceneState)
{
	LogExe(LogLv_Info, "game change state : %d", (int)eGameSceneState);
	SetSceneState(eGameSceneState);

	GameProto::GameNotifyPlayerGameState oNotify;
	oNotify.set_state(eGameSceneState);
	NotifyPlayer(oNotify);

	switch (GetSceneState())
	{
		case GameProto::ESS_Prepare: OnPrepare(); break;
		case GameProto::ESS_GameReady: OnGameReady(); break;
		case GameProto::ESS_Gaming: OnGameStart(); break;
		case GameProto::ESS_Transact: OnTransact(); break;
		default:Assert(0); break;
	}
}

//////////////////////////////////////////////////////////////////////////
CGameSceneCommon::CGameSceneCommon()
{
	SetSceneState(GameProto::ESS_None);
}

CGameSceneCommon::~CGameSceneCommon()
{
}

bool CGameSceneCommon::Init()
{
	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		if (m_qwRoles[i] != 0)
		{
			m_mapPlayers[m_qwRoles[i]].SetPlayerSession(NULL);
			m_mapPlayers[m_qwRoles[i]].SetPlayerId(m_qwRoles[i]);
		}
	}
	ChangeState(GameProto::ESS_Prepare);
	return true;
}

CPlayerBase* CGameSceneCommon::GetPlayer(UINT64 qwPlayerId)
{
	std::map<UINT64, CCommonPlayer>::iterator it = m_mapPlayers.find(qwPlayerId);
	if (it == m_mapPlayers.end())
	{
		return NULL;
	}
	return &(it->second);
}

void CGameSceneCommon::OnGameStart()
{
	for (std::map<UINT64, CCommonPlayer>::iterator it = m_mapPlayers.begin();
		it != m_mapPlayers.end(); ++it)
	{
		it->second.Init();
	}
}

void CGameSceneCommon::Gaming(double fTime)
{
	for (std::map<UINT64, CCommonPlayer>::iterator it = m_mapPlayers.begin();
		it != m_mapPlayers.end(); ++it)
	{
		it->second.Update(fTime);
	}
}

GameProto::EGameSceneState CGameSceneCommon::GetSceneState()
{
	return m_oSceneInfo.mutable_scene_info()->state();
}

void CGameSceneCommon::FillProtoScene(GameProto::GameNotifyPlayerGameSceneInfo& refInfo)
{
	refInfo.set_dw_game_type(m_dwGameType);
	*(refInfo.mutable_common_scene_info()) = m_oSceneInfo;

	for (int i = 0; i < MAXCLIENTNUM; ++i)
	{
		GameProto::RoleData* pData = refInfo.add_players();
		if (m_qwRoles[i] != 0)
		{
			m_mapPlayers[m_qwRoles[i]].FillPlayerData(*pData);
		}
	}
}

void CGameSceneCommon::SetSceneState(GameProto::EGameSceneState eGameSceneState)
{
	m_oSceneInfo.mutable_scene_info()->set_state(eGameSceneState);
}

<|endoftext|>


<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "Dialog.h"

#include "../../3RVX/Logger.h"
#include "../UITranslator.h"
#include "Control.h"

Dialog::Dialog() {

}

Dialog::Dialog(HWND parent, LPCWSTR dlgTemplate) :
_parent(parent) {
    _dlgHwnd = CreateDialogParam(
        NULL,
        dlgTemplate,
        parent,
        StaticDialogProc,
        (LPARAM) this);

    if (_dlgHwnd == NULL) {
        Logger::LogLastError();
    }
}

void Dialog::Show() {
    DialogBoxParam(NULL, _template, _parent, StaticDialogProc, (LPARAM) this);
    UITranslator::TranslateWindowText(_dlgHwnd);
}

void Dialog::AddControl(Control *control) {
    if (control == nullptr) {
        return;
    }

    int id = control->ID();
    _controlMap[id] = control;
}

HWND Dialog::DialogHandle() {
    return _dlgHwnd;
}

HWND Dialog::ParentHandle() {
    return _parent;
}

INT_PTR Dialog::StaticDialogProc(
        HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    Dialog *dlg;

    if (uMsg == WM_INITDIALOG) {
        dlg = (Dialog *) lParam;
        SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR) dlg);
    } else {
        dlg = (Dialog *) GetWindowLongPtr(hwndDlg, DWLP_USER);
        if (!dlg) {
            return FALSE;
        }
    }

    return dlg->DialogProc(hwndDlg, uMsg, wParam, lParam);
}

INT_PTR Dialog::DialogProc(HWND hwndDlg, UINT uMsg,
        WPARAM wParam, LPARAM lParam) {

    unsigned short nCode, ctrlId;

    switch (uMsg) {
    case WM_INITDIALOG:
        _dlgHwnd = hwndDlg;
        return FALSE;

    case WM_COMMAND:
        nCode = HIWORD(wParam);
        ctrlId = LOWORD(wParam);
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Command(nCode);
        } else {
            return FALSE;
        }

    case WM_NOTIFY: {
        NMHDR *nHdr = (NMHDR *) lParam;
        ctrlId = nHdr->idFrom;
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Notification(nHdr);
        } else {
            return FALSE;
        }
    }

    case WM_HSCROLL:
    case WM_VSCROLL: {
        WORD request = LOWORD(wParam);
        WORD position = HIWORD(wParam);
        HWND scrollHandle = (HWND) lParam;
        ctrlId = GetDlgCtrlID(scrollHandle);

        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Scroll(
                (uMsg == WM_HSCROLL), request, position);
        } else {
            return FALSE;
        }
    }
    }

    return FALSE;
}
<commit_msg>Comment out old dialog constructor for now<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "Dialog.h"

#include "../../3RVX/Logger.h"
#include "../UITranslator.h"
#include "Control.h"

Dialog::Dialog() {

}

Dialog::Dialog(HWND parent, LPCWSTR dlgTemplate) :
_parent(parent),
_template(dlgTemplate) {
//    _dlgHwnd = CreateDialogParam(
//        NULL,
//        dlgTemplate,
//        parent,
//        StaticDialogProc,
//        (LPARAM) this);

//    if (_dlgHwnd == NULL) {
//        Logger::LogLastError();
//    }

//    UITranslator::TranslateWindowText(_dlgHwnd);
}

void Dialog::Show() {
    DialogBoxParam(NULL, _template, _parent, StaticDialogProc, (LPARAM) this);
    UITranslator::TranslateWindowText(_dlgHwnd);
}

void Dialog::AddControl(Control *control) {
    if (control == nullptr) {
        return;
    }

    int id = control->ID();
    _controlMap[id] = control;
}

HWND Dialog::DialogHandle() {
    return _dlgHwnd;
}

HWND Dialog::ParentHandle() {
    return _parent;
}

INT_PTR Dialog::StaticDialogProc(
        HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    Dialog *dlg;

    if (uMsg == WM_INITDIALOG) {
        dlg = (Dialog *) lParam;
        SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR) dlg);
    } else {
        dlg = (Dialog *) GetWindowLongPtr(hwndDlg, DWLP_USER);
        if (!dlg) {
            return FALSE;
        }
    }

    return dlg->DialogProc(hwndDlg, uMsg, wParam, lParam);
}

INT_PTR Dialog::DialogProc(HWND hwndDlg, UINT uMsg,
        WPARAM wParam, LPARAM lParam) {

    unsigned short nCode, ctrlId;

    switch (uMsg) {
    case WM_INITDIALOG:
        _dlgHwnd = hwndDlg;
        return FALSE;

    case WM_COMMAND:
        nCode = HIWORD(wParam);
        ctrlId = LOWORD(wParam);
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Command(nCode);
        } else {
            return FALSE;
        }

    case WM_NOTIFY: {
        NMHDR *nHdr = (NMHDR *) lParam;
        ctrlId = nHdr->idFrom;
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Notification(nHdr);
        } else {
            return FALSE;
        }
    }

    case WM_HSCROLL:
    case WM_VSCROLL: {
        WORD request = LOWORD(wParam);
        WORD position = HIWORD(wParam);
        HWND scrollHandle = (HWND) lParam;
        ctrlId = GetDlgCtrlID(scrollHandle);

        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Scroll(
                (uMsg == WM_HSCROLL), request, position);
        } else {
            return FALSE;
        }
    }
    }

    return FALSE;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */
#ifndef INCLUDED_OSL_SOCKET_HXX
#define INCLUDED_OSL_SOCKET_HXX

#include <osl/socket_decl.hxx>

namespace osl
{

    inline SocketAddr::SocketAddr()
        : m_handle( osl_createEmptySocketAddr( osl_Socket_FamilyInet ) )
    {}

    inline SocketAddr::SocketAddr(const SocketAddr& Addr)
        : m_handle( osl_copySocketAddr( Addr.m_handle ) )
    {
    }

    inline SocketAddr::SocketAddr(oslSocketAddr Addr)
        : m_handle( osl_copySocketAddr( Addr ) )
    {
    }

    inline SocketAddr::SocketAddr(oslSocketAddr Addr, __osl_socket_NoCopy )
        : m_handle( Addr )
    {
    }

    inline SocketAddr::SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort)
        : m_handle( osl_createInetSocketAddr( strAddrOrHostName.pData, nPort ) )
    {
        if(! m_handle )
        {
            m_handle = osl_resolveHostname(strAddrOrHostName.pData);

            // host found?
            if(m_handle)
            {
                osl_setInetPortOfSocketAddr(m_handle, nPort);
            }
            else
            {
                osl_destroySocketAddr( m_handle );
                m_handle = 0;
            }
        }
    }

    inline SocketAddr::~SocketAddr()
    {
        if( m_handle )
            osl_destroySocketAddr( m_handle );
    }

    inline ::rtl::OUString SocketAddr::getHostname( oslSocketResult *pResult ) const
    {
        ::rtl::OUString hostname;
        oslSocketResult result = osl_getHostnameOfSocketAddr( m_handle, &(hostname.pData) );
        if( pResult )
            *pResult = result;
        return hostname;
    }

    inline sal_Int32 SAL_CALL SocketAddr::getPort() const
    {
        return osl_getInetPortOfSocketAddr(m_handle);
    }

    inline bool SAL_CALL SocketAddr::setPort( sal_Int32 nPort )
    {
        return osl_setInetPortOfSocketAddr(m_handle, nPort );
    }

    inline bool SAL_CALL SocketAddr::setHostname( const ::rtl::OUString &sDottedIpOrHostname )
    {
        *this = SocketAddr( sDottedIpOrHostname , getPort() );
        return is();
    }

    inline bool SAL_CALL SocketAddr::setAddr( const ::rtl::ByteSequence & address )
    {
        return osl_setAddrOfSocketAddr( m_handle, address.getHandle() )
            == osl_Socket_Ok;
    }

    inline ::rtl::ByteSequence SAL_CALL SocketAddr::getAddr( oslSocketResult *pResult ) const
    {
        ::rtl::ByteSequence sequence;
        oslSocketResult result = osl_getAddrOfSocketAddr( m_handle,(sal_Sequence **) &sequence );
        if( pResult )
            *pResult = result;
        return sequence;
    }

    inline SocketAddr & SAL_CALL SocketAddr::operator= (oslSocketAddr Addr)
    {
        oslSocketAddr pNewAddr = osl_copySocketAddr( Addr );
        if( m_handle )
            osl_destroySocketAddr( m_handle );
        m_handle = pNewAddr;
        return *this;
    }

    inline SocketAddr & SAL_CALL SocketAddr::operator= (const SocketAddr& Addr)
    {
        *this = (Addr.getHandle());
        return *this;
    }

    inline SocketAddr & SAL_CALL SocketAddr::assign( oslSocketAddr Addr, __osl_socket_NoCopy )
    {
        if( m_handle )
            osl_destroySocketAddr( m_handle );
        m_handle = Addr;
        return *this;
    }

    inline bool SAL_CALL SocketAddr::operator== (oslSocketAddr Addr) const
    {
        return osl_isEqualSocketAddr( m_handle, Addr );
    }

    inline oslSocketAddr SocketAddr::getHandle() const
    {
        return m_handle;
    }

    inline bool SocketAddr::is() const
    {
        return m_handle != 0;
    }

    // (static method)______________________________________________________________
    inline ::rtl::OUString SAL_CALL SocketAddr::getLocalHostname( oslSocketResult *pResult )
    {
        ::rtl::OUString hostname;
        oslSocketResult result = osl_getLocalHostname( &(hostname.pData) );
        if(pResult )
            *pResult = result;
        return hostname;
    }

    // (static method)______________________________________________________________
    inline void SAL_CALL SocketAddr::resolveHostname(
        const ::rtl::OUString & strHostName, SocketAddr &Addr)
    {
        Addr = SocketAddr( osl_resolveHostname( strHostName.pData ) , SAL_NO_COPY );
    }

    // (static method)______________________________________________________________
    inline sal_Int32 SAL_CALL SocketAddr::getServicePort(
            const ::rtl::OUString& strServiceName,
            const ::rtl::OUString & strProtocolName )
    {
        return osl_getServicePort( strServiceName.pData, strProtocolName.pData );
    }

    inline Socket::Socket(oslSocketType Type,
                          oslAddrFamily Family,
                          oslProtocol   Protocol)
        : m_handle( osl_createSocket(Family, Type, Protocol) )
    {}

    inline Socket::Socket( oslSocket socketHandle, __sal_NoAcquire )
        : m_handle( socketHandle )
    {}

    inline Socket::Socket( oslSocket socketHandle )
        : m_handle( socketHandle )
    {
        osl_acquireSocket( m_handle );
    }

    inline Socket::Socket( const Socket & socket )
        : m_handle( socket.getHandle() )
    {
        osl_acquireSocket( m_handle );
    }

    inline Socket::~Socket()
    {
        osl_releaseSocket( m_handle );
    }

    inline Socket& Socket::operator= ( oslSocket socketHandle)
    {
        osl_acquireSocket( socketHandle );
        osl_releaseSocket( m_handle );
        m_handle = socketHandle;
        return *this;
    }

    inline Socket&  Socket::operator= (const Socket& sock)
    {
        return (*this) = sock.getHandle();
    }

    inline bool Socket::operator==( const Socket& rSocket ) const
    {
        return m_handle == rSocket.getHandle();
    }

    inline bool Socket::operator==( const oslSocket socketHandle ) const
    {
        return m_handle == socketHandle;
    }

    inline void Socket::shutdown( oslSocketDirection Direction )
    {
        osl_shutdownSocket( m_handle , Direction );
    }

    inline void Socket::close()
    {
        osl_closeSocket( m_handle );
    }

    inline void Socket::getLocalAddr( SocketAddr & addr) const
    {
        addr.assign( osl_getLocalAddrOfSocket( m_handle ) , SAL_NO_COPY );
    }

    inline sal_Int32 Socket::getLocalPort() const
    {
        SocketAddr addr( 0 );
        getLocalAddr( addr );
        return addr.getPort();
    }

    inline ::rtl::OUString Socket::getLocalHost() const
    {
        SocketAddr addr( 0 );
        getLocalAddr( addr );
        return addr.getHostname();
    }

    inline void Socket::getPeerAddr( SocketAddr &addr ) const
    {
        addr.assign( osl_getPeerAddrOfSocket( m_handle ), SAL_NO_COPY );
    }

    inline sal_Int32 Socket::getPeerPort() const
    {
        SocketAddr addr( 0 );
        getPeerAddr( addr );
        return addr.getPort();
    }

    inline ::rtl::OUString Socket::getPeerHost() const
    {
        SocketAddr addr( 0 );
        getPeerAddr( addr );
        return addr.getHostname();
    }

    inline bool Socket::bind(const SocketAddr& LocalInterface)
    {
        return osl_bindAddrToSocket( m_handle , LocalInterface.getHandle() );
    }

    inline bool Socket::isRecvReady(const TimeValue *pTimeout ) const
    {
        return osl_isReceiveReady( m_handle , pTimeout );
    }

    inline bool Socket::isSendReady(const TimeValue *pTimeout ) const
    {
        return osl_isSendReady( m_handle, pTimeout );
    }

    inline bool Socket::isExceptionPending(const TimeValue *pTimeout ) const
    {
        return osl_isExceptionPending( m_handle, pTimeout );
    }

    inline oslSocketType Socket::getType() const
    {
        return osl_getSocketType( m_handle );
    }

    inline sal_Int32  Socket::getOption(
        oslSocketOption Option,
        void* pBuffer,
        sal_uInt32 BufferLen,
        oslSocketOptionLevel Level) const
    {
        return osl_getSocketOption( m_handle, Level, Option, pBuffer , BufferLen );
    }

    inline bool Socket::setOption(  oslSocketOption Option,
                                        void* pBuffer,
                                        sal_uInt32 BufferLen,
                                        oslSocketOptionLevel Level ) const
    {
        return osl_setSocketOption( m_handle, Level, Option , pBuffer, BufferLen );
    }

    inline bool Socket::setOption( oslSocketOption option, sal_Int32 nValue  )
    {
        return setOption( option, &nValue, sizeof( nValue ) );
    }

    inline sal_Int32 Socket::getOption( oslSocketOption option ) const
    {
        sal_Int32 n;
        getOption( option, &n, sizeof( n ) );
        return n;
    }

    inline bool Socket::enableNonBlockingMode( bool bNonBlockingMode)
    {
        return osl_enableNonBlockingMode( m_handle , bNonBlockingMode );
    }

    inline bool Socket::isNonBlockingMode() const
    {
        return osl_isNonBlockingMode( m_handle );
    }

    inline void SAL_CALL Socket::clearError() const
    {
        sal_Int32 err = 0;
        getOption(osl_Socket_OptionError, &err, sizeof(err));
    }

    inline oslSocketError Socket::getError() const
    {
        return osl_getLastSocketError( m_handle );
    }

    inline ::rtl::OUString Socket::getErrorAsString( ) const
    {
        ::rtl::OUString error;
        osl_getLastSocketErrorDescription( m_handle, &(error.pData) );
        return error;
    }

    inline oslSocket Socket::getHandle() const
    {
        return m_handle;
    }

    inline StreamSocket::StreamSocket(oslAddrFamily Family,
                                      oslProtocol Protocol,
                                      oslSocketType Type )
        : Socket( Type, Family, Protocol )
    {}

    inline StreamSocket::StreamSocket( oslSocket socketHandle, __sal_NoAcquire noacquire )
        : Socket( socketHandle, noacquire )
    {}

    inline StreamSocket::StreamSocket( oslSocket socketHandle )
        : Socket( socketHandle )
    {}

    inline StreamSocket::StreamSocket( const StreamSocket & socket )
        : Socket( socket )
    {}

    inline sal_Int32 StreamSocket::read(void* pBuffer, sal_uInt32 n)
    {
        return osl_readSocket( m_handle, pBuffer, n );
    }

    inline sal_Int32 StreamSocket::write(const void* pBuffer, sal_uInt32 n)
    {
        return osl_writeSocket( m_handle, pBuffer, n );
    }

    inline sal_Int32 StreamSocket::recv(void* pBuffer,
                                        sal_uInt32 BytesToRead,
                                        oslSocketMsgFlag Flag)
    {
        return osl_receiveSocket( m_handle, pBuffer,BytesToRead, Flag );
    }

    inline sal_Int32 StreamSocket::send(const void* pBuffer,
                                        sal_uInt32 BytesToSend,
                                        oslSocketMsgFlag Flag)
    {
        return osl_sendSocket( m_handle, pBuffer, BytesToSend, Flag );
    }

      inline ConnectorSocket::ConnectorSocket(oslAddrFamily Family,
                                            oslProtocol Protocol,
                                            oslSocketType   Type)
        : StreamSocket( Family, Protocol ,Type )
    {}

    inline oslSocketResult ConnectorSocket::connect( const SocketAddr& TargetHost,
                                                     const TimeValue* pTimeout )
    {
        return osl_connectSocketTo( m_handle , TargetHost.getHandle(), pTimeout );
    }

    inline AcceptorSocket::AcceptorSocket(oslAddrFamily Family ,
                                          oslProtocol   Protocol ,
                                          oslSocketType Type )
        : Socket( Type, Family, Protocol )
    {}

    inline bool AcceptorSocket::listen(sal_Int32 MaxPendingConnections)
    {
        return osl_listenOnSocket( m_handle, MaxPendingConnections );
    }

    inline oslSocketResult AcceptorSocket::acceptConnection( StreamSocket& Connection)
    {
        oslSocket o = osl_acceptConnectionOnSocket( m_handle, 0 );
        oslSocketResult status = osl_Socket_Ok;
        if( o )
        {
            Connection = StreamSocket( o , SAL_NO_ACQUIRE );
        }
        else
        {
            Connection = StreamSocket();
            status = osl_Socket_Error;
        }
        return status;
    }

    inline oslSocketResult AcceptorSocket::acceptConnection(
        StreamSocket&   Connection, SocketAddr & PeerAddr)
    {
        // TODO change in/OUT parameter
        oslSocket o = osl_acceptConnectionOnSocket( m_handle, (oslSocketAddr *)&PeerAddr );
        oslSocketResult status = osl_Socket_Ok;
        if( o )
        {
            Connection = StreamSocket( o , SAL_NO_ACQUIRE );
        }
        else
        {
            Connection = StreamSocket();
            status = osl_Socket_Error;
        }
        return status;
    }

    inline DatagramSocket::DatagramSocket(oslAddrFamily Family,
                                          oslProtocol   Protocol,
                                          oslSocketType Type)
        : Socket( Type, Family, Protocol )
    {}

    inline sal_Int32 DatagramSocket::recvFrom(void*  pBuffer,
                                              sal_uInt32 BufferSize,
                                              SocketAddr* pSenderAddr,
                                              oslSocketMsgFlag Flag )
    {
        sal_Int32 nByteRead;
        if( pSenderAddr )
        {
            // TODO : correct the out-parameter pSenderAddr outparameter
              nByteRead = osl_receiveFromSocket( m_handle, pSenderAddr->getHandle() , pBuffer,
                                                 BufferSize, Flag);
//              nByteRead = osl_receiveFromSocket( m_handle, *(oslSocketAddr**) &pSenderAddr , pBuffer,
//                                                 BufferSize, Flag);
        }
        else
        {
            nByteRead = osl_receiveFromSocket( m_handle, 0 , pBuffer , BufferSize ,  Flag );
        }
        return nByteRead;
    }

    inline sal_Int32  DatagramSocket::sendTo( const SocketAddr& ReceiverAddr,
                                              const void* pBuffer,
                                              sal_uInt32 BufferSize,
                                              oslSocketMsgFlag Flag )
    {
        return osl_sendToSocket( m_handle, ReceiverAddr.getHandle(), pBuffer, BufferSize, Flag );
    }
}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>loplugin:cstylecast, involving pointer to incomplete type<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */
#ifndef INCLUDED_OSL_SOCKET_HXX
#define INCLUDED_OSL_SOCKET_HXX

#include <osl/socket_decl.hxx>

namespace osl
{

    inline SocketAddr::SocketAddr()
        : m_handle( osl_createEmptySocketAddr( osl_Socket_FamilyInet ) )
    {}

    inline SocketAddr::SocketAddr(const SocketAddr& Addr)
        : m_handle( osl_copySocketAddr( Addr.m_handle ) )
    {
    }

    inline SocketAddr::SocketAddr(oslSocketAddr Addr)
        : m_handle( osl_copySocketAddr( Addr ) )
    {
    }

    inline SocketAddr::SocketAddr(oslSocketAddr Addr, __osl_socket_NoCopy )
        : m_handle( Addr )
    {
    }

    inline SocketAddr::SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort)
        : m_handle( osl_createInetSocketAddr( strAddrOrHostName.pData, nPort ) )
    {
        if(! m_handle )
        {
            m_handle = osl_resolveHostname(strAddrOrHostName.pData);

            // host found?
            if(m_handle)
            {
                osl_setInetPortOfSocketAddr(m_handle, nPort);
            }
            else
            {
                osl_destroySocketAddr( m_handle );
                m_handle = 0;
            }
        }
    }

    inline SocketAddr::~SocketAddr()
    {
        if( m_handle )
            osl_destroySocketAddr( m_handle );
    }

    inline ::rtl::OUString SocketAddr::getHostname( oslSocketResult *pResult ) const
    {
        ::rtl::OUString hostname;
        oslSocketResult result = osl_getHostnameOfSocketAddr( m_handle, &(hostname.pData) );
        if( pResult )
            *pResult = result;
        return hostname;
    }

    inline sal_Int32 SAL_CALL SocketAddr::getPort() const
    {
        return osl_getInetPortOfSocketAddr(m_handle);
    }

    inline bool SAL_CALL SocketAddr::setPort( sal_Int32 nPort )
    {
        return osl_setInetPortOfSocketAddr(m_handle, nPort );
    }

    inline bool SAL_CALL SocketAddr::setHostname( const ::rtl::OUString &sDottedIpOrHostname )
    {
        *this = SocketAddr( sDottedIpOrHostname , getPort() );
        return is();
    }

    inline bool SAL_CALL SocketAddr::setAddr( const ::rtl::ByteSequence & address )
    {
        return osl_setAddrOfSocketAddr( m_handle, address.getHandle() )
            == osl_Socket_Ok;
    }

    inline ::rtl::ByteSequence SAL_CALL SocketAddr::getAddr( oslSocketResult *pResult ) const
    {
        ::rtl::ByteSequence sequence;
        oslSocketResult result = osl_getAddrOfSocketAddr( m_handle,(sal_Sequence **) &sequence );
        if( pResult )
            *pResult = result;
        return sequence;
    }

    inline SocketAddr & SAL_CALL SocketAddr::operator= (oslSocketAddr Addr)
    {
        oslSocketAddr pNewAddr = osl_copySocketAddr( Addr );
        if( m_handle )
            osl_destroySocketAddr( m_handle );
        m_handle = pNewAddr;
        return *this;
    }

    inline SocketAddr & SAL_CALL SocketAddr::operator= (const SocketAddr& Addr)
    {
        *this = (Addr.getHandle());
        return *this;
    }

    inline SocketAddr & SAL_CALL SocketAddr::assign( oslSocketAddr Addr, __osl_socket_NoCopy )
    {
        if( m_handle )
            osl_destroySocketAddr( m_handle );
        m_handle = Addr;
        return *this;
    }

    inline bool SAL_CALL SocketAddr::operator== (oslSocketAddr Addr) const
    {
        return osl_isEqualSocketAddr( m_handle, Addr );
    }

    inline oslSocketAddr SocketAddr::getHandle() const
    {
        return m_handle;
    }

    inline bool SocketAddr::is() const
    {
        return m_handle != 0;
    }

    // (static method)______________________________________________________________
    inline ::rtl::OUString SAL_CALL SocketAddr::getLocalHostname( oslSocketResult *pResult )
    {
        ::rtl::OUString hostname;
        oslSocketResult result = osl_getLocalHostname( &(hostname.pData) );
        if(pResult )
            *pResult = result;
        return hostname;
    }

    // (static method)______________________________________________________________
    inline void SAL_CALL SocketAddr::resolveHostname(
        const ::rtl::OUString & strHostName, SocketAddr &Addr)
    {
        Addr = SocketAddr( osl_resolveHostname( strHostName.pData ) , SAL_NO_COPY );
    }

    // (static method)______________________________________________________________
    inline sal_Int32 SAL_CALL SocketAddr::getServicePort(
            const ::rtl::OUString& strServiceName,
            const ::rtl::OUString & strProtocolName )
    {
        return osl_getServicePort( strServiceName.pData, strProtocolName.pData );
    }

    inline Socket::Socket(oslSocketType Type,
                          oslAddrFamily Family,
                          oslProtocol   Protocol)
        : m_handle( osl_createSocket(Family, Type, Protocol) )
    {}

    inline Socket::Socket( oslSocket socketHandle, __sal_NoAcquire )
        : m_handle( socketHandle )
    {}

    inline Socket::Socket( oslSocket socketHandle )
        : m_handle( socketHandle )
    {
        osl_acquireSocket( m_handle );
    }

    inline Socket::Socket( const Socket & socket )
        : m_handle( socket.getHandle() )
    {
        osl_acquireSocket( m_handle );
    }

    inline Socket::~Socket()
    {
        osl_releaseSocket( m_handle );
    }

    inline Socket& Socket::operator= ( oslSocket socketHandle)
    {
        osl_acquireSocket( socketHandle );
        osl_releaseSocket( m_handle );
        m_handle = socketHandle;
        return *this;
    }

    inline Socket&  Socket::operator= (const Socket& sock)
    {
        return (*this) = sock.getHandle();
    }

    inline bool Socket::operator==( const Socket& rSocket ) const
    {
        return m_handle == rSocket.getHandle();
    }

    inline bool Socket::operator==( const oslSocket socketHandle ) const
    {
        return m_handle == socketHandle;
    }

    inline void Socket::shutdown( oslSocketDirection Direction )
    {
        osl_shutdownSocket( m_handle , Direction );
    }

    inline void Socket::close()
    {
        osl_closeSocket( m_handle );
    }

    inline void Socket::getLocalAddr( SocketAddr & addr) const
    {
        addr.assign( osl_getLocalAddrOfSocket( m_handle ) , SAL_NO_COPY );
    }

    inline sal_Int32 Socket::getLocalPort() const
    {
        SocketAddr addr( 0 );
        getLocalAddr( addr );
        return addr.getPort();
    }

    inline ::rtl::OUString Socket::getLocalHost() const
    {
        SocketAddr addr( 0 );
        getLocalAddr( addr );
        return addr.getHostname();
    }

    inline void Socket::getPeerAddr( SocketAddr &addr ) const
    {
        addr.assign( osl_getPeerAddrOfSocket( m_handle ), SAL_NO_COPY );
    }

    inline sal_Int32 Socket::getPeerPort() const
    {
        SocketAddr addr( 0 );
        getPeerAddr( addr );
        return addr.getPort();
    }

    inline ::rtl::OUString Socket::getPeerHost() const
    {
        SocketAddr addr( 0 );
        getPeerAddr( addr );
        return addr.getHostname();
    }

    inline bool Socket::bind(const SocketAddr& LocalInterface)
    {
        return osl_bindAddrToSocket( m_handle , LocalInterface.getHandle() );
    }

    inline bool Socket::isRecvReady(const TimeValue *pTimeout ) const
    {
        return osl_isReceiveReady( m_handle , pTimeout );
    }

    inline bool Socket::isSendReady(const TimeValue *pTimeout ) const
    {
        return osl_isSendReady( m_handle, pTimeout );
    }

    inline bool Socket::isExceptionPending(const TimeValue *pTimeout ) const
    {
        return osl_isExceptionPending( m_handle, pTimeout );
    }

    inline oslSocketType Socket::getType() const
    {
        return osl_getSocketType( m_handle );
    }

    inline sal_Int32  Socket::getOption(
        oslSocketOption Option,
        void* pBuffer,
        sal_uInt32 BufferLen,
        oslSocketOptionLevel Level) const
    {
        return osl_getSocketOption( m_handle, Level, Option, pBuffer , BufferLen );
    }

    inline bool Socket::setOption(  oslSocketOption Option,
                                        void* pBuffer,
                                        sal_uInt32 BufferLen,
                                        oslSocketOptionLevel Level ) const
    {
        return osl_setSocketOption( m_handle, Level, Option , pBuffer, BufferLen );
    }

    inline bool Socket::setOption( oslSocketOption option, sal_Int32 nValue  )
    {
        return setOption( option, &nValue, sizeof( nValue ) );
    }

    inline sal_Int32 Socket::getOption( oslSocketOption option ) const
    {
        sal_Int32 n;
        getOption( option, &n, sizeof( n ) );
        return n;
    }

    inline bool Socket::enableNonBlockingMode( bool bNonBlockingMode)
    {
        return osl_enableNonBlockingMode( m_handle , bNonBlockingMode );
    }

    inline bool Socket::isNonBlockingMode() const
    {
        return osl_isNonBlockingMode( m_handle );
    }

    inline void SAL_CALL Socket::clearError() const
    {
        sal_Int32 err = 0;
        getOption(osl_Socket_OptionError, &err, sizeof(err));
    }

    inline oslSocketError Socket::getError() const
    {
        return osl_getLastSocketError( m_handle );
    }

    inline ::rtl::OUString Socket::getErrorAsString( ) const
    {
        ::rtl::OUString error;
        osl_getLastSocketErrorDescription( m_handle, &(error.pData) );
        return error;
    }

    inline oslSocket Socket::getHandle() const
    {
        return m_handle;
    }

    inline StreamSocket::StreamSocket(oslAddrFamily Family,
                                      oslProtocol Protocol,
                                      oslSocketType Type )
        : Socket( Type, Family, Protocol )
    {}

    inline StreamSocket::StreamSocket( oslSocket socketHandle, __sal_NoAcquire noacquire )
        : Socket( socketHandle, noacquire )
    {}

    inline StreamSocket::StreamSocket( oslSocket socketHandle )
        : Socket( socketHandle )
    {}

    inline StreamSocket::StreamSocket( const StreamSocket & socket )
        : Socket( socket )
    {}

    inline sal_Int32 StreamSocket::read(void* pBuffer, sal_uInt32 n)
    {
        return osl_readSocket( m_handle, pBuffer, n );
    }

    inline sal_Int32 StreamSocket::write(const void* pBuffer, sal_uInt32 n)
    {
        return osl_writeSocket( m_handle, pBuffer, n );
    }

    inline sal_Int32 StreamSocket::recv(void* pBuffer,
                                        sal_uInt32 BytesToRead,
                                        oslSocketMsgFlag Flag)
    {
        return osl_receiveSocket( m_handle, pBuffer,BytesToRead, Flag );
    }

    inline sal_Int32 StreamSocket::send(const void* pBuffer,
                                        sal_uInt32 BytesToSend,
                                        oslSocketMsgFlag Flag)
    {
        return osl_sendSocket( m_handle, pBuffer, BytesToSend, Flag );
    }

      inline ConnectorSocket::ConnectorSocket(oslAddrFamily Family,
                                            oslProtocol Protocol,
                                            oslSocketType   Type)
        : StreamSocket( Family, Protocol ,Type )
    {}

    inline oslSocketResult ConnectorSocket::connect( const SocketAddr& TargetHost,
                                                     const TimeValue* pTimeout )
    {
        return osl_connectSocketTo( m_handle , TargetHost.getHandle(), pTimeout );
    }

    inline AcceptorSocket::AcceptorSocket(oslAddrFamily Family ,
                                          oslProtocol   Protocol ,
                                          oslSocketType Type )
        : Socket( Type, Family, Protocol )
    {}

    inline bool AcceptorSocket::listen(sal_Int32 MaxPendingConnections)
    {
        return osl_listenOnSocket( m_handle, MaxPendingConnections );
    }

    inline oslSocketResult AcceptorSocket::acceptConnection( StreamSocket& Connection)
    {
        oslSocket o = osl_acceptConnectionOnSocket( m_handle, 0 );
        oslSocketResult status = osl_Socket_Ok;
        if( o )
        {
            Connection = StreamSocket( o , SAL_NO_ACQUIRE );
        }
        else
        {
            Connection = StreamSocket();
            status = osl_Socket_Error;
        }
        return status;
    }

    inline oslSocketResult AcceptorSocket::acceptConnection(
        StreamSocket&   Connection, SocketAddr & PeerAddr)
    {
        // TODO change in/OUT parameter
        oslSocket o = osl_acceptConnectionOnSocket(
            m_handle, reinterpret_cast<oslSocketAddr *>(&PeerAddr));
        oslSocketResult status = osl_Socket_Ok;
        if( o )
        {
            Connection = StreamSocket( o , SAL_NO_ACQUIRE );
        }
        else
        {
            Connection = StreamSocket();
            status = osl_Socket_Error;
        }
        return status;
    }

    inline DatagramSocket::DatagramSocket(oslAddrFamily Family,
                                          oslProtocol   Protocol,
                                          oslSocketType Type)
        : Socket( Type, Family, Protocol )
    {}

    inline sal_Int32 DatagramSocket::recvFrom(void*  pBuffer,
                                              sal_uInt32 BufferSize,
                                              SocketAddr* pSenderAddr,
                                              oslSocketMsgFlag Flag )
    {
        sal_Int32 nByteRead;
        if( pSenderAddr )
        {
            // TODO : correct the out-parameter pSenderAddr outparameter
              nByteRead = osl_receiveFromSocket( m_handle, pSenderAddr->getHandle() , pBuffer,
                                                 BufferSize, Flag);
//              nByteRead = osl_receiveFromSocket( m_handle, *(oslSocketAddr**) &pSenderAddr , pBuffer,
//                                                 BufferSize, Flag);
        }
        else
        {
            nByteRead = osl_receiveFromSocket( m_handle, 0 , pBuffer , BufferSize ,  Flag );
        }
        return nByteRead;
    }

    inline sal_Int32  DatagramSocket::sendTo( const SocketAddr& ReceiverAddr,
                                              const void* pBuffer,
                                              sal_uInt32 BufferSize,
                                              oslSocketMsgFlag Flag )
    {
        return osl_sendToSocket( m_handle, ReceiverAddr.getHandle(), pBuffer, BufferSize, Flag );
    }
}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010-2016 Raffaello D. Di Napoli

This file is part of Abaclade.

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

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

You should have received a copy of the GNU Lesser General Public License along with Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/text.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////

namespace abc { namespace _pvt {

/*static*/ void scope_trace_tuple::write_separator(io::text::ostream * ptos) {
   ptos->write(ABC_SL(", "));
}

}} //namespace abc::_pvt

////////////////////////////////////////////////////////////////////////////////////////////////////

namespace abc { namespace _pvt {

coroutine_local_value<scope_trace const *> scope_trace::sm_pstHead /*= nullptr*/;
coroutine_local_value<bool> scope_trace::sm_bReentering /*= false*/;
coroutine_local_ptr<io::text::str_ostream> scope_trace::sm_psosScopeTrace;
coroutine_local_value<unsigned> scope_trace::sm_cScopeTraceRefs /*= 0*/;
coroutine_local_value<unsigned> scope_trace::sm_iStackDepth /*= 0*/;

scope_trace::scope_trace(source_file_address const * psfa, scope_trace_tuple const * ptplVars) :
   m_pstPrev(sm_pstHead),
   m_psfa(psfa),
   m_ptplVars(ptplVars) {
   sm_pstHead = this;
}

scope_trace::~scope_trace() {
   /* The set-and-reset of sm_bReentering doesn’t need memory barriers because this is all contained
   in a single thread (sm_bReentering is in TLS). */
   if (!sm_bReentering && _std::uncaught_exception()) {
      sm_bReentering = true;
      try {
         write(get_trace_ostream(), ++sm_iStackDepth);
      } catch (...) {
         // Don’t allow a trace to interfere with the program flow.
         // FIXME: EXC-SWALLOW
      }
      sm_bReentering = false;
   }
   // Restore the previous scope trace single-linked list head.
   sm_pstHead = m_pstPrev;
}

void scope_trace::write(io::text::ostream * ptos, unsigned iStackDepth) const {
   ptos->print(
      ABC_SL("#{} {} with args: "), iStackDepth, str(external_buffer, m_psfa->function())
   );
   // Write the variables tuple.
   m_ptplVars->write(ptos);
   ptos->print(ABC_SL(" at {}\n"), m_psfa->file_address());
}

/*static*/ void scope_trace::write_list(io::text::ostream * ptos) {
   unsigned iStackDepth = 0;
   for (scope_trace const * pst = sm_pstHead; pst; pst = pst->m_pstPrev) {
      pst->write(ptos, ++iStackDepth);
   }
}

}} //namespace abc::_pvt
<commit_msg>Fix numbering of non-destructed scope traces in abc::_pvt::scope_trace::write_list()<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010-2016 Raffaello D. Di Napoli

This file is part of Abaclade.

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

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

You should have received a copy of the GNU Lesser General Public License along with Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/text.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////

namespace abc { namespace _pvt {

/*static*/ void scope_trace_tuple::write_separator(io::text::ostream * ptos) {
   ptos->write(ABC_SL(", "));
}

}} //namespace abc::_pvt

////////////////////////////////////////////////////////////////////////////////////////////////////

namespace abc { namespace _pvt {

coroutine_local_value<scope_trace const *> scope_trace::sm_pstHead /*= nullptr*/;
coroutine_local_value<bool> scope_trace::sm_bReentering /*= false*/;
coroutine_local_ptr<io::text::str_ostream> scope_trace::sm_psosScopeTrace;
coroutine_local_value<unsigned> scope_trace::sm_cScopeTraceRefs /*= 0*/;
coroutine_local_value<unsigned> scope_trace::sm_iStackDepth /*= 0*/;

scope_trace::scope_trace(source_file_address const * psfa, scope_trace_tuple const * ptplVars) :
   m_pstPrev(sm_pstHead),
   m_psfa(psfa),
   m_ptplVars(ptplVars) {
   sm_pstHead = this;
}

scope_trace::~scope_trace() {
   /* The set-and-reset of sm_bReentering doesn’t need memory barriers because this is all contained
   in a single thread (sm_bReentering is in TLS). */
   if (!sm_bReentering && _std::uncaught_exception()) {
      sm_bReentering = true;
      try {
         write(get_trace_ostream(), ++sm_iStackDepth);
      } catch (...) {
         // Don’t allow a trace to interfere with the program flow.
         // FIXME: EXC-SWALLOW
      }
      sm_bReentering = false;
   }
   // Restore the previous scope trace single-linked list head.
   sm_pstHead = m_pstPrev;
}

void scope_trace::write(io::text::ostream * ptos, unsigned iStackDepth) const {
   ptos->print(
      ABC_SL("#{} {} with args: "), iStackDepth, str(external_buffer, m_psfa->function())
   );
   // Write the variables tuple.
   m_ptplVars->write(ptos);
   ptos->print(ABC_SL(" at {}\n"), m_psfa->file_address());
}

/*static*/ void scope_trace::write_list(io::text::ostream * ptos) {
   unsigned iStackDepth = sm_iStackDepth;
   for (scope_trace const * pst = sm_pstHead; pst; pst = pst->m_pstPrev) {
      pst->write(ptos, ++iStackDepth);
   }
}

}} //namespace abc::_pvt
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#pragma once

#include <pdal/pdal_internal.hpp>

#include <string>
#include <cassert>
#include <stdexcept>
#include <cmath>
#include <fstream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>

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

namespace pdal
{

class PDAL_DLL Utils
{
public:
    static void random_seed(unsigned int seed);
    static double random(double minimum, double maximum);
    static double uniform(const double& minimum=0.0f,
        const double& maximum=1.0f, boost::uint32_t seed=0);
    static double normal(const double& mean=0.0f, const double& sigma=1.0f,
        boost::uint32_t seed=0);

    // compares two values to within the datatype's epsilon
    template<class T>
    static bool compare_distance(const T& actual, const T& expected)
    {
        const T epsilon = std::numeric_limits<T>::epsilon();
        return compare_approx<T>(actual, expected, epsilon);
    }

    // compares two values to within a given tolerance
    // the value |tolerance| is compared to |actual - expected|
    template<class T>
    static bool compare_approx(const T& actual, const T& expected,
        const T& tolerance)
    {
        double diff = std::abs((double)actual - (double)expected);
        return diff <= std::abs((double) tolerance);
    }

    // Return a 'T' from a stream and increment src by the sizeof 'T'
    template<class T>
    static inline T read_field(boost::uint8_t*& src)
    {
        T tmp = *(T*)(void*)src;
        src += sizeof(T);
        return tmp;
    }

    // Read 'num' items from the source stream to the dest location
    template <typename T>
    static inline void read_n(T& dest, std::istream& src,
        std::streamsize const& num)
    {
        if (!src.good())
            throw pdal::invalid_stream("pdal::Utils::read_n<T> input stream is "
                "not readable");

        char* p = as_buffer(dest);
        src.read(p, num);

        assert(check_stream_state(src));
    }

    //
    // From http://stackoverflow.com/questions/485525/round-for-float-in-c
    static inline double sround(double r)
    {
        return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
    }

    static inline std::vector<boost::uint8_t>hex_string_to_binary(
        std::string const& source)
    {
        // Stolen from http://stackoverflow.com/questions/7363774/  ...
        //    c-converting-binary-data-to-a-hex-string-and-back
        static int nibbles[] =
            { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0,
              10, 11, 12, 13, 14, 15 };
        std::vector<unsigned char> retval;
        for (auto it = source.begin(); it < source.end(); it += 2) {
            unsigned char v = 0;
            if (::isxdigit(*it))
                v = (unsigned char)nibbles[::toupper(*it) - '0'] << 4;
            if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
                v += (unsigned char)nibbles[::toupper(*(it + 1)) - '0'];
            retval.push_back(v);
        }
        return retval;
    }

    static inline void binary_to_hex_stream(unsigned char* source,
        std::ostream& destination, int start, int end )
    {
        static char syms[] = "0123456789ABCDEF";
        for (int i = start; i != end; i++)
            destination << syms[((source[i] >> 4) & 0xf)] <<
                           syms[source[i] & 0xf];
    }

    static inline std::string binary_to_hex_string(
        const std::vector<unsigned char>& source)
    {
        static char syms[] = "0123456789ABCDEF";
        std::stringstream ss;
        for (std::vector<unsigned char>::const_iterator it = source.begin();
                it != source.end(); it++)
            ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];

        return ss.str();
    }

    template<typename Target, typename Source>
    static inline Target saturation_cast(Source const& src)
    {
        try
        {
            return boost::numeric_cast<Target>(src);
        }
        catch (boost::numeric::negative_overflow const&)
        {
            return std::numeric_limits<Target>::min();
        }
        catch (boost::numeric::positive_overflow const&)
        {
            return std::numeric_limits<Target>::max();
        }
    }

    static void* registerPlugin( void* stageFactoryPtr,
                                std::string const& filename,
                                std::string const& registerMethodName,
                                std::string const& versionMethodName);

    static char* getenv(const char* env);
    static std::string getenv(std::string const& name);
    static int putenv(const char* env);

    // aid to operator>> parsers
    static void eatwhitespace(std::istream& s);
    static void removeTrailingBlanks(std::string& s);

    // aid to operator>> parsers
    // if char found, eats it and returns true; otherwise, don't eat it and
    // then return false
    static bool eatcharacter(std::istream& s, char x);

    static uint32_t getStreamPrecision(double scale);

    static void* getDLLSymbol(std::string const& library,
       std::string const& name);
    static std::string base64_encode(std::vector<uint8_t> const& bytes)
        { return base64_encode(bytes.data(), bytes.size()); }
    static std::string base64_encode(const unsigned char *buf, size_t size);
    static std::vector<boost::uint8_t> base64_decode(std::string const& input);

    static FILE* portable_popen(const std::string& command,
        const std::string& mode);
    static int portable_pclose(FILE* fp);
    static int run_shell_command(const std::string& cmd, std::string& output);

    static std::string replaceAll(std::string result,
                                  const std::string& replaceWhat,
                                  const std::string& replaceWithWhat);
    static void wordWrap(std::string const& inputString,
                         std::vector<std::string>& outputString,
                         unsigned int lineLength);
    static std::string escapeJSON(const std::string &s);
    static std::string demangle(const std::string& s);

    template<typename T>
    static std::string typeidName()
        { return Utils::demangle(typeid(T).name()); }

    struct RedirectCtx
    {
        std::ofstream *m_out;
        std::streambuf *m_buf;
    };

    /// Redirect a stream to some file, by default /dev/null.
    /// \param[in] out   Stream to redirect.
    /// \param[in] file  Name of file where stream should be redirected.
    /// \return  Context for stream restoration (see restore()).
    static RedirectCtx redirect(std::ostream& out,
        const std::string& file = "/dev/null")
    {
        RedirectCtx ctx;

        ctx.m_out = new std::ofstream(file);
        ctx.m_buf = out.rdbuf();
        out.rdbuf(ctx.m_out->rdbuf());
        return ctx;
    }

    /// Restore a stream redirected with redirect().
    /// \param[in] out  Stream to be restored.
    /// \param[in] ctx  Context returned from corresponding redirect() call.
    static void restore(std::ostream& out, RedirectCtx ctx)
    {
        out.rdbuf(ctx.m_buf);
        ctx.m_out->close();
    }

private:
    template<typename T>
    static inline char* as_buffer(T& data)
    {
        return static_cast<char*>(static_cast<void*>(&data));
    }

    template<typename T>
    static inline char* as_buffer(T* data)
    {
        return static_cast<char*>(static_cast<void*>(data));
    }

    /**
    template<typename T>
    static inline char const* as_bytes(T const& data)
    {
        return static_cast<char const*>(static_cast<void const*>(&data));
    }

    template<typename T>
    static inline char const* as_bytes(T const* data)
    {
        return static_cast<char const*>(static_cast<void const*>(data));
    }
    **/

    template <typename C, typename T>
    static inline bool check_stream_state(std::basic_ios<C, T>& srtm)
    {
        // Test stream state bits
        if (srtm.eof())
            throw std::out_of_range("end of file encountered");
        else if (srtm.fail())
            throw std::runtime_error("non-fatal I/O error occured");
        else if (srtm.bad())
            throw std::runtime_error("fatal I/O error occured");
        return true;
    }
};

} // namespace pdal

<commit_msg>Utils to namespace.<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#pragma once

#include <pdal/pdal_internal.hpp>

#include <string>
#include <cassert>
#include <stdexcept>
#include <cmath>
#include <fstream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>

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

namespace pdal
{

namespace Utils
{
    template<typename T>
    char *as_buffer(T& data)
        { return static_cast<char*>(static_cast<void*>(&data)); }

    template<typename T>
    char *as_buffer(T* data)
        { return static_cast<char*>(static_cast<void*>(data)); }

    template <typename C, typename T>
    bool check_stream_state(std::basic_ios<C, T>& srtm)
    {
        // Test stream state bits
        if (srtm.eof())
            throw std::out_of_range("end of file encountered");
        else if (srtm.fail())
            throw std::runtime_error("non-fatal I/O error occured");
        else if (srtm.bad())
            throw std::runtime_error("fatal I/O error occured");
        return true;
    }

    PDAL_DLL void random_seed(unsigned int seed);
    PDAL_DLL double random(double minimum, double maximum);
    PDAL_DLL double uniform(const double& minimum=0.0f,
        const double& maximum=1.0f, boost::uint32_t seed=0);
    PDAL_DLL double normal(const double& mean=0.0f, const double& sigma=1.0f,
        boost::uint32_t seed=0);

    // compares two values to within a given tolerance
    // the value |tolerance| is compared to |actual - expected|
    template<class T>
    bool compare_approx(const T& actual, const T& expected, const T& tolerance)
    {
        double diff = std::abs((double)actual - (double)expected);
        return diff <= std::abs((double) tolerance);
    }

    // compares two values to within the datatype's epsilon
    template<class T>
    bool compare_distance(const T& actual, const T& expected)
    {
        const T epsilon = std::numeric_limits<T>::epsilon();
        return compare_approx<T>(actual, expected, epsilon);
    }

    // Return a 'T' from a stream and increment src by the sizeof 'T'
    template<class T>
    T read_field(boost::uint8_t*& src)
    {
        T tmp = *(T*)(void*)src;
        src += sizeof(T);
        return tmp;
    }

    // Read 'num' items from the source stream to the dest location
    template <typename T>
    void read_n(T& dest, std::istream& src, std::streamsize const& num)
    {
        if (!src.good())
            throw pdal::invalid_stream("pdal::Utils::read_n<T> input stream is "
                "not readable");

        src.read(as_buffer(dest), num);
        assert(check_stream_state(src));
    }

    // From http://stackoverflow.com/questions/485525/round-for-float-in-c
    inline double sround(double r)
        { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); }

    inline std::vector<boost::uint8_t>hex_string_to_binary(
        std::string const& source)
    {
        // Stolen from http://stackoverflow.com/questions/7363774/  ...
        //    c-converting-binary-data-to-a-hex-string-and-back
        static int nibbles[] =
            { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0,
              10, 11, 12, 13, 14, 15 };
        std::vector<unsigned char> retval;
        for (auto it = source.begin(); it < source.end(); it += 2) {
            unsigned char v = 0;
            if (::isxdigit(*it))
                v = (unsigned char)nibbles[::toupper(*it) - '0'] << 4;
            if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
                v += (unsigned char)nibbles[::toupper(*(it + 1)) - '0'];
            retval.push_back(v);
        }
        return retval;
    }

    inline void binary_to_hex_stream(unsigned char* source,
        std::ostream& destination, int start, int end )
    {
        static char syms[] = "0123456789ABCDEF";
        for (int i = start; i != end; i++)
            destination << syms[((source[i] >> 4) & 0xf)] <<
                           syms[source[i] & 0xf];
    }

    inline std::string binary_to_hex_string(
        const std::vector<unsigned char>& source)
    {
        static char syms[] = "0123456789ABCDEF";
        std::stringstream ss;
        for (std::vector<unsigned char>::const_iterator it = source.begin();
                it != source.end(); it++)
            ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];

        return ss.str();
    }

    template<typename Target, typename Source>
    Target saturation_cast(Source const& src)
    {
        try
        {
            return boost::numeric_cast<Target>(src);
        }
        catch (boost::numeric::negative_overflow const&)
        {
            return std::numeric_limits<Target>::min();
        }
        catch (boost::numeric::positive_overflow const&)
        {
            return std::numeric_limits<Target>::max();
        }
    }

    PDAL_DLL void *registerPlugin(void *stageFactoryPtr,
        std::string const& filename, std::string const& registerMethodName,
        std::string const& versionMethodName);

    PDAL_DLL char *getenv(const char *env);
    PDAL_DLL std::string getenv(std::string const& name);
    PDAL_DLL int putenv(const char *env);

    // aid to operator>> parsers
    PDAL_DLL void eatwhitespace(std::istream& s);
    PDAL_DLL void removeTrailingBlanks(std::string& s);

    // aid to operator>> parsers
    // if char found, eats it and returns true; otherwise, don't eat it and
    // then return false
    PDAL_DLL bool eatcharacter(std::istream& s, char x);
    PDAL_DLL uint32_t getStreamPrecision(double scale);
    PDAL_DLL void *getDLLSymbol(std::string const& library,
        std::string const& name);
    PDAL_DLL std::string base64_encode(const unsigned char *buf, size_t size);
    inline std::string base64_encode(std::vector<uint8_t> const& bytes)
        { return base64_encode(bytes.data(), bytes.size()); }
    PDAL_DLL std::vector<boost::uint8_t>
    base64_decode(std::string const& input);

    PDAL_DLL FILE* portable_popen(const std::string& command,
        const std::string& mode);
    PDAL_DLL int portable_pclose(FILE* fp);
    PDAL_DLL int run_shell_command(const std::string& cmd, std::string& output);
    PDAL_DLL std::string replaceAll(std::string result,
        const std::string& replaceWhat, const std::string& replaceWithWhat);
    PDAL_DLL void wordWrap(std::string const& inputString,
        std::vector<std::string>& outputString, unsigned int lineLength);
    PDAL_DLL std::string escapeJSON(const std::string &s);
    PDAL_DLL std::string demangle(const std::string& s);

    template<typename T>
    std::string typeidName()
        { return Utils::demangle(typeid(T).name()); }

    struct RedirectCtx
    {
        std::ofstream *m_out;
        std::streambuf *m_buf;
    };

    /// Redirect a stream to some file, by default /dev/null.
    /// \param[in] out   Stream to redirect.
    /// \param[in] file  Name of file where stream should be redirected.
    /// \return  Context for stream restoration (see restore()).
    inline RedirectCtx redirect(std::ostream& out,
        const std::string& file = "/dev/null")
    {
        RedirectCtx ctx;

        ctx.m_out = new std::ofstream(file);
        ctx.m_buf = out.rdbuf();
        out.rdbuf(ctx.m_out->rdbuf());
        return ctx;
    }

    /// Restore a stream redirected with redirect().
    /// \param[in] out  Stream to be restored.
    /// \param[in] ctx  Context returned from corresponding redirect() call.
    inline void restore(std::ostream& out, RedirectCtx ctx)
    {
        out.rdbuf(ctx.m_buf);
        ctx.m_out->close();
    }
};

} // namespace pdal

<|endoftext|>


<commit_before>/*
 +----------------------------------------------------------------------+
 | PHP-OpenCV                                                           |
 +----------------------------------------------------------------------+
 | This source file is subject to version 2.0 of the Apache license,    |
 | that is bundled with this package in the file LICENSE, and is        |
 | available through the world-wide-web at the following url:           |
 | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 | If you did not receive a copy of the Apache2.0 license and are unable|
 | to obtain it through the world-wide-web, please send a note to       |
 | hihozhou@gmail.com so we can mail you a copy immediately.            |
 +----------------------------------------------------------------------+
 | Author: HaiHao Zhou  <hihozhou@gmail.com>                            |
 +----------------------------------------------------------------------+
 */

/* $Id$ */

extern "C" {
	#ifdef HAVE_CONFIG_H
	#include "config.h"
	#endif

	#include "php.h"
	#include "php_ini.h"
	#include "ext/standard/info.h"
}
#include "php_opencv.h"
#include "source/opencv2/opencv_imgcodecs.h"
#include "source/opencv2/opencv_highgui.h"
#include "source/opencv2/opencv_imgproc.h"
#include "source/opencv2/core/opencv_type.h"
#include "source/opencv2/core/opencv_mat.h"
#include "source/opencv2/core/hal/opencv_interface.h"
#include "opencv_exception.h"
#include "source/opencv2/opencv_core.h"
#include "source/opencv2/core/opencv_base.h"
#include "source/opencv2/core/opencv_persistence.h"
#include "source/opencv2/opencv_objdetect.h"
#include "source/opencv2/opencv_videoio.h"
#include "source/opencv2/opencv_face.h"

/* If you declare any globals in php_opencv.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(opencv)
*/

/* True global resources - no need for thread safety here */
static int le_opencv;

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("opencv.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_opencv_globals, opencv_globals)
    STD_PHP_INI_ENTRY("opencv.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_opencv_globals, opencv_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_opencv_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_opencv_compiled)
{
    char *arg = NULL;
	size_t arg_len, len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "opencv", arg);

	RETURN_STR(strg);
}

/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* {{{ php_opencv_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_opencv_init_globals(zend_opencv_globals *opencv_globals)
{
	opencv_globals->global_value = 0;
	opencv_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(opencv)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
    opencv_interface_init(module_number);
    opencv_imgcodecs_init(module_number);
    opencv_highgui_init(module_number);
    opencv_exception_init();
    opencv_mat_init();
    opencv_type_init(module_number);
    opencv_imgproc_init(module_number);
	opencv_core_init(module_number);
    opencv_border_types_init(module_number);
	opencv_file_storage_init(module_number);
	opencv_objdetect_init(module_number);
	opencv_videoio_init(module_number);
    opencv_face_init(module_number);

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(opencv)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(opencv)
{
#if defined(COMPILE_DL_OPENCV) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(opencv)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(opencv)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "opencv support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ opencv_functions[]
 *
 * Every user visible function must have an entry in opencv_functions[].
 */
const zend_function_entry opencv_functions[] = {
	PHP_FE(confirm_opencv_compiled,	NULL)		/* For testing, remove later. */
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8UC, ZEND_FN(opencv_cv_8uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8SC, ZEND_FN(opencv_cv_8sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16UC, ZEND_FN(opencv_cv_16uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16SC, ZEND_FN(opencv_cv_16sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32SC, ZEND_FN(opencv_cv_32sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32FC, ZEND_FN(opencv_cv_32fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_64FC, ZEND_FN(opencv_cv_64fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imread, ZEND_FN(opencv_imread), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imwrite, ZEND_FN(opencv_imwrite), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imshow, ZEND_FN(opencv_imshow), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, waitKey, ZEND_FN(opencv_wait_key), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, namedWindow, ZEND_FN(opencv_named_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, cvtColor, ZEND_FN(opencv_cv_t_color), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, ellipse, ZEND_FN(opencv_ellipse), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, circle, ZEND_FN(opencv_circle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, fillPoly, ZEND_FN(opencv_fill_poly), NULL)////TODO fillPoly
    ZEND_NS_NAMED_FE(OPENCV_NS, line, ZEND_FN(opencv_line), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangle, ZEND_FN(opencv_rectangle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByPoint, ZEND_FN(opencv_rectangle_by_point), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByRect, ZEND_FN(opencv_rectangle_by_rect), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, addWeighted, ZEND_FN(opencv_add_weighted), opencv_add_weighted_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, split, ZEND_FN(opencv_split), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, merge, ZEND_FN(opencv_merge), opencv_merge_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, createTrackbar, ZEND_FN(opencv_create_trackbar), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, destroyWindow, ZEND_FN(opencv_destroy_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, getOptimalDFTSize, ZEND_FN(opencv_get_optimal_dft_size), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, copyMakeBorder, ZEND_FN(opencv_copy_make_border), opencv_copy_make_border_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, dft, ZEND_FN(opencv_dft), opencv_dft_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, magnitude, ZEND_FN(opencv_magnitude), opencv_magnitude_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, add, ZEND_FN(opencv_add), opencv_add_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, log, ZEND_FN(opencv_log), opencv_log_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, normalize, ZEND_FN(opencv_normalize), opencv_normalize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, equalizeHist, ZEND_FN(opencv_equalize_hist), opencv_equalize_hist_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, resize, ZEND_FN(opencv_resize), opencv_resize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, putText, ZEND_FN(opencv_put_text), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, absdiff, ZEND_FN(opencv_absdiff), opencv_absdiff_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, getTrackBarPos, ZEND_FN(opencv_get_track_bar_pos), NULL)
	PHP_FE_END	/* Must be the last line in opencv_functions[] */
};
/* }}} */

/* {{{ opencv_module_entry
 */
zend_module_entry opencv_module_entry = {
	STANDARD_MODULE_HEADER,
	"opencv",
	opencv_functions,
	PHP_MINIT(opencv),
	PHP_MSHUTDOWN(opencv),
	PHP_RINIT(opencv),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(opencv),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(opencv),
	PHP_OPENCV_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_OPENCV
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(opencv)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<commit_msg>add annotation<commit_after>/*
 +----------------------------------------------------------------------+
 | PHP-OpenCV                                                           |
 +----------------------------------------------------------------------+
 | This source file is subject to version 2.0 of the Apache license,    |
 | that is bundled with this package in the file LICENSE, and is        |
 | available through the world-wide-web at the following url:           |
 | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 | If you did not receive a copy of the Apache2.0 license and are unable|
 | to obtain it through the world-wide-web, please send a note to       |
 | hihozhou@gmail.com so we can mail you a copy immediately.            |
 +----------------------------------------------------------------------+
 | Author: HaiHao Zhou  <hihozhou@gmail.com>                            |
 +----------------------------------------------------------------------+
 */

/* $Id$ */

extern "C" {
	#ifdef HAVE_CONFIG_H
	#include "config.h"
	#endif

	#include "php.h"
	#include "php_ini.h"
	#include "ext/standard/info.h"
}
#include "php_opencv.h"
#include "source/opencv2/opencv_imgcodecs.h"
#include "source/opencv2/opencv_highgui.h"
#include "source/opencv2/opencv_imgproc.h"
#include "source/opencv2/core/opencv_type.h"
#include "source/opencv2/core/opencv_mat.h"
#include "source/opencv2/core/hal/opencv_interface.h"
#include "opencv_exception.h"
#include "source/opencv2/opencv_core.h"
#include "source/opencv2/core/opencv_base.h"
#include "source/opencv2/core/opencv_persistence.h"
#include "source/opencv2/opencv_objdetect.h"
#include "source/opencv2/opencv_videoio.h"
#include "source/opencv2/opencv_face.h"

/* If you declare any globals in php_opencv.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(opencv)
*/

/* True global resources - no need for thread safety here */
static int le_opencv;

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("opencv.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_opencv_globals, opencv_globals)
    STD_PHP_INI_ENTRY("opencv.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_opencv_globals, opencv_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_opencv_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_opencv_compiled)
{
    char *arg = NULL;
	size_t arg_len, len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "opencv", arg);

	RETURN_STR(strg);
}

/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* {{{ php_opencv_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_opencv_init_globals(zend_opencv_globals *opencv_globals)
{
	opencv_globals->global_value = 0;
	opencv_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(opencv)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
    opencv_interface_init(module_number);
    opencv_imgcodecs_init(module_number);
    opencv_highgui_init(module_number);
    opencv_exception_init();
    opencv_mat_init();
    opencv_type_init(module_number);
    opencv_imgproc_init(module_number);
	opencv_core_init(module_number);
    opencv_border_types_init(module_number);
	opencv_file_storage_init(module_number);
	opencv_objdetect_init(module_number);
	opencv_videoio_init(module_number);
    opencv_face_init(module_number);

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(opencv)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(opencv)
{
#if defined(COMPILE_DL_OPENCV) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(opencv)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(opencv)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "opencv support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ opencv_functions[]
 *
 * Every user visible function must have an entry in opencv_functions[].
 */
const zend_function_entry opencv_functions[] = {
	PHP_FE(confirm_opencv_compiled,	NULL)		/* For testing, remove later. */
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8UC, ZEND_FN(opencv_cv_8uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_8SC, ZEND_FN(opencv_cv_8sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16UC, ZEND_FN(opencv_cv_16uc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_16SC, ZEND_FN(opencv_cv_16sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32SC, ZEND_FN(opencv_cv_32sc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_32FC, ZEND_FN(opencv_cv_32fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, CV_64FC, ZEND_FN(opencv_cv_64fc), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imread, ZEND_FN(opencv_imread), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imwrite, ZEND_FN(opencv_imwrite), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, imshow, ZEND_FN(opencv_imshow), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, waitKey, ZEND_FN(opencv_wait_key), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, namedWindow, ZEND_FN(opencv_named_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, cvtColor, ZEND_FN(opencv_cv_t_color), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, ellipse, ZEND_FN(opencv_ellipse), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, circle, ZEND_FN(opencv_circle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, fillPoly, ZEND_FN(opencv_fill_poly), NULL)//TODO fillPoly
    ZEND_NS_NAMED_FE(OPENCV_NS, line, ZEND_FN(opencv_line), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangle, ZEND_FN(opencv_rectangle), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByPoint, ZEND_FN(opencv_rectangle_by_point), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, rectangleByRect, ZEND_FN(opencv_rectangle_by_rect), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, addWeighted, ZEND_FN(opencv_add_weighted), opencv_add_weighted_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, split, ZEND_FN(opencv_split), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, merge, ZEND_FN(opencv_merge), opencv_merge_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, createTrackbar, ZEND_FN(opencv_create_trackbar), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, destroyWindow, ZEND_FN(opencv_destroy_window), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, getOptimalDFTSize, ZEND_FN(opencv_get_optimal_dft_size), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, copyMakeBorder, ZEND_FN(opencv_copy_make_border), opencv_copy_make_border_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, dft, ZEND_FN(opencv_dft), opencv_dft_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, magnitude, ZEND_FN(opencv_magnitude), opencv_magnitude_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, add, ZEND_FN(opencv_add), opencv_add_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, log, ZEND_FN(opencv_log), opencv_log_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, normalize, ZEND_FN(opencv_normalize), opencv_normalize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, equalizeHist, ZEND_FN(opencv_equalize_hist), opencv_equalize_hist_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, resize, ZEND_FN(opencv_resize), opencv_resize_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, putText, ZEND_FN(opencv_put_text), NULL)
    ZEND_NS_NAMED_FE(OPENCV_NS, absdiff, ZEND_FN(opencv_absdiff), opencv_absdiff_arginfo)
    ZEND_NS_NAMED_FE(OPENCV_NS, getTrackBarPos, ZEND_FN(opencv_get_track_bar_pos), NULL)
	PHP_FE_END	/* Must be the last line in opencv_functions[] */
};
/* }}} */

/* {{{ opencv_module_entry
 */
zend_module_entry opencv_module_entry = {
	STANDARD_MODULE_HEADER,
	"opencv",
	opencv_functions,
	PHP_MINIT(opencv),
	PHP_MSHUTDOWN(opencv),
	PHP_RINIT(opencv),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(opencv),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(opencv),
	PHP_OPENCV_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_OPENCV
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(opencv)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<|endoftext|>