<commit_before>#include "../stkpl/StkPl.h"
#include "../commonfunc/StkObject.h"
#include "../commonfunc/StkStringParser.h"
#include "../stksocket/stksocket.h"
#include "StkWebAppSend.h"

class StkWebAppSend::Impl
{
public:
	int SendBufSize;
	int RecvBufSize;

	int TimeoutInterval;

	int MyId;

public:
	const wchar_t* SkipHttpHeader(const wchar_t*);
	StkObject* RecvResponse(int, wchar_t[1024]);
	int SendRequest(int, int, const char*, StkObject*);
};

const wchar_t* StkWebAppSend::Impl::SkipHttpHeader(const wchar_t* Txt)
{
	const wchar_t* Ptr = NULL;
	Ptr = StkPlWcsStr(Txt, L"\r\n\r\n");
	if (Ptr != NULL) {
		Ptr += 4;
		return Ptr;
	}
	Ptr = StkPlWcsStr(Txt, L"\n\r\n\r");
	if (Ptr != NULL) {
		Ptr += 4;
		return Ptr;
	}
	Ptr = StkPlWcsStr(Txt, L"\n\n");
	if (Ptr != NULL) {
		Ptr += 2;
		return Ptr;
	}
	return Txt;
}

StkObject* StkWebAppSend::Impl::RecvResponse(int TargetId, wchar_t Header[1024])
{
	unsigned char *Dat = new unsigned char[RecvBufSize];
	int Ret = StkSocket_Receive(TargetId, TargetId, Dat, RecvBufSize, STKSOCKET_RECV_FINISHCOND_CONTENTLENGTH, TimeoutInterval, NULL, -1);
	StkSocket_Disconnect(TargetId, TargetId, true);
	if (Ret == 0 || Ret == -1 || Ret == -2) {
		delete Dat;
		return NULL;
	}
	if (Ret >= RecvBufSize) {
		Dat[RecvBufSize - 1] = '\0';
	} else {
		Dat[Ret] = '\0';
	}
	wchar_t *DatWc = StkPlCreateWideCharFromUtf8((char*)Dat);
	delete Dat;
	if (DatWc == NULL) {
		return NULL;
	}

	// Acquire HTTP header
	const wchar_t* Req = SkipHttpHeader(DatWc);
	if (Req == DatWc || Req - DatWc >= 1024 - 1) {
		delete DatWc;
		return NULL;
	}
	StkPlWcsNCpy(Header, 1024, DatWc, Req - DatWc);
	int Tmp;
	StkObject* ReqObj = StkObject::CreateObjectFromJson(Req, &Tmp);

	delete DatWc;
	return ReqObj;
}

int StkWebAppSend::Impl::SendRequest(int TargetId, int Method, const char* Url, StkObject* ReqObj)
{
	// JSON conversion and UTF-8 conversion
	wchar_t* WDat = new wchar_t[SendBufSize];
	StkPlWcsCpy(WDat, SendBufSize, L"");
	int Length = 0;
	if (ReqObj != NULL) {
		ReqObj->ToJson(WDat, SendBufSize);
	}
	if (Length == SendBufSize - 1) {
		delete WDat;
		return -1;
	}
	char* Dat = StkPlCreateUtf8FromWideChar(WDat);
	size_t DatLength = StkPlStrLen(Dat);
	delete WDat;

	// Making HTTP header
	char HttpHeader[1024] = "";

	if (Method == STKWEBAPP_METHOD_GET) {
		StkPlStrCat(HttpHeader, 1024, "GET ");
	} else if (Method == STKWEBAPP_METHOD_POST) {
		StkPlStrCat(HttpHeader, 1024, "POST ");
	} else if (Method == STKWEBAPP_METHOD_PUT) {
		StkPlStrCat(HttpHeader, 1024, "PUT ");
	} else if (Method == STKWEBAPP_METHOD_DELETE) {
		StkPlStrCat(HttpHeader, 1024, "DELETE ");
	} else if (Method == STKWEBAPP_METHOD_HEAD) {
		StkPlStrCat(HttpHeader, 1024, "HEAD ");
	}
	StkPlStrCat(HttpHeader, 1024, Url);
	StkPlStrCat(HttpHeader, 1024, " HTTP/1.1\r\n");
	if (DatLength != 0) {
		char HttpHeaderContLen[64] = "";
		StkPlSPrintf(HttpHeaderContLen, 64, "Content-Length: %d\r\n", DatLength);
		StkPlStrCat(HttpHeader, 1024, HttpHeaderContLen);
	}
	if (Dat != NULL && *Dat != L'\0') {
		StkPlStrCat(HttpHeader, 1024, "Content-Type: application/json\r\n");
	}
	{
		char Date[64] = "";
		char DateTmp[64] = "";
		StkPlGetTimeInRfc2822(DateTmp, false);
		StkPlSPrintf(Date, 64, "Date: %s\r\n", DateTmp);
		StkPlStrCat(HttpHeader, 1024, Date);
	}
	{
		int SockType = 0;
		int ActionType = 0;
		wchar_t TargetAddr[256] = L"";
		int TargetPort = 0;
		bool CopiedFlag = true;
		if (StkSocket_GetInfo(TargetId, &SockType, &ActionType, TargetAddr, &TargetPort, &CopiedFlag) == 0) {
			char HostHeader[512] = "";
			char* TargetAddru8 = StkPlCreateUtf8FromWideChar(TargetAddr);
			StkPlSPrintf(HostHeader, 512, "Host: %s\r\n", TargetAddru8);
			StkPlStrCat(HttpHeader, 1024, HostHeader);
			delete TargetAddru8;
		}
	}
	StkPlStrCat(HttpHeader, 1024, "\r\n");
	int HeaderLength = StkPlStrLen(HttpHeader);

	// Making request data and send
	int ReqDatLength = DatLength + HeaderLength;
	if (ReqDatLength >= SendBufSize) {
		delete Dat;
		return -1;
	}
	char* ReqDat = new char[ReqDatLength + 1];
	StkPlStrCpy(ReqDat, ReqDatLength + 1, "");
	StkPlStrCat(ReqDat, ReqDatLength + 1, HttpHeader);
	StkPlStrCat((char*)ReqDat, ReqDatLength + 1, Dat);
	int RetD = StkSocket_Connect(TargetId);
	if (RetD == 0) {
		RetD = StkSocket_Send(TargetId, TargetId, (unsigned char*)ReqDat, ReqDatLength);
	}

	// Delete array
	delete Dat;
	delete ReqDat;
	return RetD;
}

StkWebAppSend::StkWebAppSend(int TargetId, const wchar_t* HostNameOrIpAddr, int PortNum)
{
	pImpl = new Impl;
	pImpl->SendBufSize = 1000000;
	pImpl->RecvBufSize = 1000000;
	pImpl->TimeoutInterval = 3000;
	pImpl->MyId = TargetId;
	StkSocket_AddInfo(pImpl->MyId, STKSOCKET_TYPE_STREAM, STKSOCKET_ACTIONTYPE_SENDER, HostNameOrIpAddr, PortNum);
}

StkWebAppSend::~StkWebAppSend()
{
	StkSocket_DeleteInfo(pImpl->MyId);
	delete pImpl;
};

StkObject* StkWebAppSend::SendRequestRecvResponse(int Method, const char* Url, StkObject* ReqObj, int* ResultCode)
{
	StkSocket_Connect(pImpl->MyId);

	StkObject* ResDat = NULL;
	wchar_t Header[1024];
	int RetSend = pImpl->SendRequest(pImpl->MyId, Method, Url, ReqObj);
	if (RetSend >= 0) {
		ResDat = pImpl->RecvResponse(pImpl->MyId, Header);
		if (ResDat == NULL) {
			*ResultCode = -1;
		} else {
			wchar_t TmpStr[16] = L"";
			wchar_t StrResultCode[16] = L"";
			StkStringParser::ParseInto3Params(Header, L"$ $ $", L'$', NULL, -1, StrResultCode, 16, NULL, -1);
			if (StrResultCode != NULL) {
				*ResultCode = StkPlWcsToL(StrResultCode);
			}
		}
	} else {
		*ResultCode = -1;
	}

	StkSocket_Disconnect(pImpl->MyId, pImpl->MyId, true);

	return ResDat;
}

int StkWebAppSend::GetSendBufSize()
{
	return pImpl->SendBufSize;
}

void StkWebAppSend::SetSendBufSize(int Size)
{
	pImpl->SendBufSize = Size;
}

int StkWebAppSend::GetRecvBufSize()
{
	return pImpl->RecvBufSize;
}

void StkWebAppSend::SetRecvBufSize(int Size)
{
	pImpl->RecvBufSize = Size;
}

int StkWebAppSend::GetTimeoutInterval()
{
	return pImpl->TimeoutInterval;
}

void StkWebAppSend::SetTimeoutInterval(int Interval)
{
	pImpl->TimeoutInterval = Interval;
}
<commit_msg>#114 : Redundant connect/disconnect has been deleted.<commit_after>#include "../stkpl/StkPl.h"
#include "../commonfunc/StkObject.h"
#include "../commonfunc/StkStringParser.h"
#include "../stksocket/stksocket.h"
#include "StkWebAppSend.h"

class StkWebAppSend::Impl
{
public:
	int SendBufSize;
	int RecvBufSize;

	int TimeoutInterval;

	int MyId;

public:
	const wchar_t* SkipHttpHeader(const wchar_t*);
	StkObject* RecvResponse(int, wchar_t[1024]);
	int SendRequest(int, int, const char*, StkObject*);
};

const wchar_t* StkWebAppSend::Impl::SkipHttpHeader(const wchar_t* Txt)
{
	const wchar_t* Ptr = NULL;
	Ptr = StkPlWcsStr(Txt, L"\r\n\r\n");
	if (Ptr != NULL) {
		Ptr += 4;
		return Ptr;
	}
	Ptr = StkPlWcsStr(Txt, L"\n\r\n\r");
	if (Ptr != NULL) {
		Ptr += 4;
		return Ptr;
	}
	Ptr = StkPlWcsStr(Txt, L"\n\n");
	if (Ptr != NULL) {
		Ptr += 2;
		return Ptr;
	}
	return Txt;
}

StkObject* StkWebAppSend::Impl::RecvResponse(int TargetId, wchar_t Header[1024])
{
	unsigned char *Dat = new unsigned char[RecvBufSize];
	int Ret = StkSocket_Receive(TargetId, TargetId, Dat, RecvBufSize, STKSOCKET_RECV_FINISHCOND_CONTENTLENGTH, TimeoutInterval, NULL, -1);
	if (Ret == 0 || Ret == -1 || Ret == -2) {
		delete Dat;
		return NULL;
	}
	if (Ret >= RecvBufSize) {
		Dat[RecvBufSize - 1] = '\0';
	} else {
		Dat[Ret] = '\0';
	}
	wchar_t *DatWc = StkPlCreateWideCharFromUtf8((char*)Dat);
	delete Dat;
	if (DatWc == NULL) {
		return NULL;
	}

	// Acquire HTTP header
	const wchar_t* Req = SkipHttpHeader(DatWc);
	if (Req == DatWc || Req - DatWc >= 1024 - 1) {
		delete DatWc;
		return NULL;
	}
	StkPlWcsNCpy(Header, 1024, DatWc, Req - DatWc);
	int Tmp;
	StkObject* ReqObj = StkObject::CreateObjectFromJson(Req, &Tmp);

	delete DatWc;
	return ReqObj;
}

int StkWebAppSend::Impl::SendRequest(int TargetId, int Method, const char* Url, StkObject* ReqObj)
{
	// JSON conversion and UTF-8 conversion
	wchar_t* WDat = new wchar_t[SendBufSize];
	StkPlWcsCpy(WDat, SendBufSize, L"");
	int Length = 0;
	if (ReqObj != NULL) {
		ReqObj->ToJson(WDat, SendBufSize);
	}
	if (Length == SendBufSize - 1) {
		delete WDat;
		return -1;
	}
	char* Dat = StkPlCreateUtf8FromWideChar(WDat);
	size_t DatLength = StkPlStrLen(Dat);
	delete WDat;

	// Making HTTP header
	char HttpHeader[1024] = "";

	if (Method == STKWEBAPP_METHOD_GET) {
		StkPlStrCat(HttpHeader, 1024, "GET ");
	} else if (Method == STKWEBAPP_METHOD_POST) {
		StkPlStrCat(HttpHeader, 1024, "POST ");
	} else if (Method == STKWEBAPP_METHOD_PUT) {
		StkPlStrCat(HttpHeader, 1024, "PUT ");
	} else if (Method == STKWEBAPP_METHOD_DELETE) {
		StkPlStrCat(HttpHeader, 1024, "DELETE ");
	} else if (Method == STKWEBAPP_METHOD_HEAD) {
		StkPlStrCat(HttpHeader, 1024, "HEAD ");
	}
	StkPlStrCat(HttpHeader, 1024, Url);
	StkPlStrCat(HttpHeader, 1024, " HTTP/1.1\r\n");
	if (DatLength != 0) {
		char HttpHeaderContLen[64] = "";
		StkPlSPrintf(HttpHeaderContLen, 64, "Content-Length: %d\r\n", DatLength);
		StkPlStrCat(HttpHeader, 1024, HttpHeaderContLen);
	}
	if (Dat != NULL && *Dat != L'\0') {
		StkPlStrCat(HttpHeader, 1024, "Content-Type: application/json\r\n");
	}
	{
		char Date[64] = "";
		char DateTmp[64] = "";
		StkPlGetTimeInRfc2822(DateTmp, false);
		StkPlSPrintf(Date, 64, "Date: %s\r\n", DateTmp);
		StkPlStrCat(HttpHeader, 1024, Date);
	}
	{
		int SockType = 0;
		int ActionType = 0;
		wchar_t TargetAddr[256] = L"";
		int TargetPort = 0;
		bool CopiedFlag = true;
		if (StkSocket_GetInfo(TargetId, &SockType, &ActionType, TargetAddr, &TargetPort, &CopiedFlag) == 0) {
			char HostHeader[512] = "";
			char* TargetAddru8 = StkPlCreateUtf8FromWideChar(TargetAddr);
			StkPlSPrintf(HostHeader, 512, "Host: %s\r\n", TargetAddru8);
			StkPlStrCat(HttpHeader, 1024, HostHeader);
			delete TargetAddru8;
		}
	}
	StkPlStrCat(HttpHeader, 1024, "\r\n");
	int HeaderLength = StkPlStrLen(HttpHeader);

	// Making request data and send
	int ReqDatLength = DatLength + HeaderLength;
	if (ReqDatLength >= SendBufSize) {
		delete Dat;
		return -1;
	}
	char* ReqDat = new char[ReqDatLength + 1];
	StkPlStrCpy(ReqDat, ReqDatLength + 1, "");
	StkPlStrCat(ReqDat, ReqDatLength + 1, HttpHeader);
	StkPlStrCat((char*)ReqDat, ReqDatLength + 1, Dat);
	int RetD = StkSocket_Send(TargetId, TargetId, (unsigned char*)ReqDat, ReqDatLength);

	// Delete array
	delete Dat;
	delete ReqDat;
	return RetD;
}

StkWebAppSend::StkWebAppSend(int TargetId, const wchar_t* HostNameOrIpAddr, int PortNum)
{
	pImpl = new Impl;
	pImpl->SendBufSize = 1000000;
	pImpl->RecvBufSize = 1000000;
	pImpl->TimeoutInterval = 3000;
	pImpl->MyId = TargetId;
	StkSocket_AddInfo(pImpl->MyId, STKSOCKET_TYPE_STREAM, STKSOCKET_ACTIONTYPE_SENDER, HostNameOrIpAddr, PortNum);
}

StkWebAppSend::~StkWebAppSend()
{
	StkSocket_DeleteInfo(pImpl->MyId);
	delete pImpl;
};

StkObject* StkWebAppSend::SendRequestRecvResponse(int Method, const char* Url, StkObject* ReqObj, int* ResultCode)
{
	int RetConn = StkSocket_Connect(pImpl->MyId);
	if (RetConn != 0) {
		*ResultCode = -1;
		return NULL;
	}

	StkObject* ResDat = NULL;
	wchar_t Header[1024];
	int RetSend = pImpl->SendRequest(pImpl->MyId, Method, Url, ReqObj);
	if (RetSend >= 0) {
		ResDat = pImpl->RecvResponse(pImpl->MyId, Header);
		if (ResDat == NULL) {
			*ResultCode = -1;
		} else {
			wchar_t TmpStr[16] = L"";
			wchar_t StrResultCode[16] = L"";
			StkStringParser::ParseInto3Params(Header, L"$ $ $", L'$', NULL, -1, StrResultCode, 16, NULL, -1);
			if (StrResultCode != NULL) {
				*ResultCode = StkPlWcsToL(StrResultCode);
			}
		}
	} else {
		*ResultCode = -1;
	}

	StkSocket_Disconnect(pImpl->MyId, pImpl->MyId, true);

	return ResDat;
}

int StkWebAppSend::GetSendBufSize()
{
	return pImpl->SendBufSize;
}

void StkWebAppSend::SetSendBufSize(int Size)
{
	pImpl->SendBufSize = Size;
}

int StkWebAppSend::GetRecvBufSize()
{
	return pImpl->RecvBufSize;
}

void StkWebAppSend::SetRecvBufSize(int Size)
{
	pImpl->RecvBufSize = Size;
}

int StkWebAppSend::GetTimeoutInterval()
{
	return pImpl->TimeoutInterval;
}

void StkWebAppSend::SetTimeoutInterval(int Interval)
{
	pImpl->TimeoutInterval = Interval;
}
<|endoftext|>


<commit_before>#include "LightShaderHandler.h"

LightShaderHandler::LightShaderHandler()
{
}

LightShaderHandler::~LightShaderHandler()
{
}

int LightShaderHandler::Initialize(ID3D11Device * device, HWND * windowHandle, DirectX::XMFLOAT2 resolution)
{
	HRESULT hResult;
	ID3D10Blob* vertexShaderBuffer = nullptr;
	ID3D10Blob* pixelShaderBuffer = nullptr;

	//Insert shader path here
	WCHAR* vsFilename = L"../GraphicsDLL/LightVertexShader.hlsl";
	WCHAR* psFilename = L"../GraphicsDLL/LightPixelShader.hlsl";

	// Compile the shaders \\

	hResult = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &vertexShaderBuffer, NULL);
	if (FAILED(hResult))
	{
		return 1;
	}
	hResult = D3DCompileFromFile(psFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &pixelShaderBuffer, NULL);
	if (FAILED(hResult))
	{
		return 1;
	}

	// Create the shaders \\

	hResult = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &this->m_vertexShader[0]);
	if (FAILED(hResult))
	{
		return 1;
	}
	hResult = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &this->m_pixelShader);
	if (FAILED(hResult)) {
		return 1;
	}

	// Create the input layout \\

	D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
	polygonLayout[0].SemanticName = "POSITION";
	polygonLayout[0].SemanticIndex = 0;
	polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
	polygonLayout[0].InputSlot = 0;
	polygonLayout[0].AlignedByteOffset = 0;
	polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[0].InstanceDataStepRate = 0;

	polygonLayout[1].SemanticName = "TEXCOORD";
	polygonLayout[1].SemanticIndex = 0;
	polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
	polygonLayout[1].InputSlot = 0;
	polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[1].InstanceDataStepRate = 0;

	unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
	//Create the vertex input layout.
	hResult = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &this->m_layout);
	if (FAILED(hResult)) {
		return 1;
	}

	//Release and nullptr the buffers as they are no longer needed
	vertexShaderBuffer->Release();
	vertexShaderBuffer = nullptr;
	pixelShaderBuffer->Release();
	pixelShaderBuffer = nullptr;

	// Create the matrix buffer \\

	D3D11_BUFFER_DESC matrixBufferDesc;
	ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc));
	//Fill the description of the dynamic matrix constant buffer that is in the vertex shader
	matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDesc.ByteWidth = sizeof(ShaderLib::LightConstantBuffer);
	matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	matrixBufferDesc.MiscFlags = 0;
	matrixBufferDesc.StructureByteStride = 0;

	// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
	hResult = device->CreateBuffer(&matrixBufferDesc, NULL, &this->m_matrixBuffer);
	if (FAILED(hResult)) {
		return 1;
	}

	// Create the sampler \\

	D3D11_SAMPLER_DESC samplerDesc;
	ZeroMemory(&samplerDesc, sizeof(samplerDesc));

	//Fill the texture sampler state description
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.MaxAnisotropy = 1;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	samplerDesc.BorderColor[0] = 0;
	samplerDesc.BorderColor[1] = 0;
	samplerDesc.BorderColor[2] = 0;
	samplerDesc.BorderColor[3] = 0;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	//Create the texture sampler state
	hResult = device->CreateSamplerState(&samplerDesc, &this->m_samplerState);
	if (FAILED(hResult))
	{
		return 1;
	}

	return 0;
}

int LightShaderHandler::SetActive(ID3D11DeviceContext * deviceContext, ShaderLib::ShaderType shaderType)
{
	ShaderHandler::SetActive(deviceContext, shaderType);

	//Set the sampler state in pixel shader
	deviceContext->PSSetSamplers(0, 1, &this->m_samplerState);

	return 0;
}

void LightShaderHandler::Shutdown()
{
}

int LightShaderHandler::SetShaderParameters(ID3D11DeviceContext * deviceContext, ShaderLib::LightConstantBuffer * shaderParams)
{
	return 0;
}
<commit_msg>ADD LightShaderHandler Shutdown() implemented<commit_after>#include "LightShaderHandler.h"

LightShaderHandler::LightShaderHandler()
{
}

LightShaderHandler::~LightShaderHandler()
{
}

int LightShaderHandler::Initialize(ID3D11Device * device, HWND * windowHandle, DirectX::XMFLOAT2 resolution)
{
	HRESULT hResult;
	ID3D10Blob* vertexShaderBuffer = nullptr;
	ID3D10Blob* pixelShaderBuffer = nullptr;

	//Insert shader path here
	WCHAR* vsFilename = L"../GraphicsDLL/LightVertexShader.hlsl";
	WCHAR* psFilename = L"../GraphicsDLL/LightPixelShader.hlsl";

	// Compile the shaders \\

	hResult = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &vertexShaderBuffer, NULL);
	if (FAILED(hResult))
	{
		return 1;
	}
	hResult = D3DCompileFromFile(psFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &pixelShaderBuffer, NULL);
	if (FAILED(hResult))
	{
		return 1;
	}

	// Create the shaders \\

	hResult = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &this->m_vertexShader[0]);
	if (FAILED(hResult))
	{
		return 1;
	}
	hResult = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &this->m_pixelShader);
	if (FAILED(hResult)) {
		return 1;
	}

	// Create the input layout \\

	D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
	polygonLayout[0].SemanticName = "POSITION";
	polygonLayout[0].SemanticIndex = 0;
	polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
	polygonLayout[0].InputSlot = 0;
	polygonLayout[0].AlignedByteOffset = 0;
	polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[0].InstanceDataStepRate = 0;

	polygonLayout[1].SemanticName = "TEXCOORD";
	polygonLayout[1].SemanticIndex = 0;
	polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
	polygonLayout[1].InputSlot = 0;
	polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[1].InstanceDataStepRate = 0;

	unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
	//Create the vertex input layout.
	hResult = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &this->m_layout);
	if (FAILED(hResult)) {
		return 1;
	}

	//Release and nullptr the buffers as they are no longer needed
	vertexShaderBuffer->Release();
	vertexShaderBuffer = nullptr;
	pixelShaderBuffer->Release();
	pixelShaderBuffer = nullptr;

	// Create the matrix buffer \\

	D3D11_BUFFER_DESC matrixBufferDesc;
	ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc));
	//Fill the description of the dynamic matrix constant buffer that is in the vertex shader
	matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDesc.ByteWidth = sizeof(ShaderLib::LightConstantBuffer);
	matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	matrixBufferDesc.MiscFlags = 0;
	matrixBufferDesc.StructureByteStride = 0;

	// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
	hResult = device->CreateBuffer(&matrixBufferDesc, NULL, &this->m_matrixBuffer);
	if (FAILED(hResult)) {
		return 1;
	}

	// Create the sampler \\

	D3D11_SAMPLER_DESC samplerDesc;
	ZeroMemory(&samplerDesc, sizeof(samplerDesc));

	//Fill the texture sampler state description
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.MaxAnisotropy = 1;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	samplerDesc.BorderColor[0] = 0;
	samplerDesc.BorderColor[1] = 0;
	samplerDesc.BorderColor[2] = 0;
	samplerDesc.BorderColor[3] = 0;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	//Create the texture sampler state
	hResult = device->CreateSamplerState(&samplerDesc, &this->m_samplerState);
	if (FAILED(hResult))
	{
		return 1;
	}

	return 0;
}

int LightShaderHandler::SetActive(ID3D11DeviceContext * deviceContext, ShaderLib::ShaderType shaderType)
{
	ShaderHandler::SetActive(deviceContext, shaderType);

	//Set the sampler state in pixel shader
	deviceContext->PSSetSamplers(0, 1, &this->m_samplerState);

	return 0;
}

void LightShaderHandler::Shutdown()
{
	ShaderHandler::Shutdown();

	//Release the sampler state
	if (this->m_samplerState)
	{
		this->m_samplerState->Release();
		this->m_samplerState = nullptr;
	}
}

int LightShaderHandler::SetShaderParameters(ID3D11DeviceContext * deviceContext, ShaderLib::LightConstantBuffer * shaderParams)
{
	return 0;
}
<|endoftext|>


<commit_before>/*!
 * \copy
 *     Copyright (c)  2009-2013, Cisco Systems
 *     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.
 *
 *     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 HOLDER 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.
 *
 *
 * \file	utils.c
 *
 * \brief	common tool/function utilization
 *
 * \date	03/10/2009 Created
 *
 *************************************************************************************
 */

#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#if defined(_WIN32)
#include <windows.h>
#include <sys/types.h>
#include <sys/timeb.h>
#ifndef _MSC_VER
#include <sys/time.h>
#ifndef HAVE_STRNLEN
#define strnlen(a,b) strlen(a)
#endif //!HAVE_STRNLEN
#endif //!_MSC_VER
#else
#include <sys/time.h>
#include <sys/timeb.h>
#endif //_WIN32

#include "utils.h"
#include "macros.h"
#include "wels_const.h"
#include "cpu_core.h"
#include "decoder_context.h"
#include "crt_util_safe_x.h"	// Safe CRT routines like utils for cross platforms
#include "mem_align.h"

namespace WelsDec {

// to fill default routines
PWelsLogCallbackFunc g_pLog	= NULL;

void_t WelsLog (void_t* pPtr, int32_t iLevel, const char* kpFmt, ...) {
  va_list pVl;

  PWelsDecoderContext pCtx  = (PWelsDecoderContext)pPtr;

  va_start (pVl, kpFmt);
  g_pLog (pCtx->pTraceHandle, iLevel, kpFmt, pVl);
  va_end (pVl);
}

#if  defined(_WIN32) && defined(_MSC_VER)

#if  defined(_MSC_VER) && (_MSC_VER>=1500)

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list  pArgPtr;
  int32_t  iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy_s (pDest, iSizeInBytes, kpSrc, iCount);

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen_s (kpStr, iMaxlen);
}

int32_t WelsVsprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsprintf_s (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  WelsFileHandle* pFp = NULL;
  if (fopen_s (&pFp, kpFilename, kpMode) != 0) {
    return NULL;
  }

  return pFp;
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  return _ftime_s (pTp);
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm   sTimeNow;

  localtime_s (&sTimeNow, &kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, &sTimeNow);
}

#else

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsprintf (pBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strlen (kpStr); //confirmed_safe_unsafe_usage
}

int32_t WelsVsprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsprintf (pBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  return _ftime (pTp);
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif // _MSC_VER

#else  //GCC

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  return strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage
}

#if !defined(MACOS) && !defined(UNIX) && !defined(APPLE_IOS)
int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen (kpStr, iMaxlen); //confirmed_safe_unsafe_usage
}
#else
int32_t WelsStrnlen (const str_t* kpString, int32_t iMaxlen) {
  // In mac os, there is no strnlen in string.h, we can only use strlen instead of strnlen or
  // implement strnlen by ourself

#if 1
  return strlen (kpString); //confirmed_safe_unsafe_usage
#else
  const str_t* kpSrc;
  for (kpSrc = kpString; iMaxlen-- && *kpSrc != '\0'; ++kpSrc)
    return kpSrc - kpString;
#endif

}
#endif

int32_t WelsVsprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsprintf (pBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle*   pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  struct timeval  sTv;

  if (gettimeofday (&sTv, NULL)) {
    return -1;
  }

  pTp->time = sTv.tv_sec;
  pTp->millitm = (uint16_t)sTv.tv_usec / 1000;

  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif

int32_t WelsFwrite (const void_t* kpBuffer, int32_t iSize, int32_t iCount, WelsFileHandle* pFp) {
  return fwrite (kpBuffer, iSize, iCount, pFp);
}

uint16_t WelsGetMillsecond (const SWelsTime* kpTp) {
  return kpTp->millitm;
}

int32_t WelsFflush (WelsFileHandle* pFp) {
  return fflush (pFp);
}

} // namespace WelsDec
<commit_msg>Fix the old MSVC version of WelsGetTimeOfDay<commit_after>/*!
 * \copy
 *     Copyright (c)  2009-2013, Cisco Systems
 *     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.
 *
 *     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 HOLDER 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.
 *
 *
 * \file	utils.c
 *
 * \brief	common tool/function utilization
 *
 * \date	03/10/2009 Created
 *
 *************************************************************************************
 */

#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#if defined(_WIN32)
#include <windows.h>
#include <sys/types.h>
#include <sys/timeb.h>
#ifndef _MSC_VER
#include <sys/time.h>
#ifndef HAVE_STRNLEN
#define strnlen(a,b) strlen(a)
#endif //!HAVE_STRNLEN
#endif //!_MSC_VER
#else
#include <sys/time.h>
#include <sys/timeb.h>
#endif //_WIN32

#include "utils.h"
#include "macros.h"
#include "wels_const.h"
#include "cpu_core.h"
#include "decoder_context.h"
#include "crt_util_safe_x.h"	// Safe CRT routines like utils for cross platforms
#include "mem_align.h"

namespace WelsDec {

// to fill default routines
PWelsLogCallbackFunc g_pLog	= NULL;

void_t WelsLog (void_t* pPtr, int32_t iLevel, const char* kpFmt, ...) {
  va_list pVl;

  PWelsDecoderContext pCtx  = (PWelsDecoderContext)pPtr;

  va_start (pVl, kpFmt);
  g_pLog (pCtx->pTraceHandle, iLevel, kpFmt, pVl);
  va_end (pVl);
}

#if  defined(_WIN32) && defined(_MSC_VER)

#if  defined(_MSC_VER) && (_MSC_VER>=1500)

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list  pArgPtr;
  int32_t  iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy_s (pDest, iSizeInBytes, kpSrc, iCount);

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen_s (kpStr, iMaxlen);
}

int32_t WelsVsprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsprintf_s (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  WelsFileHandle* pFp = NULL;
  if (fopen_s (&pFp, kpFilename, kpMode) != 0) {
    return NULL;
  }

  return pFp;
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  return _ftime_s (pTp);
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm   sTimeNow;

  localtime_s (&sTimeNow, &kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, &sTimeNow);
}

#else

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsprintf (pBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strlen (kpStr); //confirmed_safe_unsafe_usage
}

int32_t WelsVsprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsprintf (pBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  _ftime (pTp);
  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif // _MSC_VER

#else  //GCC

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  return strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage
}

#if !defined(MACOS) && !defined(UNIX) && !defined(APPLE_IOS)
int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen (kpStr, iMaxlen); //confirmed_safe_unsafe_usage
}
#else
int32_t WelsStrnlen (const str_t* kpString, int32_t iMaxlen) {
  // In mac os, there is no strnlen in string.h, we can only use strlen instead of strnlen or
  // implement strnlen by ourself

#if 1
  return strlen (kpString); //confirmed_safe_unsafe_usage
#else
  const str_t* kpSrc;
  for (kpSrc = kpString; iMaxlen-- && *kpSrc != '\0'; ++kpSrc)
    return kpSrc - kpString;
#endif

}
#endif

int32_t WelsVsprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsprintf (pBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle*   pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  struct timeval  sTv;

  if (gettimeofday (&sTv, NULL)) {
    return -1;
  }

  pTp->time = sTv.tv_sec;
  pTp->millitm = (uint16_t)sTv.tv_usec / 1000;

  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif

int32_t WelsFwrite (const void_t* kpBuffer, int32_t iSize, int32_t iCount, WelsFileHandle* pFp) {
  return fwrite (kpBuffer, iSize, iCount, pFp);
}

uint16_t WelsGetMillsecond (const SWelsTime* kpTp) {
  return kpTp->millitm;
}

int32_t WelsFflush (WelsFileHandle* pFp) {
  return fflush (pFp);
}

} // namespace WelsDec
<|endoftext|>


<commit_before>/*
  TMP36.h - Library for reading the temperature of a TMP36.
  Created by Maurice (Mausy5043) Hendrix, FEB2015

  MIT license
*/

//#include "Arduino.h"
#include "TMP36.h"

TMP36::TMP36(int pin, int samples)
{
  _pin = pin;
  _samples = samples;
}

void TMP36::begin()
{
  // set up the pin!
  pinMode(_pin, INPUT);
  //_lastreadtime = 0;
}

float TMP36::readTemperature(void)
{
  return -0.01;
}
<commit_msg>20150217.1155<commit_after>/*
  TMP36.h - Library for reading the temperature of a TMP36.
  Created by Maurice (Mausy5043) Hendrix, FEB2015

  MIT license
*/

//#include "Arduino.h"
#include "TMP36.h"

TMP36::TMP36(int pin, int samples)
{
  _pin = pin;
  _samples = samples;
}

void TMP36::begin()
{
  // set up the pin!
  pinMode(_pin, INPUT);
  //_lastreadtime = 0;
}

float TMP36::readTemperature(void)
{
  int cntSamples;
  int sumSamples;
  float measurement;

  // *** Add up the pre-defined number of samples for Sample Averaging
  for (cntSamples = 0; cntSamples < _samples; cntSamples++) {
    sumSamples += analogRead(_pin);
    // minimum delay on analog pins is 100ms
    delay(110);
  }

  measurement = (float)sumSamples / (float)cntSamples; // Calculate avg raw value.
  measurement = map(measurement * 10, 0, 10230, 0, ref5V * 10000) * 0.0001;
  return 100 * measurement - 50.0;
}
<|endoftext|>


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

#include "xwalk/runtime/browser/android/xwalk_dev_tools_server.h"

#include "base/android/jni_string.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "content/public/browser/android/devtools_auth.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_http_handler_delegate.h"
#include "jni/XWalkDevToolsServer_jni.h"
#include "net/socket/unix_domain_socket_posix.h"

namespace {

// FIXME(girish): The frontend URL needs to be served from the domain below
// for remote debugging to work in chrome (see chrome's devtools_ui.cc).
// Currently, the chrome version is hardcoded because of this dependancy.
const char kFrontEndURL[] =
    "http://chrome-devtools-frontend.appspot.com/static/%s/devtools.html";
// TODO(girish): Get version from build system.
const char kChromeVersion[] = "28.0.1500.36";

// Delegate implementation for the devtools http handler on android. A new
// instance of this gets created each time devtools is enabled.
class XWalkDevToolsServerDelegate : public content::DevToolsHttpHandlerDelegate {
 public:
  explicit XWalkDevToolsServerDelegate() {
  }

  virtual std::string GetDiscoveryPageHTML() OVERRIDE {
    return std::string();
  }

  virtual bool BundlesFrontendResources() OVERRIDE {
    return false;
  }

  virtual base::FilePath GetDebugFrontendDir() OVERRIDE {
    return base::FilePath();
  }

  virtual std::string GetPageThumbnailData(const GURL& url) OVERRIDE {
    return std::string();
  }

  virtual content::RenderViewHost* CreateNewTarget() OVERRIDE {
    return NULL;
  }

  virtual TargetType GetTargetType(content::RenderViewHost*) OVERRIDE {
    return kTargetTypeTab;
  }

  virtual std::string GetViewDescription(content::RenderViewHost*) OVERRIDE {
    return std::string();
  }

  virtual scoped_refptr<net::StreamListenSocket> CreateSocketForTethering(
      net::StreamListenSocket::Delegate* delegate,
      std::string* name) OVERRIDE {
    return NULL;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(XWalkDevToolsServerDelegate);
};

}  // namespace

namespace xwalk {

XWalkDevToolsServer::XWalkDevToolsServer(const std::string& socket_name)
    : socket_name_(socket_name),
      protocol_handler_(NULL) {
}

XWalkDevToolsServer::~XWalkDevToolsServer() {
  Stop();
}

void XWalkDevToolsServer::Start() {
  if (protocol_handler_)
    return;

  protocol_handler_ = content::DevToolsHttpHandler::Start(
      new net::UnixDomainSocketWithAbstractNamespaceFactory(
          socket_name_,
          base::Bind(&content::CanUserConnectToDevTools)),
      base::StringPrintf(kFrontEndURL, kChromeVersion),
      new XWalkDevToolsServerDelegate());
}

void XWalkDevToolsServer::Stop() {
  if (!protocol_handler_)
    return;
  // Note that the call to Stop() below takes care of |protocol_handler_|
  // deletion.
  protocol_handler_->Stop();
  protocol_handler_ = NULL;
}

bool XWalkDevToolsServer::IsStarted() const {
  return protocol_handler_;
}

bool RegisterXWalkDevToolsServer(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

static jint InitRemoteDebugging(JNIEnv* env,
                                jobject obj,
                                jstring socketName) {
  XWalkDevToolsServer* server = new XWalkDevToolsServer(
      base::android::ConvertJavaStringToUTF8(env, socketName));
  return reinterpret_cast<jint>(server);
}

static void DestroyRemoteDebugging(JNIEnv* env, jobject obj, jint server) {
  delete reinterpret_cast<XWalkDevToolsServer*>(server);
}

static jboolean IsRemoteDebuggingEnabled(JNIEnv* env,
                                         jobject obj,
                                         jint server) {
  return reinterpret_cast<XWalkDevToolsServer*>(server)->IsStarted();
}

static void SetRemoteDebuggingEnabled(JNIEnv* env,
                                      jobject obj,
                                      jint server,
                                      jboolean enabled) {
  XWalkDevToolsServer* devtools_server = reinterpret_cast<XWalkDevToolsServer*>(server);
  if (enabled) {
    devtools_server->Start();
  } else {
    devtools_server->Stop();
  }
}

}  // namespace xwalk
<commit_msg>[Android] Allow connection from same uid to devtools server.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/android/xwalk_dev_tools_server.h"

#include <sys/types.h>
#include <unistd.h>

#include "base/android/jni_string.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "content/public/browser/android/devtools_auth.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_http_handler_delegate.h"
#include "jni/XWalkDevToolsServer_jni.h"
#include "net/socket/unix_domain_socket_posix.h"

namespace {

// FIXME(girish): The frontend URL needs to be served from the domain below
// for remote debugging to work in chrome (see chrome's devtools_ui.cc).
// Currently, the chrome version is hardcoded because of this dependancy.
const char kFrontEndURL[] =
    "http://chrome-devtools-frontend.appspot.com/static/%s/devtools.html";
// TODO(girish): Get version from build system.
const char kChromeVersion[] = "28.0.1500.36";

// Delegate implementation for the devtools http handler on android. A new
// instance of this gets created each time devtools is enabled.
class XWalkDevToolsServerDelegate : public content::DevToolsHttpHandlerDelegate {
 public:
  explicit XWalkDevToolsServerDelegate() {
  }

  virtual std::string GetDiscoveryPageHTML() OVERRIDE {
    return std::string();
  }

  virtual bool BundlesFrontendResources() OVERRIDE {
    return false;
  }

  virtual base::FilePath GetDebugFrontendDir() OVERRIDE {
    return base::FilePath();
  }

  virtual std::string GetPageThumbnailData(const GURL& url) OVERRIDE {
    return std::string();
  }

  virtual content::RenderViewHost* CreateNewTarget() OVERRIDE {
    return NULL;
  }

  virtual TargetType GetTargetType(content::RenderViewHost*) OVERRIDE {
    return kTargetTypeTab;
  }

  virtual std::string GetViewDescription(content::RenderViewHost*) OVERRIDE {
    return std::string();
  }

  virtual scoped_refptr<net::StreamListenSocket> CreateSocketForTethering(
      net::StreamListenSocket::Delegate* delegate,
      std::string* name) OVERRIDE {
    return NULL;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(XWalkDevToolsServerDelegate);
};

// Allow connection from same uid to devtools server.
// This supports the XDK usage: debug bridge wrapper connects to the devtools
// server.
static bool CanUserConnectToDevTools(uid_t uid, gid_t gid) {
  if (uid == getuid())
    return true;

  return content::CanUserConnectToDevTools(uid, gid);
}

}  // namespace

namespace xwalk {

XWalkDevToolsServer::XWalkDevToolsServer(const std::string& socket_name)
    : socket_name_(socket_name),
      protocol_handler_(NULL) {
}

XWalkDevToolsServer::~XWalkDevToolsServer() {
  Stop();
}

void XWalkDevToolsServer::Start() {
  if (protocol_handler_)
    return;

  protocol_handler_ = content::DevToolsHttpHandler::Start(
      new net::UnixDomainSocketWithAbstractNamespaceFactory(
          socket_name_,
          base::Bind(&CanUserConnectToDevTools)),
      base::StringPrintf(kFrontEndURL, kChromeVersion),
      new XWalkDevToolsServerDelegate());
}

void XWalkDevToolsServer::Stop() {
  if (!protocol_handler_)
    return;
  // Note that the call to Stop() below takes care of |protocol_handler_|
  // deletion.
  protocol_handler_->Stop();
  protocol_handler_ = NULL;
}

bool XWalkDevToolsServer::IsStarted() const {
  return protocol_handler_;
}

bool RegisterXWalkDevToolsServer(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

static jint InitRemoteDebugging(JNIEnv* env,
                                jobject obj,
                                jstring socketName) {
  XWalkDevToolsServer* server = new XWalkDevToolsServer(
      base::android::ConvertJavaStringToUTF8(env, socketName));
  return reinterpret_cast<jint>(server);
}

static void DestroyRemoteDebugging(JNIEnv* env, jobject obj, jint server) {
  delete reinterpret_cast<XWalkDevToolsServer*>(server);
}

static jboolean IsRemoteDebuggingEnabled(JNIEnv* env,
                                         jobject obj,
                                         jint server) {
  return reinterpret_cast<XWalkDevToolsServer*>(server)->IsStarted();
}

static void SetRemoteDebuggingEnabled(JNIEnv* env,
                                      jobject obj,
                                      jint server,
                                      jboolean enabled) {
  XWalkDevToolsServer* devtools_server = reinterpret_cast<XWalkDevToolsServer*>(server);
  if (enabled) {
    devtools_server->Start();
  } else {
    devtools_server->Stop();
  }
}

}  // namespace xwalk
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "random.h"

#include "Basics/threads.h"

////////////////////////////////////////////////////////////////////////////////
/// @brief already initialized
////////////////////////////////////////////////////////////////////////////////

static bool Initialized = false;

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a seed
////////////////////////////////////////////////////////////////////////////////

static unsigned long SeedRandom(void) {
  unsigned long seed;

#ifdef TRI_HAVE_GETTIMEOFDAY
  struct timeval tv;

  /* ignore result */ gettimeofday(&tv, 0);

  seed = static_cast<decltype(seed)>(tv.tv_sec);
  seed ^= static_cast<decltype(seed)>(tv.tv_usec);
#else
  seed = static_cast<decltype(seed)>(time(0));
#endif

  seed ^= static_cast<decltype(seed)>((uint32_t) TRI_CurrentProcessId() << 8);
  seed ^= static_cast<decltype(seed)>((uint32_t) TRI_CurrentProcessId() << 16);
  seed ^= static_cast<decltype(seed)>((uint32_t) TRI_CurrentProcessId() << 24);
  seed ^= static_cast<decltype(seed)>(reinterpret_cast<std::conditional<std::is_pointer<TRI_tid_t>::value, uintptr_t, uint32_t>::type>(TRI_CurrentThreadId()));

  return seed;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 16 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint16_t TRI_UInt16Random(void) {
#if RAND_MAX == 2147483647

  return TRI_random() & 0xFFFF;

#else

  uint32_t l1;
  uint32_t l2;

  l1 = TRI_random();
  l2 = TRI_random();

  return ((l1 & 0xFF) << 8) | (l2 & 0xFF);

#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 32 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint32_t TRI_UInt32Random(void) {
#if RAND_MAX == 2147483647

  uint32_t l1;
  uint32_t l2;

  l1 = (uint32_t)TRI_random();
  l2 = (uint32_t)TRI_random();

  return ((l1 & 0xFFFF) << 16) | (l2 & 0xFFFF);

#else

#ifdef _WIN32
  unsigned int number;
  auto err = rand_s(&number);
  if (err == 0) {
    return number;
  }
#endif

  uint32_t l1;
  uint32_t l2;
  uint32_t l3;
  uint32_t l4;

  l1 = TRI_random();
  l2 = TRI_random();
  l3 = TRI_random();
  l4 = TRI_random();

  return ((l1 & 0xFF) << 24) | ((l2 & 0xFF) << 16) | ((l3 & 0xFF) << 8) |
         (l4 & 0xFF);
#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief initializes the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_InitializeRandom(void) {
  if (Initialized) {
    return;
  }

  TRI_srandom(SeedRandom());

  Initialized = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief shuts down the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_ShutdownRandom(void) {
  if (!Initialized) {
    return;
  }

  Initialized = false;
}
<commit_msg>fixed compile error<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "random.h"

#include "Basics/threads.h"

////////////////////////////////////////////////////////////////////////////////
/// @brief already initialized
////////////////////////////////////////////////////////////////////////////////

static bool Initialized = false;

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a seed
////////////////////////////////////////////////////////////////////////////////

static unsigned long SeedRandom(void) {
  unsigned long seed;

#ifdef TRI_HAVE_GETTIMEOFDAY
  struct timeval tv;

  /* ignore result */ gettimeofday(&tv, 0);

  seed = static_cast<decltype(seed)>(tv.tv_sec);
  seed ^= static_cast<decltype(seed)>(tv.tv_usec);
#else
  seed = static_cast<decltype(seed)>(time(0));
#endif

  seed ^= static_cast<decltype(seed)>((uint32_t) TRI_CurrentProcessId() << 8);
  seed ^= static_cast<decltype(seed)>((uint32_t) TRI_CurrentProcessId() << 16);
  seed ^= static_cast<decltype(seed)>((uint32_t) TRI_CurrentProcessId() << 24);
  seed ^= static_cast<decltype(seed)>(reinterpret_cast<std::conditional<std::is_pointer<TRI_tid_t>::value, uintptr_t, TRI_tid_t>::type>(TRI_CurrentThreadId()));

  return seed;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 16 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint16_t TRI_UInt16Random(void) {
#if RAND_MAX == 2147483647

  return TRI_random() & 0xFFFF;

#else

  uint32_t l1;
  uint32_t l2;

  l1 = TRI_random();
  l2 = TRI_random();

  return ((l1 & 0xFF) << 8) | (l2 & 0xFF);

#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 32 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint32_t TRI_UInt32Random(void) {
#if RAND_MAX == 2147483647

  uint32_t l1;
  uint32_t l2;

  l1 = (uint32_t)TRI_random();
  l2 = (uint32_t)TRI_random();

  return ((l1 & 0xFFFF) << 16) | (l2 & 0xFFFF);

#else

#ifdef _WIN32
  unsigned int number;
  auto err = rand_s(&number);
  if (err == 0) {
    return number;
  }
#endif

  uint32_t l1;
  uint32_t l2;
  uint32_t l3;
  uint32_t l4;

  l1 = TRI_random();
  l2 = TRI_random();
  l3 = TRI_random();
  l4 = TRI_random();

  return ((l1 & 0xFF) << 24) | ((l2 & 0xFF) << 16) | ((l3 & 0xFF) << 8) |
         (l4 & 0xFF);
#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief initializes the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_InitializeRandom(void) {
  if (Initialized) {
    return;
  }

  TRI_srandom(SeedRandom());

  Initialized = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief shuts down the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_ShutdownRandom(void) {
  if (!Initialized) {
    return;
  }

  Initialized = 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 .
 */

#include <sal/main.h>

#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/awt/ImageScaleMode.hpp>

#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/button.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/imgctrl.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/graphicfilter.hxx>
#include <vcl/graph.hxx>
#include <tools/extendapplicationenvironment.hxx>
#include <tools/stream.hxx>

#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>

#include <math.h>

#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace cppu;

// Forward declaration
void Main();

SAL_IMPLEMENT_MAIN()
{
    tools::extendApplicationEnvironment();

    // create the global service-manager
    Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext();
    Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY );

    if( !xServiceManager.is() )
        Application::Abort( "Failed to bootstrap" );

    comphelper::setProcessServiceFactory( xServiceManager );

    InitVCL();
    ::Main();
    DeInitVCL();

    return 0;
}

class MyWin : public WorkWindow
{
    PushButton      m_aListButton;
    ListBox         m_aSvpBitmaps;
    ImageControl    m_aImage;
    PushButton      m_aQuitButton;
public:
                 MyWin( vcl::Window* pParent, WinBits nWinStyle );

    virtual void MouseMove( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonDown( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonUp( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void KeyInput( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void KeyUp( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
    virtual void Resize() SAL_OVERRIDE;

    virtual bool Close() SAL_OVERRIDE;

    void parseList( const OString& rList );
    OString processCommand( const OString& rCommand );

    DECL_LINK( ListHdl, Button* );
    DECL_LINK( SelectHdl, ListBox* );
    DECL_LINK( QuitHdl, Button* );
};

void Main()
{
    MyWin aMainWin( NULL, WB_STDWORK );
    aMainWin.SetText( OUString( "SvpClient" ) );
    aMainWin.Show();

    Application::Execute();
}

MyWin::MyWin( vcl::Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle ),
    m_aListButton( this, 0 ),
    m_aSvpBitmaps( this, WB_BORDER ),
    m_aImage( this, WB_BORDER ),
    m_aQuitButton( this, 0 )
{
    m_aListButton.SetPosSizePixel( Point( 10, 10 ), Size( 120, 25 ) );
    m_aListButton.SetText( OUString( "List Elements" ) );
    m_aListButton.SetClickHdl( LINK( this, MyWin, ListHdl ) );
    m_aListButton.Show();

    m_aSvpBitmaps.SetPosSizePixel( Point( 10, 40 ), Size( 150, 150 ) );
    m_aSvpBitmaps.SetSelectHdl( LINK( this, MyWin, SelectHdl ) );
    m_aSvpBitmaps.Show();

    m_aImage.SetPosSizePixel( Point( 170, 10 ), Size( 400, 400 ) );
    m_aImage.SetScaleMode( com::sun::star::awt::ImageScaleMode::NONE );
    m_aImage.Show();

    m_aQuitButton.SetPosSizePixel( Point( 10, 300 ), Size( 120,25 ) );
    m_aQuitButton.SetText( OUString( "Quit SVP server" ) );
    m_aQuitButton.SetClickHdl( LINK( this, MyWin, QuitHdl ) );
    m_aQuitButton.Show();
}

bool MyWin::Close()
{
    bool bRet = WorkWindow::Close();
    if( bRet )
        Application::Quit();
    return bRet;
}

void MyWin::parseList( const OString& rList )
{
    sal_Int32 nTokenPos = 0;
    OUString aElementType;
    m_aSvpBitmaps.Clear();
    while( nTokenPos >= 0 )
    {
        OString aLine = rList.getToken( 0, '\n', nTokenPos );
        if( ! aLine.getLength() || *aLine.getStr() == '#' )
            continue;

        if( aLine.startsWith( "ElementType: " ) )
            aElementType = OStringToOUString( aLine.copy( 13 ), RTL_TEXTENCODING_ASCII_US );
        else
        {
            OUStringBuffer aNewElement( 64 );
            aNewElement.append( aElementType );
            aNewElement.appendAscii( ": " );
            aNewElement.append( OStringToOUString( aLine, RTL_TEXTENCODING_ASCII_US ) );
            m_aSvpBitmaps.InsertEntry( aNewElement.makeStringAndClear() );
        }
    }
}

OString MyWin::processCommand( const OString& rCommand )
{
    static const char* pEnv = getenv("SVP_LISTENER_PORT");
    OStringBuffer aAnswer;
    int nPort = (pEnv && *pEnv) ? atoi(pEnv) : 8000;
    int nSocket = socket( PF_INET, SOCK_STREAM, 0 );
    if( nSocket >= 0)
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(struct sockaddr_in));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(nPort);
        addr.sin_addr.s_addr = INADDR_ANY;
        if( connect( nSocket, (const sockaddr*)&addr, sizeof(addr) ) )
        {
            perror( "SvpElementContainer: connect() failed" );
        }
        else
        {
            write( nSocket, rCommand.getStr(), rCommand.getLength() );
            write( nSocket, "\n", 1 );
            char buf[256];
            ssize_t nBytes = 0;
            do
            {
                nBytes = read( nSocket, buf, sizeof(buf) );
                aAnswer.append( buf, nBytes );
            } while( nBytes == sizeof( buf ) );
        }
        close(nSocket);
    }
    else
        perror( "SvpElementContainer: socket() failed\n" );
    return aAnswer.makeStringAndClear();
}

IMPL_LINK( MyWin, ListHdl, Button*, )
{
    parseList( processCommand( "list" ) );
    return 0;
}

IMPL_LINK( MyWin, QuitHdl, Button*, )
{
    processCommand( "quit" );
    return 0;
}

IMPL_LINK( MyWin, SelectHdl, ListBox*, )
{
    OUString aEntry = m_aSvpBitmaps.GetSelectEntry();
    sal_Int32 nPos = aEntry.indexOf( ": " );
    if( nPos != -1 )
    {
        OStringBuffer aCommand( 64 );
        aCommand.append( "get " );
        aCommand.append( OUStringToOString( aEntry.copy( nPos+2 ), RTL_TEXTENCODING_ASCII_US ) );
        OString aAnswer( processCommand( aCommand.makeStringAndClear() ) );
        SvMemoryStream aStream( aAnswer.getLength() );
        aStream.Write( aAnswer.getStr(), aAnswer.getLength() );
        aStream.Seek( STREAM_SEEK_TO_BEGIN );

        Graphic aGraphicResult;
        GraphicFilter &rFilter = GraphicFilter::GetGraphicFilter();
        rFilter.ImportGraphic( aGraphicResult, OUString("import"), aStream );

        Bitmap aBitmap = aGraphicResult.GetBitmap();

        fprintf( stderr, "got bitmap of size %ldx%ld\n",
                 sal::static_int_cast< long >(aBitmap.GetSizePixel().Width()),
                 sal::static_int_cast< long >(aBitmap.GetSizePixel().Height()));
        Size aFixedSize( aBitmap.GetSizePixel() );
        aFixedSize.Width() += 10;
        aFixedSize.Height() += 10;
        m_aImage.SetSizePixel( aFixedSize );
        m_aImage.SetImage( Image( BitmapEx( aBitmap ) ) );
    }
    return 0;
}

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );
}

void MyWin::Resize()
{
    WorkWindow::Resize();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror=unused-result<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 .
 */

#include <sal/main.h>

#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/awt/ImageScaleMode.hpp>

#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/button.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/imgctrl.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/graphicfilter.hxx>
#include <vcl/graph.hxx>
#include <tools/extendapplicationenvironment.hxx>
#include <tools/stream.hxx>

#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>

#include <math.h>

#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace cppu;

// Forward declaration
void Main();

SAL_IMPLEMENT_MAIN()
{
    tools::extendApplicationEnvironment();

    // create the global service-manager
    Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext();
    Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY );

    if( !xServiceManager.is() )
        Application::Abort( "Failed to bootstrap" );

    comphelper::setProcessServiceFactory( xServiceManager );

    InitVCL();
    ::Main();
    DeInitVCL();

    return 0;
}

class MyWin : public WorkWindow
{
    PushButton      m_aListButton;
    ListBox         m_aSvpBitmaps;
    ImageControl    m_aImage;
    PushButton      m_aQuitButton;
public:
                 MyWin( vcl::Window* pParent, WinBits nWinStyle );

    virtual void MouseMove( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonDown( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void MouseButtonUp( const MouseEvent& rMEvt ) SAL_OVERRIDE;
    virtual void KeyInput( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void KeyUp( const KeyEvent& rKEvt ) SAL_OVERRIDE;
    virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
    virtual void Resize() SAL_OVERRIDE;

    virtual bool Close() SAL_OVERRIDE;

    void parseList( const OString& rList );
    OString processCommand( const OString& rCommand );

    DECL_LINK( ListHdl, Button* );
    DECL_LINK( SelectHdl, ListBox* );
    DECL_LINK( QuitHdl, Button* );
};

void Main()
{
    MyWin aMainWin( NULL, WB_STDWORK );
    aMainWin.SetText( OUString( "SvpClient" ) );
    aMainWin.Show();

    Application::Execute();
}

MyWin::MyWin( vcl::Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle ),
    m_aListButton( this, 0 ),
    m_aSvpBitmaps( this, WB_BORDER ),
    m_aImage( this, WB_BORDER ),
    m_aQuitButton( this, 0 )
{
    m_aListButton.SetPosSizePixel( Point( 10, 10 ), Size( 120, 25 ) );
    m_aListButton.SetText( OUString( "List Elements" ) );
    m_aListButton.SetClickHdl( LINK( this, MyWin, ListHdl ) );
    m_aListButton.Show();

    m_aSvpBitmaps.SetPosSizePixel( Point( 10, 40 ), Size( 150, 150 ) );
    m_aSvpBitmaps.SetSelectHdl( LINK( this, MyWin, SelectHdl ) );
    m_aSvpBitmaps.Show();

    m_aImage.SetPosSizePixel( Point( 170, 10 ), Size( 400, 400 ) );
    m_aImage.SetScaleMode( com::sun::star::awt::ImageScaleMode::NONE );
    m_aImage.Show();

    m_aQuitButton.SetPosSizePixel( Point( 10, 300 ), Size( 120,25 ) );
    m_aQuitButton.SetText( OUString( "Quit SVP server" ) );
    m_aQuitButton.SetClickHdl( LINK( this, MyWin, QuitHdl ) );
    m_aQuitButton.Show();
}

bool MyWin::Close()
{
    bool bRet = WorkWindow::Close();
    if( bRet )
        Application::Quit();
    return bRet;
}

void MyWin::parseList( const OString& rList )
{
    sal_Int32 nTokenPos = 0;
    OUString aElementType;
    m_aSvpBitmaps.Clear();
    while( nTokenPos >= 0 )
    {
        OString aLine = rList.getToken( 0, '\n', nTokenPos );
        if( ! aLine.getLength() || *aLine.getStr() == '#' )
            continue;

        if( aLine.startsWith( "ElementType: " ) )
            aElementType = OStringToOUString( aLine.copy( 13 ), RTL_TEXTENCODING_ASCII_US );
        else
        {
            OUStringBuffer aNewElement( 64 );
            aNewElement.append( aElementType );
            aNewElement.appendAscii( ": " );
            aNewElement.append( OStringToOUString( aLine, RTL_TEXTENCODING_ASCII_US ) );
            m_aSvpBitmaps.InsertEntry( aNewElement.makeStringAndClear() );
        }
    }
}

OString MyWin::processCommand( const OString& rCommand )
{
    static const char* pEnv = getenv("SVP_LISTENER_PORT");
    OStringBuffer aAnswer;
    int nPort = (pEnv && *pEnv) ? atoi(pEnv) : 8000;
    int nSocket = socket( PF_INET, SOCK_STREAM, 0 );
    if( nSocket >= 0)
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(struct sockaddr_in));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(nPort);
        addr.sin_addr.s_addr = INADDR_ANY;
        if( connect( nSocket, (const sockaddr*)&addr, sizeof(addr) ) )
        {
            perror( "SvpElementContainer: connect() failed" );
        }
        else
        {
            ssize_t nBytes = 0;
            nBytes = write( nSocket, rCommand.getStr(), rCommand.getLength() );
            nBytes = write( nSocket, "\n", 1 );
            nBytes = 0;
            char buf[256];
            do
            {
                nBytes = read( nSocket, buf, sizeof(buf) );
                aAnswer.append( buf, nBytes );
            } while( nBytes == sizeof( buf ) );
        }
        close(nSocket);
    }
    else
        perror( "SvpElementContainer: socket() failed\n" );
    return aAnswer.makeStringAndClear();
}

IMPL_LINK( MyWin, ListHdl, Button*, )
{
    parseList( processCommand( "list" ) );
    return 0;
}

IMPL_LINK( MyWin, QuitHdl, Button*, )
{
    processCommand( "quit" );
    return 0;
}

IMPL_LINK( MyWin, SelectHdl, ListBox*, )
{
    OUString aEntry = m_aSvpBitmaps.GetSelectEntry();
    sal_Int32 nPos = aEntry.indexOf( ": " );
    if( nPos != -1 )
    {
        OStringBuffer aCommand( 64 );
        aCommand.append( "get " );
        aCommand.append( OUStringToOString( aEntry.copy( nPos+2 ), RTL_TEXTENCODING_ASCII_US ) );
        OString aAnswer( processCommand( aCommand.makeStringAndClear() ) );
        SvMemoryStream aStream( aAnswer.getLength() );
        aStream.Write( aAnswer.getStr(), aAnswer.getLength() );
        aStream.Seek( STREAM_SEEK_TO_BEGIN );

        Graphic aGraphicResult;
        GraphicFilter &rFilter = GraphicFilter::GetGraphicFilter();
        rFilter.ImportGraphic( aGraphicResult, OUString("import"), aStream );

        Bitmap aBitmap = aGraphicResult.GetBitmap();

        fprintf( stderr, "got bitmap of size %ldx%ld\n",
                 sal::static_int_cast< long >(aBitmap.GetSizePixel().Width()),
                 sal::static_int_cast< long >(aBitmap.GetSizePixel().Height()));
        Size aFixedSize( aBitmap.GetSizePixel() );
        aFixedSize.Width() += 10;
        aFixedSize.Height() += 10;
        m_aImage.SetSizePixel( aFixedSize );
        m_aImage.SetImage( Image( BitmapEx( aBitmap ) ) );
    }
    return 0;
}

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );
}

void MyWin::Resize()
{
    WorkWindow::Resize();
}

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


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief random functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "random.h"

#include "Basics/threads.h"

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief already initialised
////////////////////////////////////////////////////////////////////////////////

static bool Initialised = false;

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a seed
////////////////////////////////////////////////////////////////////////////////

static unsigned long SeedRandom (void) {
  unsigned long seed;

#ifdef TRI_HAVE_GETTIMEOFDAY
  struct timeval tv;

  /* ignore result */ gettimeofday(&tv, 0);

  seed = (unsigned long)(tv.tv_sec);
  seed ^= (unsigned long)(tv.tv_usec);
#else
  seed = (unsigned long) time(0);
#endif

  seed ^= (unsigned long)(TRI_CurrentProcessId() << 8);
  seed ^= (unsigned long)(TRI_CurrentProcessId() << 16);
  seed ^= (unsigned long)(TRI_CurrentProcessId() << 24);
  seed ^= (unsigned long)(TRI_CurrentThreadId());

  return seed;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 16 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint16_t TRI_UInt16Random (void) {
#if RAND_MAX == 2147483647

  return TRI_random() & 0xFFFF;

#else

  uint32_t l1;
  uint32_t l2;

  l1 = TRI_random();
  l2 = TRI_random();

  return ((l1 & 0xFF) << 8) | (l2 & 0xFF);

#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 32 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint32_t TRI_UInt32Random (void) {
#if RAND_MAX == 2147483647

  uint32_t l1;
  uint32_t l2;

  l1 = (uint32_t) TRI_random();
  l2 = (uint32_t) TRI_random();

  return ((l1 & 0xFFFF) << 16) | (l2 & 0xFFFF);

#else

#ifdef _WIN32
  unsigned int number;
  auto err = rand_s(&number);^
  if (err == 0) {
    return number;
  }
#endif

  uint32_t l1;
  uint32_t l2;
  uint32_t l3;
  uint32_t l4;

  l1 = TRI_random();
  l2 = TRI_random();
  l3 = TRI_random();
  l4 = TRI_random();

  return ((l1 & 0xFF) << 24) | ((l2 & 0xFF) << 16) | ((l3 & 0xFF) << 8) | (l4 & 0xFF);
#endif
}

// -----------------------------------------------------------------------------
// --SECTION--                                                            MODULE
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief initialises the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_InitialiseRandom (void) {
  if (Initialised) {
    return;
  }

  TRI_srandom(SeedRandom());

  Initialised = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief shuts down the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_ShutdownRandom (void) {
  if (! Initialised) {
    return;
  }

  Initialised = false;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Fix typo introduced by manualy editing diffs<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief random functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "random.h"

#include "Basics/threads.h"

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief already initialised
////////////////////////////////////////////////////////////////////////////////

static bool Initialised = false;

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a seed
////////////////////////////////////////////////////////////////////////////////

static unsigned long SeedRandom (void) {
  unsigned long seed;

#ifdef TRI_HAVE_GETTIMEOFDAY
  struct timeval tv;

  /* ignore result */ gettimeofday(&tv, 0);

  seed = (unsigned long)(tv.tv_sec);
  seed ^= (unsigned long)(tv.tv_usec);
#else
  seed = (unsigned long) time(0);
#endif

  seed ^= (unsigned long)(TRI_CurrentProcessId() << 8);
  seed ^= (unsigned long)(TRI_CurrentProcessId() << 16);
  seed ^= (unsigned long)(TRI_CurrentProcessId() << 24);
  seed ^= (unsigned long)(TRI_CurrentThreadId());

  return seed;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 16 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint16_t TRI_UInt16Random (void) {
#if RAND_MAX == 2147483647

  return TRI_random() & 0xFFFF;

#else

  uint32_t l1;
  uint32_t l2;

  l1 = TRI_random();
  l2 = TRI_random();

  return ((l1 & 0xFF) << 8) | (l2 & 0xFF);

#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a 32 bit random unsigned integer
////////////////////////////////////////////////////////////////////////////////

uint32_t TRI_UInt32Random (void) {
#if RAND_MAX == 2147483647

  uint32_t l1;
  uint32_t l2;

  l1 = (uint32_t) TRI_random();
  l2 = (uint32_t) TRI_random();

  return ((l1 & 0xFFFF) << 16) | (l2 & 0xFFFF);

#else

#ifdef _WIN32
  unsigned int number;
  auto err = rand_s(&number);
  if (err == 0) {
    return number;
  }
#endif

  uint32_t l1;
  uint32_t l2;
  uint32_t l3;
  uint32_t l4;

  l1 = TRI_random();
  l2 = TRI_random();
  l3 = TRI_random();
  l4 = TRI_random();

  return ((l1 & 0xFF) << 24) | ((l2 & 0xFF) << 16) | ((l3 & 0xFF) << 8) | (l4 & 0xFF);
#endif
}

// -----------------------------------------------------------------------------
// --SECTION--                                                            MODULE
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief initialises the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_InitialiseRandom (void) {
  if (Initialised) {
    return;
  }

  TRI_srandom(SeedRandom());

  Initialised = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief shuts down the random components
////////////////////////////////////////////////////////////////////////////////

void TRI_ShutdownRandom (void) {
  if (! Initialised) {
    return;
  }

  Initialised = false;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>