<commit_before>#include <ShaderReflection.h>
#include <ShaderMeta/USMShaderMeta.h>
#include <LogDelegate.h>
#include <cassert>
#include <map>
#define WIN32_LEAN_AND_MEAN
#include <d3dcompiler.h>

// StructCache stores D3D11 type to metadata index mapping, where metadata index is an index in the Out.Structs array
static bool ProcessStructure(CUSMShaderMeta& Meta, ID3D11ShaderReflectionType* pType, uint32_t StructSize, std::map<ID3D11ShaderReflectionType*, size_t>& StructCache)
{
	if (!pType) return false;

	// Already processed
	if (StructCache.find(pType) != StructCache.cend()) return true;

	D3D11_SHADER_TYPE_DESC D3DTypeDesc;
	pType->GetDesc(&D3DTypeDesc);

	// Has no members
	if (D3DTypeDesc.Members == 0) return true;

	// Add and fill new structure layout metadata
	StructCache.emplace(pType, Meta.Structs.size());
	CUSMStructMeta StructMeta;
	StructMeta.Name = D3DTypeDesc.Name ? D3DTypeDesc.Name : std::string();

	StructMeta.Members.reserve(D3DTypeDesc.Members);
	for (UINT MemberIdx = 0; MemberIdx < D3DTypeDesc.Members; ++MemberIdx)
	{
		LPCSTR pMemberName = pType->GetMemberTypeName(MemberIdx);

		ID3D11ShaderReflectionType* pMemberType = pType->GetMemberTypeByIndex(MemberIdx);
		D3D11_SHADER_TYPE_DESC D3DMemberTypeDesc;
		pMemberType->GetDesc(&D3DMemberTypeDesc);

		CUSMConstMetaBase MemberMeta;
		MemberMeta.Name = pMemberName;
		MemberMeta.Offset = D3DMemberTypeDesc.Offset;
		MemberMeta.Flags = 0;

		uint32_t MemberSize;
		if (MemberIdx + 1 < D3DTypeDesc.Members)
		{
			ID3D11ShaderReflectionType* pNextMemberType = pType->GetMemberTypeByIndex(MemberIdx + 1);
			D3D11_SHADER_TYPE_DESC D3DNextMemberTypeDesc;
			pNextMemberType->GetDesc(&D3DNextMemberTypeDesc);
			MemberSize = D3DNextMemberTypeDesc.Offset - D3DMemberTypeDesc.Offset;
		}
		else MemberSize = StructSize - D3DMemberTypeDesc.Offset;

		if (D3DMemberTypeDesc.Elements > 1)
		{
			// Arrays
			MemberMeta.ElementSize = MemberSize / D3DMemberTypeDesc.Elements;
			MemberMeta.ElementCount = D3DMemberTypeDesc.Elements;
		}
		else
		{
			// Non-arrays and arrays [1]
			MemberMeta.ElementSize = MemberSize;
			MemberMeta.ElementCount = 1;
		}

		if (D3DMemberTypeDesc.Class == D3D_SVC_STRUCT)
		{
			MemberMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
			if (!ProcessStructure(Meta, pMemberType, MemberMeta.ElementSize, StructCache)) continue;
			MemberMeta.StructIndex = StructCache[pMemberType];
		}
		else
		{
			MemberMeta.StructIndex = (uint32_t)(-1);
			switch (D3DMemberTypeDesc.Type)
			{
				case D3D_SVT_BOOL:	MemberMeta.Type = USMConst_Bool; break;
				case D3D_SVT_INT:
				case D3D_SVT_UINT:	MemberMeta.Type = USMConst_Int; break;
				case D3D_SVT_FLOAT:	MemberMeta.Type = USMConst_Float; break;
				default:
				{
					//Messages += "Unsupported constant '";
					//Messages += pMemberName;
					//Messages += "' type '";
					//Messages += std::to_string(D3DMemberTypeDesc.Type);
					//Messages += "' in a structure '";
					//Messages += (D3DTypeDesc.Name ? D3DTypeDesc.Name : "");
					//Messages += "'\n";
					return false;
				}
			}

			MemberMeta.Columns = D3DMemberTypeDesc.Columns;
			MemberMeta.Rows = D3DMemberTypeDesc.Rows;

			if (D3DMemberTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
				MemberMeta.Flags |= USMShaderConst_ColumnMajor;
		}

		StructMeta.Members.push_back(std::move(MemberMeta));
	}

	Meta.Structs.push_back(std::move(StructMeta));

	return true;
}
//---------------------------------------------------------------------

bool ExtractUSMMetaFromBinary(const void* pData, size_t Size, CUSMShaderMeta& OutMeta, uint32_t& OutMinFeatureLevel, uint64_t& OutRequiresFlags, DEMShaderCompiler::ILogDelegate* pLog)
{
	ID3D11ShaderReflection* pReflector = nullptr;
	if (FAILED(D3DReflect(pData, Size, IID_ID3D11ShaderReflection, (void**)&pReflector))) return false;

	D3D_FEATURE_LEVEL D3DFeatureLevel;
	if (FAILED(pReflector->GetMinFeatureLevel(&D3DFeatureLevel)))
	{
		pReflector->Release();
		return false;
	}

	switch (D3DFeatureLevel)
	{
		case D3D_FEATURE_LEVEL_9_1:		OutMinFeatureLevel = GPU_Level_D3D9_1; break;
		case D3D_FEATURE_LEVEL_9_2:		OutMinFeatureLevel = GPU_Level_D3D9_2; break;
		case D3D_FEATURE_LEVEL_9_3:		OutMinFeatureLevel = GPU_Level_D3D9_3; break;
		case D3D_FEATURE_LEVEL_10_0:	OutMinFeatureLevel = GPU_Level_D3D10_0; break;
		case D3D_FEATURE_LEVEL_10_1:	OutMinFeatureLevel = GPU_Level_D3D10_1; break;
		case D3D_FEATURE_LEVEL_11_0:	OutMinFeatureLevel = GPU_Level_D3D11_0; break;
		//case D3D_FEATURE_LEVEL_11_1:
		default:						OutMinFeatureLevel = GPU_Level_D3D11_1; break;
	}

	OutRequiresFlags = pReflector->GetRequiresFlags();

	D3D11_SHADER_DESC D3DDesc;
	if (FAILED(pReflector->GetDesc(&D3DDesc)))
	{
		pReflector->Release();
		return false;
	}

	std::map<ID3D11ShaderReflectionType*, size_t> StructCache;

	for (UINT RsrcIdx = 0; RsrcIdx < D3DDesc.BoundResources; ++RsrcIdx)
	{
		D3D11_SHADER_INPUT_BIND_DESC RsrcDesc;
		if (FAILED(pReflector->GetResourceBindingDesc(RsrcIdx, &RsrcDesc)))
		{
			pReflector->Release();
			return false;
		}

		// D3D_SIF_USERPACKED - may fail assertion if not set!

		switch (RsrcDesc.Type)
		{
			case D3D_SIT_TEXTURE:
			{
				CUSMRsrcMeta Meta;
				Meta.Name = RsrcDesc.Name;
				Meta.RegisterStart = RsrcDesc.BindPoint;
				Meta.RegisterCount = RsrcDesc.BindCount;

				switch (RsrcDesc.Dimension)
				{
					case D3D_SRV_DIMENSION_TEXTURE1D:			Meta.Type = USMRsrc_Texture1D; break;
					case D3D_SRV_DIMENSION_TEXTURE1DARRAY:		Meta.Type = USMRsrc_Texture1DArray; break;
					case D3D_SRV_DIMENSION_TEXTURE2D:			Meta.Type = USMRsrc_Texture2D; break;
					case D3D_SRV_DIMENSION_TEXTURE2DARRAY:		Meta.Type = USMRsrc_Texture2DArray; break;
					case D3D_SRV_DIMENSION_TEXTURE2DMS:			Meta.Type = USMRsrc_Texture2DMS; break;
					case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY:	Meta.Type = USMRsrc_Texture2DMSArray; break;
					case D3D_SRV_DIMENSION_TEXTURE3D:			Meta.Type = USMRsrc_Texture3D; break;
					case D3D_SRV_DIMENSION_TEXTURECUBE:			Meta.Type = USMRsrc_TextureCUBE; break;
					case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:	Meta.Type = USMRsrc_TextureCUBEArray; break;
					default:									Meta.Type = USMRsrc_Unknown; break;
				}

				OutMeta.Resources.push_back(std::move(Meta));

				break;
			}
			case D3D_SIT_SAMPLER:
			{
				// D3D_SIF_COMPARISON_SAMPLER
				CUSMSamplerMeta Meta;
				Meta.Name = RsrcDesc.Name;
				Meta.RegisterStart = RsrcDesc.BindPoint;
				Meta.RegisterCount = RsrcDesc.BindCount;
				OutMeta.Samplers.push_back(std::move(Meta));
				break;
			}
			case D3D_SIT_CBUFFER:
			case D3D_SIT_TBUFFER:
			case D3D_SIT_STRUCTURED:
			{
				// Can't violate this condition (can't define cbuffer / tbuffer array)
				assert(RsrcDesc.BindCount == 1);

				// There can be cbuffer and tbuffer with the same name, so search by name and type
				D3D_CBUFFER_TYPE DesiredType;
				switch (RsrcDesc.Type)
				{
					case D3D_SIT_CBUFFER:		DesiredType = D3D_CT_CBUFFER; break;
					case D3D_SIT_TBUFFER:		DesiredType = D3D_CT_TBUFFER; break;
					case D3D_SIT_STRUCTURED:	DesiredType = D3D_CT_RESOURCE_BIND_INFO; break;
				}

				ID3D11ShaderReflectionConstantBuffer* pCB = nullptr;
				D3D11_SHADER_BUFFER_DESC D3DBufDesc;
				for (size_t BufIdx = 0; BufIdx < D3DDesc.ConstantBuffers; ++BufIdx)
				{
					ID3D11ShaderReflectionConstantBuffer* pCurrCB = pReflector->GetConstantBufferByIndex(BufIdx);
					pCurrCB->GetDesc(&D3DBufDesc);
					if (!strcmp(RsrcDesc.Name, D3DBufDesc.Name) && D3DBufDesc.Type == DesiredType)
					{
						pCB = pCurrCB;
						break;
					}
				}

				if (!pCB || !D3DBufDesc.Variables) continue;

				//D3DBufDesc.uFlags & D3D_CBF_USERPACKED

				DWORD TypeMask;
				if (RsrcDesc.Type == D3D_SIT_TBUFFER) TypeMask = USMBuffer_Texture;
				else if (RsrcDesc.Type == D3D_SIT_STRUCTURED) TypeMask = USMBuffer_Structured;
				else TypeMask = 0;

				CUSMBufferMeta Meta;
				Meta.Name = RsrcDesc.Name;
				Meta.Register = (RsrcDesc.BindPoint | TypeMask);
				Meta.Size = D3DBufDesc.Size;
				OutMeta.Buffers.push_back(std::move(Meta));

				if (RsrcDesc.Type != D3D_SIT_STRUCTURED)
				{
					for (UINT VarIdx = 0; VarIdx < D3DBufDesc.Variables; ++VarIdx)
					{
						ID3D11ShaderReflectionVariable* pVar = pCB->GetVariableByIndex(VarIdx);
						if (!pVar) continue;

						D3D11_SHADER_VARIABLE_DESC D3DVarDesc;
						pVar->GetDesc(&D3DVarDesc);

						//D3D_SVF_USERPACKED             = 1,
						//D3D_SVF_USED                   = 2,

						ID3D11ShaderReflectionType* pVarType = pVar->GetType();
						if (!pVarType) continue;

						D3D11_SHADER_TYPE_DESC D3DTypeDesc;
						pVarType->GetDesc(&D3DTypeDesc);

						CUSMConstMeta ConstMeta;
						ConstMeta.Name = D3DVarDesc.Name;
						ConstMeta.BufferIndex = OutMeta.Buffers.size() - 1;
						ConstMeta.Offset = D3DVarDesc.StartOffset;
						ConstMeta.Flags = 0;

						if (D3DTypeDesc.Elements > 1)
						{
							// Arrays
							ConstMeta.ElementSize = D3DVarDesc.Size / D3DTypeDesc.Elements;
							ConstMeta.ElementCount = D3DTypeDesc.Elements;
						}
						else
						{
							// Non-arrays and arrays [1]
							ConstMeta.ElementSize = D3DVarDesc.Size;
							ConstMeta.ElementCount = 1;
						}

						if (D3DTypeDesc.Class == D3D_SVC_STRUCT)
						{
							ConstMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
							if (!ProcessStructure(OutMeta, pVarType, ConstMeta.ElementSize, StructCache)) continue;
							ConstMeta.StructIndex = StructCache[pVarType];
						}
						else
						{
							ConstMeta.StructIndex = (uint32_t)(-1);
							switch (D3DTypeDesc.Type)
							{
								case D3D_SVT_BOOL:	ConstMeta.Type = USMConst_Bool; break;
								case D3D_SVT_INT:
								case D3D_SVT_UINT:	ConstMeta.Type = USMConst_Int; break;
								case D3D_SVT_FLOAT:	ConstMeta.Type = USMConst_Float; break;
								default:
								{
									if (pLog)
										pLog->LogInfo((std::string("Unsupported constant '") + D3DVarDesc.Name + "' type '" +
											std::to_string(D3DTypeDesc.Type) + "' in USM buffer '" + RsrcDesc.Name).c_str());
									return false;
								}
							}

							ConstMeta.Columns = D3DTypeDesc.Columns;
							ConstMeta.Rows = D3DTypeDesc.Rows;

							if (D3DTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
								ConstMeta.Flags |= USMShaderConst_ColumnMajor;

							OutMeta.Consts.push_back(std::move(ConstMeta));
						}
					}
				}

				break;
			}
		}
	}

	pReflector->Release();

	return true;
}
//---------------------------------------------------------------------
<commit_msg>Minor changes<commit_after>#include <ShaderReflection.h>
#include <ShaderMeta/USMShaderMeta.h>
#include <LogDelegate.h>
#include <cassert>
#include <map>
#define WIN32_LEAN_AND_MEAN
#include <d3dcompiler.h>

// StructCache stores D3D11 type to metadata index mapping, where metadata index is an index in the Out.Structs array
static bool ProcessStructure(CUSMShaderMeta& Meta, ID3D11ShaderReflectionType* pType, uint32_t StructSize,
	std::map<ID3D11ShaderReflectionType*, size_t>& StructCache, DEMShaderCompiler::ILogDelegate* pLog)
{
	if (!pType) return false;

	// Already processed
	if (StructCache.find(pType) != StructCache.cend()) return true;

	D3D11_SHADER_TYPE_DESC D3DTypeDesc;
	pType->GetDesc(&D3DTypeDesc);

	// Has no members
	if (D3DTypeDesc.Members == 0) return true;

	// Add and fill new structure layout metadata
	StructCache.emplace(pType, Meta.Structs.size());
	CUSMStructMeta StructMeta;
	StructMeta.Name = D3DTypeDesc.Name ? D3DTypeDesc.Name : std::string();

	StructMeta.Members.reserve(D3DTypeDesc.Members);
	for (UINT MemberIdx = 0; MemberIdx < D3DTypeDesc.Members; ++MemberIdx)
	{
		LPCSTR pMemberName = pType->GetMemberTypeName(MemberIdx);

		ID3D11ShaderReflectionType* pMemberType = pType->GetMemberTypeByIndex(MemberIdx);
		D3D11_SHADER_TYPE_DESC D3DMemberTypeDesc;
		pMemberType->GetDesc(&D3DMemberTypeDesc);

		CUSMConstMetaBase MemberMeta;
		MemberMeta.Name = pMemberName;
		MemberMeta.Offset = D3DMemberTypeDesc.Offset;
		MemberMeta.Flags = 0;

		uint32_t MemberSize;
		if (MemberIdx + 1 < D3DTypeDesc.Members)
		{
			ID3D11ShaderReflectionType* pNextMemberType = pType->GetMemberTypeByIndex(MemberIdx + 1);
			D3D11_SHADER_TYPE_DESC D3DNextMemberTypeDesc;
			pNextMemberType->GetDesc(&D3DNextMemberTypeDesc);
			MemberSize = D3DNextMemberTypeDesc.Offset - D3DMemberTypeDesc.Offset;
		}
		else MemberSize = StructSize - D3DMemberTypeDesc.Offset;

		if (D3DMemberTypeDesc.Elements > 1)
		{
			// Arrays
			MemberMeta.ElementSize = MemberSize / D3DMemberTypeDesc.Elements;
			MemberMeta.ElementCount = D3DMemberTypeDesc.Elements;
		}
		else
		{
			// Non-arrays and arrays [1]
			MemberMeta.ElementSize = MemberSize;
			MemberMeta.ElementCount = 1;
		}

		if (D3DMemberTypeDesc.Class == D3D_SVC_STRUCT)
		{
			MemberMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
			if (!ProcessStructure(Meta, pMemberType, MemberMeta.ElementSize, StructCache, pLog)) continue;
			MemberMeta.StructIndex = StructCache[pMemberType];
		}
		else
		{
			MemberMeta.StructIndex = static_cast<uint32_t>(-1);
			switch (D3DMemberTypeDesc.Type)
			{
				case D3D_SVT_BOOL:	MemberMeta.Type = USMConst_Bool; break;
				case D3D_SVT_INT:
				case D3D_SVT_UINT:	MemberMeta.Type = USMConst_Int; break;
				case D3D_SVT_FLOAT:	MemberMeta.Type = USMConst_Float; break;
				default:
				{
					if (pLog)
						pLog->LogInfo((std::string("Unsupported constant '") + pMemberName + "' type '" +
							std::to_string(D3DMemberTypeDesc.Type) + "' in a structure '" + (D3DTypeDesc.Name ? D3DTypeDesc.Name : "")).c_str());
					return false;
				}
			}

			MemberMeta.Columns = D3DMemberTypeDesc.Columns;
			MemberMeta.Rows = D3DMemberTypeDesc.Rows;

			if (D3DMemberTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
				MemberMeta.Flags |= USMShaderConst_ColumnMajor;
		}

		StructMeta.Members.push_back(std::move(MemberMeta));
	}

	Meta.Structs.push_back(std::move(StructMeta));

	return true;
}
//---------------------------------------------------------------------

bool ExtractUSMMetaFromBinary(const void* pData, size_t Size, CUSMShaderMeta& OutMeta, uint32_t& OutMinFeatureLevel, uint64_t& OutRequiresFlags, DEMShaderCompiler::ILogDelegate* pLog)
{
	ID3D11ShaderReflection* pReflector = nullptr;
	if (FAILED(D3DReflect(pData, Size, IID_ID3D11ShaderReflection, (void**)&pReflector))) return false;

	D3D_FEATURE_LEVEL D3DFeatureLevel;
	if (FAILED(pReflector->GetMinFeatureLevel(&D3DFeatureLevel)))
	{
		pReflector->Release();
		return false;
	}

	switch (D3DFeatureLevel)
	{
		case D3D_FEATURE_LEVEL_9_1:		OutMinFeatureLevel = GPU_Level_D3D9_1; break;
		case D3D_FEATURE_LEVEL_9_2:		OutMinFeatureLevel = GPU_Level_D3D9_2; break;
		case D3D_FEATURE_LEVEL_9_3:		OutMinFeatureLevel = GPU_Level_D3D9_3; break;
		case D3D_FEATURE_LEVEL_10_0:	OutMinFeatureLevel = GPU_Level_D3D10_0; break;
		case D3D_FEATURE_LEVEL_10_1:	OutMinFeatureLevel = GPU_Level_D3D10_1; break;
		case D3D_FEATURE_LEVEL_11_0:	OutMinFeatureLevel = GPU_Level_D3D11_0; break;
		//case D3D_FEATURE_LEVEL_11_1:
		default:						OutMinFeatureLevel = GPU_Level_D3D11_1; break;
	}

	OutRequiresFlags = pReflector->GetRequiresFlags();

	D3D11_SHADER_DESC D3DDesc;
	if (FAILED(pReflector->GetDesc(&D3DDesc)))
	{
		pReflector->Release();
		return false;
	}

	std::map<ID3D11ShaderReflectionType*, size_t> StructCache;

	for (UINT RsrcIdx = 0; RsrcIdx < D3DDesc.BoundResources; ++RsrcIdx)
	{
		D3D11_SHADER_INPUT_BIND_DESC RsrcDesc;
		if (FAILED(pReflector->GetResourceBindingDesc(RsrcIdx, &RsrcDesc)))
		{
			pReflector->Release();
			return false;
		}

		// D3D_SIF_USERPACKED - may fail assertion if not set!

		switch (RsrcDesc.Type)
		{
			case D3D_SIT_TEXTURE:
			{
				CUSMRsrcMeta Meta;
				Meta.Name = RsrcDesc.Name;
				Meta.RegisterStart = RsrcDesc.BindPoint;
				Meta.RegisterCount = RsrcDesc.BindCount;

				switch (RsrcDesc.Dimension)
				{
					case D3D_SRV_DIMENSION_TEXTURE1D:			Meta.Type = USMRsrc_Texture1D; break;
					case D3D_SRV_DIMENSION_TEXTURE1DARRAY:		Meta.Type = USMRsrc_Texture1DArray; break;
					case D3D_SRV_DIMENSION_TEXTURE2D:			Meta.Type = USMRsrc_Texture2D; break;
					case D3D_SRV_DIMENSION_TEXTURE2DARRAY:		Meta.Type = USMRsrc_Texture2DArray; break;
					case D3D_SRV_DIMENSION_TEXTURE2DMS:			Meta.Type = USMRsrc_Texture2DMS; break;
					case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY:	Meta.Type = USMRsrc_Texture2DMSArray; break;
					case D3D_SRV_DIMENSION_TEXTURE3D:			Meta.Type = USMRsrc_Texture3D; break;
					case D3D_SRV_DIMENSION_TEXTURECUBE:			Meta.Type = USMRsrc_TextureCUBE; break;
					case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:	Meta.Type = USMRsrc_TextureCUBEArray; break;
					default:									Meta.Type = USMRsrc_Unknown; break;
				}

				OutMeta.Resources.push_back(std::move(Meta));

				break;
			}
			case D3D_SIT_SAMPLER:
			{
				// D3D_SIF_COMPARISON_SAMPLER
				CUSMSamplerMeta Meta;
				Meta.Name = RsrcDesc.Name;
				Meta.RegisterStart = RsrcDesc.BindPoint;
				Meta.RegisterCount = RsrcDesc.BindCount;
				OutMeta.Samplers.push_back(std::move(Meta));
				break;
			}
			case D3D_SIT_CBUFFER:
			case D3D_SIT_TBUFFER:
			case D3D_SIT_STRUCTURED:
			{
				// Can't violate this condition (can't define cbuffer / tbuffer array)
				assert(RsrcDesc.BindCount == 1);

				// There can be cbuffer and tbuffer with the same name, so search by name and type
				D3D_CBUFFER_TYPE DesiredType;
				switch (RsrcDesc.Type)
				{
					case D3D_SIT_CBUFFER:		DesiredType = D3D_CT_CBUFFER; break;
					case D3D_SIT_TBUFFER:		DesiredType = D3D_CT_TBUFFER; break;
					case D3D_SIT_STRUCTURED:	DesiredType = D3D_CT_RESOURCE_BIND_INFO; break;
				}

				ID3D11ShaderReflectionConstantBuffer* pCB = nullptr;
				D3D11_SHADER_BUFFER_DESC D3DBufDesc;
				for (size_t BufIdx = 0; BufIdx < D3DDesc.ConstantBuffers; ++BufIdx)
				{
					ID3D11ShaderReflectionConstantBuffer* pCurrCB = pReflector->GetConstantBufferByIndex(BufIdx);
					pCurrCB->GetDesc(&D3DBufDesc);
					if (!strcmp(RsrcDesc.Name, D3DBufDesc.Name) && D3DBufDesc.Type == DesiredType)
					{
						pCB = pCurrCB;
						break;
					}
				}

				if (!pCB || !D3DBufDesc.Variables) continue;

				//D3DBufDesc.uFlags & D3D_CBF_USERPACKED

				DWORD TypeMask;
				if (RsrcDesc.Type == D3D_SIT_TBUFFER) TypeMask = USMBuffer_Texture;
				else if (RsrcDesc.Type == D3D_SIT_STRUCTURED) TypeMask = USMBuffer_Structured;
				else TypeMask = 0;

				CUSMBufferMeta Meta;
				Meta.Name = RsrcDesc.Name;
				Meta.Register = (RsrcDesc.BindPoint | TypeMask);
				Meta.Size = D3DBufDesc.Size;
				OutMeta.Buffers.push_back(std::move(Meta));

				if (RsrcDesc.Type != D3D_SIT_STRUCTURED)
				{
					for (UINT VarIdx = 0; VarIdx < D3DBufDesc.Variables; ++VarIdx)
					{
						ID3D11ShaderReflectionVariable* pVar = pCB->GetVariableByIndex(VarIdx);
						if (!pVar) continue;

						D3D11_SHADER_VARIABLE_DESC D3DVarDesc;
						pVar->GetDesc(&D3DVarDesc);

						//D3D_SVF_USERPACKED             = 1,
						//D3D_SVF_USED                   = 2,

						ID3D11ShaderReflectionType* pVarType = pVar->GetType();
						if (!pVarType) continue;

						D3D11_SHADER_TYPE_DESC D3DTypeDesc;
						pVarType->GetDesc(&D3DTypeDesc);

						CUSMConstMeta ConstMeta;
						ConstMeta.Name = D3DVarDesc.Name;
						ConstMeta.BufferIndex = OutMeta.Buffers.size() - 1;
						ConstMeta.Offset = D3DVarDesc.StartOffset;
						ConstMeta.Flags = 0;

						if (D3DTypeDesc.Elements > 1)
						{
							// Arrays
							ConstMeta.ElementSize = D3DVarDesc.Size / D3DTypeDesc.Elements;
							ConstMeta.ElementCount = D3DTypeDesc.Elements;
						}
						else
						{
							// Non-arrays and arrays [1]
							ConstMeta.ElementSize = D3DVarDesc.Size;
							ConstMeta.ElementCount = 1;
						}

						if (D3DTypeDesc.Class == D3D_SVC_STRUCT)
						{
							ConstMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
							if (!ProcessStructure(OutMeta, pVarType, ConstMeta.ElementSize, StructCache, pLog)) continue;
							ConstMeta.StructIndex = StructCache[pVarType];
						}
						else
						{
							ConstMeta.StructIndex = static_cast<uint32_t>(-1);
							switch (D3DTypeDesc.Type)
							{
								case D3D_SVT_BOOL:	ConstMeta.Type = USMConst_Bool; break;
								case D3D_SVT_INT:
								case D3D_SVT_UINT:	ConstMeta.Type = USMConst_Int; break;
								case D3D_SVT_FLOAT:	ConstMeta.Type = USMConst_Float; break;
								default:
								{
									if (pLog)
										pLog->LogInfo((std::string("Unsupported constant '") + D3DVarDesc.Name + "' type '" +
											std::to_string(D3DTypeDesc.Type) + "' in USM buffer '" + RsrcDesc.Name).c_str());
									return false;
								}
							}

							ConstMeta.Columns = D3DTypeDesc.Columns;
							ConstMeta.Rows = D3DTypeDesc.Rows;

							if (D3DTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
								ConstMeta.Flags |= USMShaderConst_ColumnMajor;

							OutMeta.Consts.push_back(std::move(ConstMeta));
						}
					}
				}

				break;
			}
		}
	}

	pReflector->Release();

	return true;
}
//---------------------------------------------------------------------
<|endoftext|>


<commit_before>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008-2009 Appcelerator, Inc. All Rights Reserved.
 */

#include "boot.h"
#include "popup_dialog_win32.h"
#include <process.h>
#include <windows.h>
using std::wstring;

#ifndef MAX_PATH
#define MAX_PATH 512
#endif

#ifdef USE_BREAKPAD
#include "client/windows/handler/exception_handler.h"
#include "common/windows/http_upload.h"
#endif

namespace KrollBoot
{
	extern string applicationHome;
	extern string updateFile;
	extern SharedApplication app;
	extern int argc;
	extern const char** argv;

	inline void ShowError(string msg, bool fatal)
	{
		std::cerr << "Error: " << msg << std::endl;
		MessageBoxA(NULL, msg.c_str(), GetApplicationName().c_str(), MB_OK|MB_ICONERROR|MB_SYSTEMMODAL);
		if (fatal)
			exit(1);
	}

	std::string GetApplicationHomePath()
	{
		char path[MAX_PATH];
		int size = GetModuleFileNameA(GetModuleHandle(NULL), (char*)path, MAX_PATH);
		if (size>0)
		{
			path[size] = '\0';
		}
		return FileUtils::Dirname(string(path));
	}

	bool IsWindowsXP()
	{
		OSVERSIONINFO osVersion;
		osVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		::GetVersionEx(&osVersion);
		return osVersion.dwMajorVersion == 5;
	}

	void BootstrapPlatformSpecific(string path)
	{
		// Add runtime path and all module paths to PATH
		path = app->runtime->path + ";" + path;
		string currentPath = EnvironmentUtils::Get("PATH");
		if (!currentPath.empty())
		{
			path = path + ":" + currentPath;
		}
		EnvironmentUtils::Set("PATH", path);
	}

	string Blastoff()
	{
		if (!IsWindowsXP())
		{
			// Windows boot does not normally need to restart itself,  so just
			// launch the host here and exit with the appropriate return value.
			EnvironmentUtils::Unset(BOOTSTRAP_ENV);
			exit(KrollBoot::StartHost());
		}

		// TODO: Fix manual activation context setup for Windows XP so we don't need
		// to do the thing below any longer.

		// We are on Windows XP. We need to reboot ourselves, but using the kboot.exe
		// that is included with the runtime. The manifest embedded in kboot points
		// to a DLL named "WebKit.dll" relative to the exe -- we need that path to
		// resolve for registration-free COM to work.
		string allArgs;
		for (int i = 0; i < argc; i++)
		{
			string arg = argv[i];
			size_t quotePos = arg.find('\"');
			if (quotePos == string::npos)
			{
				allArgs.append("\"");
				allArgs.append(arg);
				allArgs.append("\" ");
			}
			else
			{
				allArgs.append(arg + " ");
			}
		}
		string appName = app->runtime->path + "\\kboot.exe";

		STARTUPINFOA startupInfo = {0};
		startupInfo.cb = sizeof(startupInfo);
		PROCESS_INFORMATION processInformation;

		char* applicationName = _strdup(appName.c_str());
		char* allArguments = _strdup(allArgs.c_str());
		int success = CreateProcessA(
			applicationName, allArguments,
			NULL, NULL, FALSE, 0, NULL, NULL,
			&startupInfo, &processInformation);
		free(applicationName);
		free(allArguments);

		if (success == 0)
		{
			string errorString = string("Could not bootstrap into ");
			errorString.append(appName);
			errorString.append(": ");
			errorString.append(KrollUtils::Win32Utils::QuickFormatMessage(GetLastError()));
			ShowError(errorString);
		}
		else
		{
			CloseHandle(processInformation.hThread);
			WaitForSingleObject(processInformation.hProcess, INFINITE);
			DWORD retCode;
			if (GetExitCodeProcess(processInformation.hProcess, &retCode))
			{
				exit(retCode);
			}
			return "Could not retrieve the exit code.";
		}
	}

	typedef int Executor(HINSTANCE, int, const char **);
	int StartHost()
	{
		string runtimePath = EnvironmentUtils::Get("KR_RUNTIME");
		std::string khost = FileUtils::Join(runtimePath.c_str(), "khost.dll", NULL);

		// now we need to load the host and get 'er booted
		if (!FileUtils::IsFile(khost))
		{
			ShowError(string("Couldn't find required file: ") + khost);
			return __LINE__;
		}

		HMODULE dll = LoadLibraryA(khost.c_str());
		if (!dll)
		{
			char msg[MAX_PATH];
			sprintf_s(msg,"Couldn't load file: %s, error: %d", khost.c_str(), GetLastError());
			ShowError(msg);
			return __LINE__;
		}
		Executor *executor = (Executor*)GetProcAddress(dll, "Execute");
		if (!executor)
		{
			ShowError(string("Invalid entry point for") + khost);
			return __LINE__;
		}

		return executor(::GetModuleHandle(NULL), argc,(const char**)argv);
	}

	bool RunInstaller(vector<SharedDependency> missing, bool forceInstall)
	{
		string exec = FileUtils::Join(
			app->path.c_str(), "installer", "Installer.exe", NULL);
		if (!FileUtils::IsFile(exec))
		{
			ShowError("Missing installer and application has additional modules that are needed.");
			return false;
		}
		bool result = BootUtils::RunInstaller(missing, app, updateFile, "", false, forceInstall);

		// Ugh. Now we need to figure out where the app installer installed
		// to. We would normally use stdout, but we had to execute with
		// an expensive call to ShellExecuteEx, so we're just going to read
		// the information from a file.
		if (!app->IsInstalled())
		{
			string installedToFile = FileUtils::Join(app->GetDataPath().c_str(), ".installedto", NULL);
			// The user probably cancelled -- don't show an error
			if (!FileUtils::IsFile(installedToFile))
				return true;

			std::ifstream file(installedToFile.c_str());
			if (file.bad() || file.fail() || file.eof())
			{
				DeleteFileA(installedToFile.c_str());
				ShowError("Could not determine where installer installed application.");
				return false; // Don't show further errors
			}
			string appInstallPath;
			std::getline(file, appInstallPath);
			appInstallPath = FileUtils::Trim(appInstallPath);

			SharedApplication newapp = Application::NewApplication(appInstallPath);
			if (newapp.isNull())
			{
				return false; // Don't show further errors
			}
			else
			{
				app = newapp;
			}
			DeleteFileA(installedToFile.c_str());
		}
		return result;
	}

	string GetApplicationName()
	{
		if (!app.isNull())
		{
			return app->name.c_str();
		}
		return PRODUCT_NAME;
	}

#ifdef USE_BREAKPAD
	static google_breakpad::ExceptionHandler* breakpad;
	extern string dumpFilePath;

	char breakpadCallBuffer[MAX_PATH];
	bool HandleCrash(
		const wchar_t* dumpPath,
		const wchar_t* id,
		void* context,
		EXCEPTION_POINTERS* exinfo,
		MDRawAssertionInfo* assertion,
		bool succeeded)
	{
		if (succeeded)
		{
			STARTUPINFOA startupInfo = {0};
			startupInfo.cb = sizeof(startupInfo);
			PROCESS_INFORMATION processInformation;

			_snprintf_s(breakpadCallBuffer, MAX_PATH, MAX_PATH - 1,
				 "\"%s\" \"%s\" %S %S", argv[0], CRASH_REPORT_OPT, dumpPath, id);

			CreateProcessA(
				NULL,
				breakpadCallBuffer,
				NULL,
				NULL,
				FALSE,
				0,
				NULL,
				NULL,
				&startupInfo,
				&processInformation);
		}

		// We would not normally need to do this, but on Windows XP it
		// seems that this callback is called multiple times for a crash.
		// We should probably try to remove the following line the next
		// time we update breakpad.
		exit(__LINE__);
		return true;
	}

	wstring StringToWString(string in)
	{
		wstring out(in.length(), L' ');
		copy(in.begin(), in.end(), out.begin());
		return out;
	}

	map<wstring, wstring> GetCrashReportParametersW()
	{
		map<wstring, wstring> paramsW;
		map<string, string> params = GetCrashReportParameters();
		map<string, string>::iterator i = params.begin();
		while (i != params.end())
		{
			wstring key = StringToWString(i->first);
			wstring val = StringToWString(i->second);
			i++;

			paramsW[key] = val;
		}
		return paramsW;
	}

	int SendCrashReport()
	{
		InitCrashDetection();
		std::string title = GetCrashDetectionTitle();
		std::string msg = GetCrashDetectionHeader();
		msg.append("\n\n");
		msg.append(GetCrashDetectionMessage());

		Win32PopupDialog popupDialog(NULL);
		popupDialog.SetTitle(title);
		popupDialog.SetMessage(msg);
		popupDialog.SetShowCancelButton(true);
		if (popupDialog.Show() != IDYES)
		{
			return __LINE__;
		}

		wstring url = L"https://";
		url += StringToWString(CRASH_REPORT_URL);

		const std::map<wstring, wstring> parameters = GetCrashReportParametersW();
		wstring dumpFilePathW = StringToWString(dumpFilePath);
		wstring responseBody;
		int responseCode;

		bool success = google_breakpad::HTTPUpload::SendRequest(
			url,
			parameters,
			dumpFilePathW.c_str(),
			L"dump",
			NULL,
			&responseBody,
			&responseCode);

		if (!success)
		{
#ifdef DEBUG
			ShowError("Error uploading crash dump.");
#endif
			return __LINE__;
		}
#ifdef DEBUG
		else
		{
			MessageBoxW(NULL,L"Your crash report has been submitted. Thank You!",L"Error Reporting Status",MB_OK | MB_ICONINFORMATION);
		}
#endif
		return 0;
	}
#endif
}

#if defined(OS_WIN32) && !defined(WIN32_CONSOLE)
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR command_line, int)
#else
int main(int __argc, const char* __argv[])
#endif
{
	KrollBoot::argc = __argc;
	KrollBoot::argv = (const char**) __argv;

#ifdef USE_BREAKPAD
	// Don't install a handler if we are just handling an error.
	if (__argc > 2 && !strcmp(CRASH_REPORT_OPT, __argv[1]))
	{
		return KrollBoot::SendCrashReport();
	}

	wchar_t tempPath[MAX_PATH];
	GetTempPathW(MAX_PATH, tempPath);
	KrollBoot::breakpad = new google_breakpad::ExceptionHandler(
		tempPath,
		NULL,
		KrollBoot::HandleCrash,
		NULL,
		google_breakpad::ExceptionHandler::HANDLER_ALL);
#endif

	// Only Windows XP systems will need to restart the host.
	if (EnvironmentUtils::Has(BOOTSTRAP_ENV))
	{
			EnvironmentUtils::Unset(BOOTSTRAP_ENV);
			return KrollBoot::StartHost();
	}
	else
	{
		return KrollBoot::Bootstrap();
	}
}
<commit_msg>use QuickFormatMessage when khost.dll fails to load<commit_after>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008-2009 Appcelerator, Inc. All Rights Reserved.
 */

#include "boot.h"
#include "popup_dialog_win32.h"
#include <process.h>
#include <windows.h>
using std::wstring;

#ifndef MAX_PATH
#define MAX_PATH 512
#endif

#ifdef USE_BREAKPAD
#include "client/windows/handler/exception_handler.h"
#include "common/windows/http_upload.h"
#endif

namespace KrollBoot
{
	extern string applicationHome;
	extern string updateFile;
	extern SharedApplication app;
	extern int argc;
	extern const char** argv;

	inline void ShowError(string msg, bool fatal)
	{
		std::cerr << "Error: " << msg << std::endl;
		MessageBoxA(NULL, msg.c_str(), GetApplicationName().c_str(), MB_OK|MB_ICONERROR|MB_SYSTEMMODAL);
		if (fatal)
			exit(1);
	}

	std::string GetApplicationHomePath()
	{
		char path[MAX_PATH];
		int size = GetModuleFileNameA(GetModuleHandle(NULL), (char*)path, MAX_PATH);
		if (size>0)
		{
			path[size] = '\0';
		}
		return FileUtils::Dirname(string(path));
	}

	bool IsWindowsXP()
	{
		OSVERSIONINFO osVersion;
		osVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		::GetVersionEx(&osVersion);
		return osVersion.dwMajorVersion == 5;
	}

	void BootstrapPlatformSpecific(string path)
	{
		// Add runtime path and all module paths to PATH
		path = app->runtime->path + ";" + path;
		string currentPath = EnvironmentUtils::Get("PATH");
		if (!currentPath.empty())
		{
			path = path + ":" + currentPath;
		}
		EnvironmentUtils::Set("PATH", path);
	}

	string Blastoff()
	{
		if (!IsWindowsXP())
		{
			// Windows boot does not normally need to restart itself,  so just
			// launch the host here and exit with the appropriate return value.
			EnvironmentUtils::Unset(BOOTSTRAP_ENV);
			exit(KrollBoot::StartHost());
		}

		// TODO: Fix manual activation context setup for Windows XP so we don't need
		// to do the thing below any longer.

		// We are on Windows XP. We need to reboot ourselves, but using the kboot.exe
		// that is included with the runtime. The manifest embedded in kboot points
		// to a DLL named "WebKit.dll" relative to the exe -- we need that path to
		// resolve for registration-free COM to work.
		string allArgs;
		for (int i = 0; i < argc; i++)
		{
			string arg = argv[i];
			size_t quotePos = arg.find('\"');
			if (quotePos == string::npos)
			{
				allArgs.append("\"");
				allArgs.append(arg);
				allArgs.append("\" ");
			}
			else
			{
				allArgs.append(arg + " ");
			}
		}
		string appName = app->runtime->path + "\\kboot.exe";

		STARTUPINFOA startupInfo = {0};
		startupInfo.cb = sizeof(startupInfo);
		PROCESS_INFORMATION processInformation;

		char* applicationName = _strdup(appName.c_str());
		char* allArguments = _strdup(allArgs.c_str());
		int success = CreateProcessA(
			applicationName, allArguments,
			NULL, NULL, FALSE, 0, NULL, NULL,
			&startupInfo, &processInformation);
		free(applicationName);
		free(allArguments);

		if (success == 0)
		{
			string errorString = string("Could not bootstrap into ");
			errorString.append(appName);
			errorString.append(": ");
			errorString.append(KrollUtils::Win32Utils::QuickFormatMessage(GetLastError()));
			ShowError(errorString);
		}
		else
		{
			CloseHandle(processInformation.hThread);
			WaitForSingleObject(processInformation.hProcess, INFINITE);
			DWORD retCode;
			if (GetExitCodeProcess(processInformation.hProcess, &retCode))
			{
				exit(retCode);
			}
			return "Could not retrieve the exit code.";
		}
	}

	typedef int Executor(HINSTANCE, int, const char **);
	int StartHost()
	{
		string runtimePath = EnvironmentUtils::Get("KR_RUNTIME");
		std::string khost = FileUtils::Join(runtimePath.c_str(), "khost.dll", NULL);

		// now we need to load the host and get 'er booted
		if (!FileUtils::IsFile(khost))
		{
			ShowError(string("Couldn't find required file: ") + khost);
			return __LINE__;
		}

		HMODULE dll = LoadLibraryA(khost.c_str());
		if (!dll)
		{
			char msg[MAX_PATH];
	 		sprintf_s(msg,"Couldn't load file: %s, error: %s", khost.c_str(),
				KrollUtils::Win32Utils::QuickFormatMessage(GetLastError()).c_str());

			ShowError(msg);
			return __LINE__;
		}
		Executor *executor = (Executor*)GetProcAddress(dll, "Execute");
		if (!executor)
		{
			ShowError(string("Invalid entry point for") + khost);
			return __LINE__;
		}

		return executor(::GetModuleHandle(NULL), argc,(const char**)argv);
	}

	bool RunInstaller(vector<SharedDependency> missing, bool forceInstall)
	{
		string exec = FileUtils::Join(
			app->path.c_str(), "installer", "Installer.exe", NULL);
		if (!FileUtils::IsFile(exec))
		{
			ShowError("Missing installer and application has additional modules that are needed.");
			return false;
		}
		bool result = BootUtils::RunInstaller(missing, app, updateFile, "", false, forceInstall);

		// Ugh. Now we need to figure out where the app installer installed
		// to. We would normally use stdout, but we had to execute with
		// an expensive call to ShellExecuteEx, so we're just going to read
		// the information from a file.
		if (!app->IsInstalled())
		{
			string installedToFile = FileUtils::Join(app->GetDataPath().c_str(), ".installedto", NULL);
			// The user probably cancelled -- don't show an error
			if (!FileUtils::IsFile(installedToFile))
				return true;

			std::ifstream file(installedToFile.c_str());
			if (file.bad() || file.fail() || file.eof())
			{
				DeleteFileA(installedToFile.c_str());
				ShowError("Could not determine where installer installed application.");
				return false; // Don't show further errors
			}
			string appInstallPath;
			std::getline(file, appInstallPath);
			appInstallPath = FileUtils::Trim(appInstallPath);

			SharedApplication newapp = Application::NewApplication(appInstallPath);
			if (newapp.isNull())
			{
				return false; // Don't show further errors
			}
			else
			{
				app = newapp;
			}
			DeleteFileA(installedToFile.c_str());
		}
		return result;
	}

	string GetApplicationName()
	{
		if (!app.isNull())
		{
			return app->name.c_str();
		}
		return PRODUCT_NAME;
	}

#ifdef USE_BREAKPAD
	static google_breakpad::ExceptionHandler* breakpad;
	extern string dumpFilePath;

	char breakpadCallBuffer[MAX_PATH];
	bool HandleCrash(
		const wchar_t* dumpPath,
		const wchar_t* id,
		void* context,
		EXCEPTION_POINTERS* exinfo,
		MDRawAssertionInfo* assertion,
		bool succeeded)
	{
		if (succeeded)
		{
			STARTUPINFOA startupInfo = {0};
			startupInfo.cb = sizeof(startupInfo);
			PROCESS_INFORMATION processInformation;

			_snprintf_s(breakpadCallBuffer, MAX_PATH, MAX_PATH - 1,
				 "\"%s\" \"%s\" %S %S", argv[0], CRASH_REPORT_OPT, dumpPath, id);

			CreateProcessA(
				NULL,
				breakpadCallBuffer,
				NULL,
				NULL,
				FALSE,
				0,
				NULL,
				NULL,
				&startupInfo,
				&processInformation);
		}

		// We would not normally need to do this, but on Windows XP it
		// seems that this callback is called multiple times for a crash.
		// We should probably try to remove the following line the next
		// time we update breakpad.
		exit(__LINE__);
		return true;
	}

	wstring StringToWString(string in)
	{
		wstring out(in.length(), L' ');
		copy(in.begin(), in.end(), out.begin());
		return out;
	}

	map<wstring, wstring> GetCrashReportParametersW()
	{
		map<wstring, wstring> paramsW;
		map<string, string> params = GetCrashReportParameters();
		map<string, string>::iterator i = params.begin();
		while (i != params.end())
		{
			wstring key = StringToWString(i->first);
			wstring val = StringToWString(i->second);
			i++;

			paramsW[key] = val;
		}
		return paramsW;
	}

	int SendCrashReport()
	{
		InitCrashDetection();
		std::string title = GetCrashDetectionTitle();
		std::string msg = GetCrashDetectionHeader();
		msg.append("\n\n");
		msg.append(GetCrashDetectionMessage());

		Win32PopupDialog popupDialog(NULL);
		popupDialog.SetTitle(title);
		popupDialog.SetMessage(msg);
		popupDialog.SetShowCancelButton(true);
		if (popupDialog.Show() != IDYES)
		{
			return __LINE__;
		}

		wstring url = L"https://";
		url += StringToWString(CRASH_REPORT_URL);

		const std::map<wstring, wstring> parameters = GetCrashReportParametersW();
		wstring dumpFilePathW = StringToWString(dumpFilePath);
		wstring responseBody;
		int responseCode;

		bool success = google_breakpad::HTTPUpload::SendRequest(
			url,
			parameters,
			dumpFilePathW.c_str(),
			L"dump",
			NULL,
			&responseBody,
			&responseCode);

		if (!success)
		{
#ifdef DEBUG
			ShowError("Error uploading crash dump.");
#endif
			return __LINE__;
		}
#ifdef DEBUG
		else
		{
			MessageBoxW(NULL,L"Your crash report has been submitted. Thank You!",L"Error Reporting Status",MB_OK | MB_ICONINFORMATION);
		}
#endif
		return 0;
	}
#endif
}

#if defined(OS_WIN32) && !defined(WIN32_CONSOLE)
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR command_line, int)
#else
int main(int __argc, const char* __argv[])
#endif
{
	KrollBoot::argc = __argc;
	KrollBoot::argv = (const char**) __argv;

#ifdef USE_BREAKPAD
	// Don't install a handler if we are just handling an error.
	if (__argc > 2 && !strcmp(CRASH_REPORT_OPT, __argv[1]))
	{
		return KrollBoot::SendCrashReport();
	}

	wchar_t tempPath[MAX_PATH];
	GetTempPathW(MAX_PATH, tempPath);
	KrollBoot::breakpad = new google_breakpad::ExceptionHandler(
		tempPath,
		NULL,
		KrollBoot::HandleCrash,
		NULL,
		google_breakpad::ExceptionHandler::HANDLER_ALL);
#endif

	// Only Windows XP systems will need to restart the host.
	if (EnvironmentUtils::Has(BOOTSTRAP_ENV))
	{
			EnvironmentUtils::Unset(BOOTSTRAP_ENV);
			return KrollBoot::StartHost();
	}
	else
	{
		return KrollBoot::Bootstrap();
	}
}
<|endoftext|>


<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ inlcludes

// Local includes
#include "fe.h"
#include "elem.h"

template <>
Real FE<0,LAGRANGE>::shape(const ElemType,
			   const Order,
			   const unsigned int i,
			   const Point&)
{
  libmesh_assert (i < 1);
  return 1.;
}

template <>
Real FE<0,LAGRANGE>::shape(const Elem*,
			   const Order,
			   const unsigned int i,
			   const Point&)
{
  libmesh_assert (i < 1);
  return 1.;
}

template <>
Real FE<0,LAGRANGE>::shape_deriv(const ElemType,
				 const Order,
				 const unsigned int,
				 const unsigned int,
				 const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}

template <>
Real FE<0,LAGRANGE>::shape_deriv(const Elem*,
				 const Order,
				 const unsigned int,
				 const unsigned int,
				 const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}

template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const ElemType,
					const Order,
					const unsigned int,
					const unsigned int,
					const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}

template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const Elem*,
				        const Order,
				        const unsigned int,
				        const unsigned int,
				        const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}
<commit_msg>comment typo fix<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "fe.h"
#include "elem.h"

template <>
Real FE<0,LAGRANGE>::shape(const ElemType,
			   const Order,
			   const unsigned int i,
			   const Point&)
{
  libmesh_assert (i < 1);
  return 1.;
}

template <>
Real FE<0,LAGRANGE>::shape(const Elem*,
			   const Order,
			   const unsigned int i,
			   const Point&)
{
  libmesh_assert (i < 1);
  return 1.;
}

template <>
Real FE<0,LAGRANGE>::shape_deriv(const ElemType,
				 const Order,
				 const unsigned int,
				 const unsigned int,
				 const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}

template <>
Real FE<0,LAGRANGE>::shape_deriv(const Elem*,
				 const Order,
				 const unsigned int,
				 const unsigned int,
				 const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}

template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const ElemType,
					const Order,
					const unsigned int,
					const unsigned int,
					const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}

template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const Elem*,
				        const Order,
				        const unsigned int,
				        const unsigned int,
				        const Point&)
{
  // No spatial derivatives in 0D!
  libmesh_error();
  return 0.;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/visualization/software-license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "GaussianDistribution.h"

#include <cmath>

#include "boost/math/distributions/normal.hpp"

namespace madai {

struct GaussianDistribution::GaussianDistributionPrivate {
  /** Underlying class from Boost library that computes the things we want. */
  boost::math::normal m_InternalDistribution;
  GaussianDistributionPrivate(double mean, double standardDeviation);
};

GaussianDistribution::GaussianDistributionPrivate
::GaussianDistributionPrivate(double mean, double standardDeviation) :
  m_InternalDistribution(mean, standardDeviation)
{
}

GaussianDistribution
::GaussianDistribution() :
  m_Mean( 0.0 ),
  m_StandardDeviation( 1.0 ),
  m_GaussianDistributionImplementation(
      new GaussianDistribution::GaussianDistributionPrivate(
          m_Mean, m_StandardDeviation))
{
}

GaussianDistribution
::~GaussianDistribution()
{
  delete m_GaussianDistributionImplementation;
}

Distribution *
GaussianDistribution
::Clone() const
{
  GaussianDistribution * d = new GaussianDistribution();
  d->SetMean(this->GetMean());
  d->SetStandardDeviation(this->GetStandardDeviation());
  return d;
}

void
GaussianDistribution
::SetMean( double mean )
{
  m_Mean = mean;

  delete m_GaussianDistributionImplementation;
  m_GaussianDistributionImplementation =
    new GaussianDistribution::GaussianDistributionPrivate(
        m_Mean, m_StandardDeviation);
}

double
GaussianDistribution
::GetMean() const
{
  return m_Mean;
}

void
GaussianDistribution
::SetStandardDeviation( double standardDeviation )
{
  m_StandardDeviation = standardDeviation;

  delete m_GaussianDistributionImplementation;
  m_GaussianDistributionImplementation =
    new GaussianDistribution::GaussianDistributionPrivate(
        m_Mean, m_StandardDeviation);
}

double
GaussianDistribution
::GetStandardDeviation() const
{
  return m_StandardDeviation;
}

double
GaussianDistribution
::GetLogProbabilityDensity( double x ) const
{
  return log( this->GetNormalizationFactor() ) + this->GetExponent( x );
}

double
GaussianDistribution
::GetGradientLogProbabilityDensity( double x ) const
{
  double diff = x - m_Mean;
  double variance = m_StandardDeviation * m_StandardDeviation;
  return ( - diff / variance );
}

double
GaussianDistribution
::GetProbabilityDensity( double x ) const
{
  //return this->GetNormalizationFactor() * exp( this->GetExponent( x ) );
  return boost::math::pdf(
      m_GaussianDistributionImplementation->m_InternalDistribution, x );
}

double
GaussianDistribution
::GetPercentile( double percentile ) const
{
  return boost::math::quantile(
      m_GaussianDistributionImplementation->m_InternalDistribution,
      percentile );
}

double
GaussianDistribution
::GetSample(madai::Random & r) const
{
  return r.Gaussian(this->m_Mean, this->m_StandardDeviation);
}

double
GaussianDistribution
::GetNormalizationFactor() const
{
  double variance = m_StandardDeviation * m_StandardDeviation;

  return (1.0 / sqrt( 2.0 * M_PI * variance ) );
}

double
GaussianDistribution
::GetExponent( double x ) const
{
  double variance = m_StandardDeviation * m_StandardDeviation;
  double exponent = -( x - m_Mean ) * ( x - m_Mean ) / ( 2.0 * variance );

  return exponent;
}

double
GaussianDistribution
::GetExpectedValue() const
{
  return m_Mean;
}

} // end namespace madai
<commit_msg>Enabled defintion of M_PI by defining _USE_MATH_DEFINES<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/visualization/software-license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "GaussianDistribution.h"

#define _USE_MATH_DEFINES // Needed for M_PI to be defined on Windows
#include <cmath>
#undef _USE_MATH_DEFINES

#include "boost/math/distributions/normal.hpp"

namespace madai {

struct GaussianDistribution::GaussianDistributionPrivate {
  /** Underlying class from Boost library that computes the things we want. */
  boost::math::normal m_InternalDistribution;
  GaussianDistributionPrivate(double mean, double standardDeviation);
};

GaussianDistribution::GaussianDistributionPrivate
::GaussianDistributionPrivate(double mean, double standardDeviation) :
  m_InternalDistribution(mean, standardDeviation)
{
}

GaussianDistribution
::GaussianDistribution() :
  m_Mean( 0.0 ),
  m_StandardDeviation( 1.0 ),
  m_GaussianDistributionImplementation(
      new GaussianDistribution::GaussianDistributionPrivate(
          m_Mean, m_StandardDeviation))
{
}

GaussianDistribution
::~GaussianDistribution()
{
  delete m_GaussianDistributionImplementation;
}

Distribution *
GaussianDistribution
::Clone() const
{
  GaussianDistribution * d = new GaussianDistribution();
  d->SetMean(this->GetMean());
  d->SetStandardDeviation(this->GetStandardDeviation());
  return d;
}

void
GaussianDistribution
::SetMean( double mean )
{
  m_Mean = mean;

  delete m_GaussianDistributionImplementation;
  m_GaussianDistributionImplementation =
    new GaussianDistribution::GaussianDistributionPrivate(
        m_Mean, m_StandardDeviation);
}

double
GaussianDistribution
::GetMean() const
{
  return m_Mean;
}

void
GaussianDistribution
::SetStandardDeviation( double standardDeviation )
{
  m_StandardDeviation = standardDeviation;

  delete m_GaussianDistributionImplementation;
  m_GaussianDistributionImplementation =
    new GaussianDistribution::GaussianDistributionPrivate(
        m_Mean, m_StandardDeviation);
}

double
GaussianDistribution
::GetStandardDeviation() const
{
  return m_StandardDeviation;
}

double
GaussianDistribution
::GetLogProbabilityDensity( double x ) const
{
  return log( this->GetNormalizationFactor() ) + this->GetExponent( x );
}

double
GaussianDistribution
::GetGradientLogProbabilityDensity( double x ) const
{
  double diff = x - m_Mean;
  double variance = m_StandardDeviation * m_StandardDeviation;
  return ( - diff / variance );
}

double
GaussianDistribution
::GetProbabilityDensity( double x ) const
{
  //return this->GetNormalizationFactor() * exp( this->GetExponent( x ) );
  return boost::math::pdf(
      m_GaussianDistributionImplementation->m_InternalDistribution, x );
}

double
GaussianDistribution
::GetPercentile( double percentile ) const
{
  return boost::math::quantile(
      m_GaussianDistributionImplementation->m_InternalDistribution,
      percentile );
}

double
GaussianDistribution
::GetSample(madai::Random & r) const
{
  return r.Gaussian(this->m_Mean, this->m_StandardDeviation);
}

double
GaussianDistribution
::GetNormalizationFactor() const
{
  double variance = m_StandardDeviation * m_StandardDeviation;

  return (1.0 / sqrt( 2.0 * M_PI * variance ) );
}

double
GaussianDistribution
::GetExponent( double x ) const
{
  double variance = m_StandardDeviation * m_StandardDeviation;
  double exponent = -( x - m_Mean ) * ( x - m_Mean ) / ( 2.0 * variance );

  return exponent;
}

double
GaussianDistribution
::GetExpectedValue() const
{
  return m_Mean;
}

} // end namespace madai
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "webkit/tools/test_shell/test_shell_webmimeregistry_impl.h"

#include "base/string_util.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"

using WebKit::WebString;
using WebKit::WebMimeRegistry;

namespace {

// Convert a WebString to ASCII, falling back on an empty string in the case
// of a non-ASCII string.
std::string ToASCIIOrEmpty(const WebString& string) {
  if (!IsStringASCII(string))
    return std::string();
  return UTF16ToASCII(string);
}

}  // namespace

TestShellWebMimeRegistryImpl::TestShellWebMimeRegistryImpl() {
  media_map_.insert("video/ogg");
  media_map_.insert("audio/ogg");
  media_map_.insert("application/ogg");

  codecs_map_.insert("theora");
  codecs_map_.insert("vorbis");
}

WebMimeRegistry::SupportsType
TestShellWebMimeRegistryImpl::supportsMediaMIMEType(
    const WebString& mime_type, const WebString& codecs) {
  // Not supporting the container is a flat-out no.
  if (!IsSupportedMediaMimeType(ToASCIIOrEmpty(mime_type).c_str()))
    return IsNotSupported;

  // If we don't recognize the codec, it's possible we support it.
  std::vector<std::string> parsed_codecs;
  net::ParseCodecString(ToASCIIOrEmpty(codecs).c_str(), &parsed_codecs, true);
  if (!AreSupportedMediaCodecs(parsed_codecs))
    return MayBeSupported;

  // Otherwise we have a perfect match.
  return IsSupported;
}

bool TestShellWebMimeRegistryImpl::IsSupportedMediaMimeType(
    const std::string& mime_type) {
  return media_map_.find(mime_type) != media_map_.end();
}

bool TestShellWebMimeRegistryImpl::AreSupportedMediaCodecs(
    const std::vector<std::string>& codecs) {
  for (size_t i = 0; i < codecs.size(); ++i) {
    if (codecs_map_.find(codecs[i]) == codecs_map_.end()) {
      return false;
    }
  }
  return true;
}
<commit_msg>Add audio/wav and audio/x-wav to TestShellWebMimeRegistryImpl.<commit_after>// Copyright (c) 2010 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 "webkit/tools/test_shell/test_shell_webmimeregistry_impl.h"

#include "base/string_util.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"

using WebKit::WebString;
using WebKit::WebMimeRegistry;

namespace {

// Convert a WebString to ASCII, falling back on an empty string in the case
// of a non-ASCII string.
std::string ToASCIIOrEmpty(const WebString& string) {
  if (!IsStringASCII(string))
    return std::string();
  return UTF16ToASCII(string);
}

}  // namespace

TestShellWebMimeRegistryImpl::TestShellWebMimeRegistryImpl() {
  // Claim we support Ogg+Theora/Vorbis.
  media_map_.insert("video/ogg");
  media_map_.insert("audio/ogg");
  media_map_.insert("application/ogg");
  codecs_map_.insert("theora");
  codecs_map_.insert("vorbis");

  // Claim we support WAV.
  media_map_.insert("audio/wav");
  media_map_.insert("audio/x-wav");
  codecs_map_.insert("1");  // PCM for WAV.
}

WebMimeRegistry::SupportsType
TestShellWebMimeRegistryImpl::supportsMediaMIMEType(
    const WebString& mime_type, const WebString& codecs) {
  // Not supporting the container is a flat-out no.
  if (!IsSupportedMediaMimeType(ToASCIIOrEmpty(mime_type).c_str()))
    return IsNotSupported;

  // If we don't recognize the codec, it's possible we support it.
  std::vector<std::string> parsed_codecs;
  net::ParseCodecString(ToASCIIOrEmpty(codecs).c_str(), &parsed_codecs, true);
  if (!AreSupportedMediaCodecs(parsed_codecs))
    return MayBeSupported;

  // Otherwise we have a perfect match.
  return IsSupported;
}

bool TestShellWebMimeRegistryImpl::IsSupportedMediaMimeType(
    const std::string& mime_type) {
  return media_map_.find(mime_type) != media_map_.end();
}

bool TestShellWebMimeRegistryImpl::AreSupportedMediaCodecs(
    const std::vector<std::string>& codecs) {
  for (size_t i = 0; i < codecs.size(); ++i) {
    if (codecs_map_.find(codecs[i]) == codecs_map_.end()) {
      return false;
    }
  }
  return true;
}
<|endoftext|>


<commit_before>// Copyright 2015 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 "remoting/host/logging.h"

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

#include "base/logging.h"
#include "base/scoped_generic.h"
#include "base/strings/string_number_conversions.h"

namespace remoting {

namespace {

const char kChromotingLoggingFacility[] = "org.chromium.chromoting";

// Define a scoper for objects allocated by asl_new.
struct ScopedAslMsgTraits {
  static aslmsg InvalidValue() {
    return nullptr;
  }
  static void Free(aslmsg msg) {
    asl_free(msg);
  }
};
typedef base::ScopedGeneric<aslmsg, ScopedAslMsgTraits> ScopedAslMsg;

// Logging message handler that writes to syslog.
// The log can be obtained by running the following in a terminal:
// syslog -k Facility org.chromium.chromoting
bool LogMessageToAsl(
    logging::LogSeverity severity,
    const char* file,
    int line,
    size_t message_start,
    const std::string& message) {
  int level;
  switch(severity) {
    case logging::LOG_INFO:
      level = ASL_LEVEL_NOTICE;
      break;
    case logging::LOG_WARNING:
      level = ASL_LEVEL_WARNING;
      break;
    case logging::LOG_ERROR:
      level = ASL_LEVEL_ERR;
      break;
    case logging::LOG_FATAL:
      level = ASL_LEVEL_EMERG;
      break;
    default:
      // 'notice' is the lowest priority that the asl libraries will log by
      // default.
      level = ASL_LEVEL_NOTICE;
      break;
  }

  ScopedAslMsg asl_message(asl_new(ASL_TYPE_MSG));
  if (!asl_message.is_valid())
    return false;

  if (asl_set(asl_message.get(), ASL_KEY_FACILITY,
              kChromotingLoggingFacility) != 0)
    return false;

  if (asl_set(asl_message.get(), ASL_KEY_LEVEL,
              base::IntToString(level).c_str()) != 0)
    return false;

  // Restrict read access to the message to root and the current user.
  if (asl_set(asl_message.get(), ASL_KEY_READ_UID,
              base::IntToString(geteuid()).c_str()) != 0)
    return false;

  if (asl_set(asl_message.get(), ASL_KEY_MSG,
              message.c_str() + message_start) != 0)
    return false;

  asl_send(nullptr, asl_message.get());

  // Don't prevent message from being logged by traditional means.
  return false;
}

}  // namespace

void InitHostLogging() {
  // Write logs to the system debug log.
  logging::LoggingSettings settings;
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
  logging::InitLogging(settings);

  // Write logs to syslog as well.
  logging::SetLogMessageHandler(LogMessageToAsl);
}

}  // namespace remoting
<commit_msg>Fix terminal spam caused by host crashes<commit_after>// Copyright 2015 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 "remoting/host/logging.h"

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

#include "base/logging.h"
#include "base/scoped_generic.h"
#include "base/strings/string_number_conversions.h"

namespace remoting {

namespace {

const char kChromotingLoggingFacility[] = "org.chromium.chromoting";

// Define a scoper for objects allocated by asl_new.
struct ScopedAslMsgTraits {
  static aslmsg InvalidValue() {
    return nullptr;
  }
  static void Free(aslmsg msg) {
    asl_free(msg);
  }
};
typedef base::ScopedGeneric<aslmsg, ScopedAslMsgTraits> ScopedAslMsg;

// Logging message handler that writes to syslog.
// The log can be obtained by running the following in a terminal:
// syslog -k Facility org.chromium.chromoting
bool LogMessageToAsl(
    logging::LogSeverity severity,
    const char* file,
    int line,
    size_t message_start,
    const std::string& message) {
  int level;
  switch(severity) {
    case logging::LOG_INFO:
      level = ASL_LEVEL_NOTICE;
      break;
    case logging::LOG_WARNING:
      level = ASL_LEVEL_WARNING;
      break;
    case logging::LOG_ERROR:
    case logging::LOG_FATAL:
      level = ASL_LEVEL_ERR;
      break;
    default:
      // 'notice' is the lowest priority that the asl libraries will log by
      // default.
      level = ASL_LEVEL_NOTICE;
      break;
  }

  ScopedAslMsg asl_message(asl_new(ASL_TYPE_MSG));
  if (!asl_message.is_valid())
    return false;

  if (asl_set(asl_message.get(), ASL_KEY_FACILITY,
              kChromotingLoggingFacility) != 0)
    return false;

  if (asl_set(asl_message.get(), ASL_KEY_LEVEL,
              base::IntToString(level).c_str()) != 0)
    return false;

  // Restrict read access to the message to root and the current user.
  if (asl_set(asl_message.get(), ASL_KEY_READ_UID,
              base::IntToString(geteuid()).c_str()) != 0)
    return false;

  if (asl_set(asl_message.get(), ASL_KEY_MSG,
              message.c_str() + message_start) != 0)
    return false;

  asl_send(nullptr, asl_message.get());

  // Don't prevent message from being logged by traditional means.
  return false;
}

}  // namespace

void InitHostLogging() {
  // Write logs to the system debug log.
  logging::LoggingSettings settings;
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
  logging::InitLogging(settings);

  // Write logs to syslog as well.
  logging::SetLogMessageHandler(LogMessageToAsl);
}

}  // namespace remoting
<|endoftext|>


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

#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class NotificationsPermissionTest : public UITest {
 public:
  NotificationsPermissionTest() {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }
};

// Flaky, http://crbug.com/62311.
TEST_F(NotificationsPermissionTest, FLAKY_TestUserGestureInfobar) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  scoped_refptr<TabProxy> tab(browser->GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/notifications/notifications_request_function.html")));
  WaitUntilTabCount(1);

  // Request permission by calling request() while eval'ing an inline script;
  // That's considered a user gesture to webkit, and should produce an infobar.
  bool result;
  ASSERT_TRUE(tab->ExecuteAndExtractBool(
      L"",
      L"window.domAutomationController.send(request());",
      &result));
  EXPECT_TRUE(result);

  EXPECT_TRUE(tab->WaitForInfoBarCount(1));
}

// Flaky, http://crbug.com/62311.
TEST_F(NotificationsPermissionTest, FLAKY_TestNoUserGestureInfobar) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  scoped_refptr<TabProxy> tab(browser->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Load a page which just does a request; no user gesture should result
  // in no infobar.
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/notifications/notifications_request_inline.html")));
  WaitUntilTabCount(1);

  size_t info_bar_count;
  ASSERT_TRUE(tab->GetInfoBarCount(&info_bar_count));
  EXPECT_EQ(0U, info_bar_count);
}
<commit_msg>Disable test that's timing out BUG=74428 TEST=none Review URL: http://codereview.chromium.org/6598038<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class NotificationsPermissionTest : public UITest {
 public:
  NotificationsPermissionTest() {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }
};

// Flaky, http://crbug.com/62311 and http://crbug.com/74428.
TEST_F(NotificationsPermissionTest, DISABLED_TestUserGestureInfobar) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  scoped_refptr<TabProxy> tab(browser->GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/notifications/notifications_request_function.html")));
  WaitUntilTabCount(1);

  // Request permission by calling request() while eval'ing an inline script;
  // That's considered a user gesture to webkit, and should produce an infobar.
  bool result;
  ASSERT_TRUE(tab->ExecuteAndExtractBool(
      L"",
      L"window.domAutomationController.send(request());",
      &result));
  EXPECT_TRUE(result);

  EXPECT_TRUE(tab->WaitForInfoBarCount(1));
}

// Flaky, http://crbug.com/62311.
TEST_F(NotificationsPermissionTest, FLAKY_TestNoUserGestureInfobar) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  scoped_refptr<TabProxy> tab(browser->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Load a page which just does a request; no user gesture should result
  // in no infobar.
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/notifications/notifications_request_inline.html")));
  WaitUntilTabCount(1);

  size_t info_bar_count;
  ASSERT_TRUE(tab->GetInfoBarCount(&info_bar_count));
  EXPECT_EQ(0U, info_bar_count);
}
<|endoftext|>


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

#include <stdlib.h>  // required by _set_abort_behavior
#include <gtk/gtk.h>

#include "base/command_line.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
  gtk_init(argc, argv);
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  // Pick a theme that uses Cairo for drawing, since we:
  // 1) currently don't support GTK themes that use the GDK drawing APIs, and
  // 2) need to use a unified theme for layout tests anyway.
  g_object_set(gtk_settings_get_default(),
               "gtk-theme-name", "Mist",
               NULL);
}

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
}

bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  return true;
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
}

void TestShellPlatformDelegate::InitializeGUI() {
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(TestShell *) {
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
}
<commit_msg>Do no use custom gtkrc files in layout test mode.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdlib.h>  // required by _set_abort_behavior
#include <gtk/gtk.h>

#include "base/command_line.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
  gtk_init(argc, argv);
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  // Stop custom gtkrc files from messing with the theme.
  gchar* default_gtkrc_files[] = { NULL };
  gtk_rc_set_default_files(default_gtkrc_files);
  gtk_rc_reparse_all_for_settings(gtk_settings_get_default(), TRUE);

  // Pick a theme that uses Cairo for drawing, since we:
  // 1) currently don't support GTK themes that use the GDK drawing APIs, and
  // 2) need to use a unified theme for layout tests anyway.
  g_object_set(gtk_settings_get_default(),
               "gtk-theme-name", "Mist",
               NULL);
}

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
}

bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  return true;
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
}

void TestShellPlatformDelegate::InitializeGUI() {
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(TestShell *) {
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
}
<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "process_memory_stats.h"
#include <vespa/vespalib/stllike/asciistream.h>
#include <algorithm>

#include <vespa/log/log.h>

LOG_SETUP(".vespalib.util.process_memory_stats");

namespace vespalib {

namespace {

#ifdef __linux__
/*
 * Check if line specifies an address range.
 *
 * address           perms offset  dev   inode   pathname
 *
 * 00400000-00420000 r-xp 00000000 fd:04 16545041                           /usr/bin/less
 */

bool
isRange(vespalib::stringref line) {
    for (char c : line) {
        if (c == ' ') {
            return true;
        }
        if (c == ':') {
            return false;
        }
    }
    return false;
}

/*
 * Check if address range is anonymous, e.g. not mapped from file.
 * inode number is 0 in that case.
 *
 * address           perms offset  dev   inode   pathname
 *
 * 00400000-00420000 r-xp 00000000 fd:04 16545041                           /usr/bin/less
 * 00625000-00628000 rw-p 00000000 00:00 0
 *
 * The range starting at 00400000 is not anonymous.
 * The range starting at 00625000 is anonymous.
 */

bool
isAnonymous(vespalib::stringref line) {
    int delims = 0;
    for (char c : line) {
        if (delims >= 4) {
            return (c == '0');
        }
        if (c == ' ') {
            ++delims;
        }
    }
    return true;
}

/*
 * Lines not containing an address range contains a header and a
 * value, e.g.
 *
 * Size:                128 kB
 * Rss:                  96 kB
 * Anonymous:             0 kB
 *
 * The lines with header Anonymous are ignored, thus anonymous pages
 * caused by mmap() of a file with MAP_PRIVATE flags are counted as
 * mapped pages.
 */

vespalib::stringref
getLineHeader(vespalib::stringref line)
{
    return line.substr(0, line.find(':'));
}
#endif

}

ProcessMemoryStats
ProcessMemoryStats::createStatsFromSmaps()
{
    ProcessMemoryStats ret;
#ifdef __linux__
    asciistream smaps = asciistream::createFromDevice("/proc/self/smaps");
    bool anonymous = true;
    uint64_t lineVal = 0;
    while (!smaps.eof()) {
        string backedLine = smaps.getline();
        stringref line(backedLine);
        if (isRange(line)) {
            ret._mappings_count += 1;
            anonymous = isAnonymous(line);
        } else if (!line.empty()) {
            stringref lineHeader = getLineHeader(line);
            if (lineHeader == "Size") {
                asciistream is(line.substr(lineHeader.size() + 1));
                is >> lineVal;
                if (anonymous) {
                    ret._anonymous_virt += lineVal * 1024;
                } else {
                    ret._mapped_virt += lineVal * 1024;
                }
            } else if (lineHeader == "Rss") {
                asciistream is(line.substr(lineHeader.size() + 1));
                is >> lineVal;
                if (anonymous) {
                    ret._anonymous_rss += lineVal * 1024;
                } else {
                    ret._mapped_rss += lineVal * 1024;
                }
            }
        }
    }
#endif
    return ret;
}

ProcessMemoryStats::ProcessMemoryStats()
    : _mapped_virt(0),
      _mapped_rss(0),
      _anonymous_virt(0),
      _anonymous_rss(0),
      _mappings_count(0)
{
}

ProcessMemoryStats::ProcessMemoryStats(uint64_t mapped_virt,
                                       uint64_t mapped_rss,
                                       uint64_t anonymous_virt,
                                       uint64_t anonymous_rss,
                                       uint64_t mappings_cnt)
    : _mapped_virt(mapped_virt),
      _mapped_rss(mapped_rss),
      _anonymous_virt(anonymous_virt),
      _anonymous_rss(anonymous_rss),
      _mappings_count(mappings_cnt)
{
}

namespace {

bool
similar(uint64_t lhs, uint64_t rhs, uint64_t epsilon)
{
    return (lhs < rhs) ? ((rhs - lhs) <= epsilon) : ((lhs - rhs) <= epsilon);
}

}

bool
ProcessMemoryStats::similarTo(const ProcessMemoryStats &rhs, uint64_t sizeEpsilon) const
{
    return similar(_mapped_virt, rhs._mapped_virt, sizeEpsilon) &&
            similar(_mapped_rss, rhs._mapped_rss, sizeEpsilon) &&
            similar(_anonymous_virt, rhs._anonymous_virt, sizeEpsilon) &&
            similar(_anonymous_rss, rhs._anonymous_rss, sizeEpsilon) &&
            (_mappings_count == rhs._mappings_count);
}

vespalib::string
ProcessMemoryStats::toString() const
{
    vespalib::asciistream stream;
    stream << "_mapped_virt=" << _mapped_virt << ", "
           << "_mapped_rss=" << _mapped_rss << ", "
           << "_anonymous_virt=" << _anonymous_virt << ", "
           << "_anonymous_rss=" << _anonymous_rss << ", "
           << "_mappings_count=" << _mappings_count;
    return stream.str();
}

ProcessMemoryStats
ProcessMemoryStats::create(uint64_t sizeEpsilon)
{
    constexpr size_t NUM_TRIES = 10;
    std::vector<ProcessMemoryStats> samples;
    samples.reserve(NUM_TRIES);
    samples.push_back(createStatsFromSmaps());
    for (size_t i = 0; i < NUM_TRIES; ++i) {
        samples.push_back(createStatsFromSmaps());
        if (samples.back().similarTo(*(samples.rbegin()+1), sizeEpsilon)) {
            return samples.back();
        }
        LOG(debug, "create(): Memory stats have changed, trying to read smaps file again: i=%zu, prevStats={%s}, currStats={%s}",
            i, (samples.rbegin()+1)->toString().c_str(), samples.back().toString().c_str());
    }
    std::sort(samples.begin(), samples.end());
    LOG(debug, "We failed to find 2 consecutive samples that where similar with epsilon of %" PRIu64 ".\nSmallest is '%s',\n median is '%s',\n largest is '%s'",
                 sizeEpsilon, samples.front().toString().c_str(), samples[samples.size()/2].toString().c_str(), samples.back().toString().c_str());
    return samples[samples.size()/2];
}

}
<commit_msg>Reduce to 3 tries as this is a rather expensive operation with many smaps.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "process_memory_stats.h"
#include <vespa/vespalib/stllike/asciistream.h>
#include <algorithm>

#include <vespa/log/log.h>

LOG_SETUP(".vespalib.util.process_memory_stats");

namespace vespalib {

namespace {

#ifdef __linux__
/*
 * Check if line specifies an address range.
 *
 * address           perms offset  dev   inode   pathname
 *
 * 00400000-00420000 r-xp 00000000 fd:04 16545041                           /usr/bin/less
 */

bool
isRange(vespalib::stringref line) {
    for (char c : line) {
        if (c == ' ') {
            return true;
        }
        if (c == ':') {
            return false;
        }
    }
    return false;
}

/*
 * Check if address range is anonymous, e.g. not mapped from file.
 * inode number is 0 in that case.
 *
 * address           perms offset  dev   inode   pathname
 *
 * 00400000-00420000 r-xp 00000000 fd:04 16545041                           /usr/bin/less
 * 00625000-00628000 rw-p 00000000 00:00 0
 *
 * The range starting at 00400000 is not anonymous.
 * The range starting at 00625000 is anonymous.
 */

bool
isAnonymous(vespalib::stringref line) {
    int delims = 0;
    for (char c : line) {
        if (delims >= 4) {
            return (c == '0');
        }
        if (c == ' ') {
            ++delims;
        }
    }
    return true;
}

/*
 * Lines not containing an address range contains a header and a
 * value, e.g.
 *
 * Size:                128 kB
 * Rss:                  96 kB
 * Anonymous:             0 kB
 *
 * The lines with header Anonymous are ignored, thus anonymous pages
 * caused by mmap() of a file with MAP_PRIVATE flags are counted as
 * mapped pages.
 */

vespalib::stringref
getLineHeader(vespalib::stringref line)
{
    return line.substr(0, line.find(':'));
}
#endif

}

ProcessMemoryStats
ProcessMemoryStats::createStatsFromSmaps()
{
    ProcessMemoryStats ret;
#ifdef __linux__
    asciistream smaps = asciistream::createFromDevice("/proc/self/smaps");
    bool anonymous = true;
    uint64_t lineVal = 0;
    while (!smaps.eof()) {
        string backedLine = smaps.getline();
        stringref line(backedLine);
        if (isRange(line)) {
            ret._mappings_count += 1;
            anonymous = isAnonymous(line);
        } else if (!line.empty()) {
            stringref lineHeader = getLineHeader(line);
            if (lineHeader == "Size") {
                asciistream is(line.substr(lineHeader.size() + 1));
                is >> lineVal;
                if (anonymous) {
                    ret._anonymous_virt += lineVal * 1024;
                } else {
                    ret._mapped_virt += lineVal * 1024;
                }
            } else if (lineHeader == "Rss") {
                asciistream is(line.substr(lineHeader.size() + 1));
                is >> lineVal;
                if (anonymous) {
                    ret._anonymous_rss += lineVal * 1024;
                } else {
                    ret._mapped_rss += lineVal * 1024;
                }
            }
        }
    }
#endif
    return ret;
}

ProcessMemoryStats::ProcessMemoryStats()
    : _mapped_virt(0),
      _mapped_rss(0),
      _anonymous_virt(0),
      _anonymous_rss(0),
      _mappings_count(0)
{
}

ProcessMemoryStats::ProcessMemoryStats(uint64_t mapped_virt,
                                       uint64_t mapped_rss,
                                       uint64_t anonymous_virt,
                                       uint64_t anonymous_rss,
                                       uint64_t mappings_cnt)
    : _mapped_virt(mapped_virt),
      _mapped_rss(mapped_rss),
      _anonymous_virt(anonymous_virt),
      _anonymous_rss(anonymous_rss),
      _mappings_count(mappings_cnt)
{
}

namespace {

bool
similar(uint64_t lhs, uint64_t rhs, uint64_t epsilon)
{
    return (lhs < rhs) ? ((rhs - lhs) <= epsilon) : ((lhs - rhs) <= epsilon);
}

}

bool
ProcessMemoryStats::similarTo(const ProcessMemoryStats &rhs, uint64_t sizeEpsilon) const
{
    return similar(_mapped_virt, rhs._mapped_virt, sizeEpsilon) &&
            similar(_mapped_rss, rhs._mapped_rss, sizeEpsilon) &&
            similar(_anonymous_virt, rhs._anonymous_virt, sizeEpsilon) &&
            similar(_anonymous_rss, rhs._anonymous_rss, sizeEpsilon) &&
            (_mappings_count == rhs._mappings_count);
}

vespalib::string
ProcessMemoryStats::toString() const
{
    vespalib::asciistream stream;
    stream << "_mapped_virt=" << _mapped_virt << ", "
           << "_mapped_rss=" << _mapped_rss << ", "
           << "_anonymous_virt=" << _anonymous_virt << ", "
           << "_anonymous_rss=" << _anonymous_rss << ", "
           << "_mappings_count=" << _mappings_count;
    return stream.str();
}

ProcessMemoryStats
ProcessMemoryStats::create(uint64_t sizeEpsilon)
{
    constexpr size_t NUM_TRIES = 3;
    std::vector<ProcessMemoryStats> samples;
    samples.reserve(NUM_TRIES);
    samples.push_back(createStatsFromSmaps());
    for (size_t i = 0; i < NUM_TRIES; ++i) {
        samples.push_back(createStatsFromSmaps());
        if (samples.back().similarTo(*(samples.rbegin()+1), sizeEpsilon)) {
            return samples.back();
        }
        LOG(debug, "create(): Memory stats have changed, trying to read smaps file again: i=%zu, prevStats={%s}, currStats={%s}",
            i, (samples.rbegin()+1)->toString().c_str(), samples.back().toString().c_str());
    }
    std::sort(samples.begin(), samples.end());
    LOG(debug, "We failed to find 2 consecutive samples that where similar with epsilon of %" PRIu64 ".\nSmallest is '%s',\n median is '%s',\n largest is '%s'",
                 sizeEpsilon, samples.front().toString().c_str(), samples[samples.size()/2].toString().c_str(), samples.back().toString().c_str());
    return samples[samples.size()/2];
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTexpand.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-12 10:55:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef \
    INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX
#define \
    INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include "com/sun/star/uno/Exception.hpp"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include "com/sun/star/uno/Sequence.hxx"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif

namespace com { namespace sun { namespace star { namespace uno {
    class XComponentContext;
    class XInterface;
} } } }
namespace rtl { class OUString; }

namespace stoc { namespace uriproc {

namespace UriSchemeParser_vndDOTsunDOTstarDOTexpand {
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
    SAL_CALL create(
        ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XComponentContext > const &)
        SAL_THROW((::com::sun::star::uno::Exception));

    ::rtl::OUString SAL_CALL getImplementationName();

    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
    getSupportedServiceNames();
}

} }

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.26); FILE MERGED 2008/04/01 15:42:29 thb 1.2.26.3: #i85898# Stripping all external header guards 2008/04/01 12:41:47 thb 1.2.26.2: #i85898# Stripping all external header guards 2008/03/31 07:26:13 rt 1.2.26.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTexpand.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef \
    INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX
#define \
    INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX

#include "sal/config.h"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "sal/types.h"

namespace com { namespace sun { namespace star { namespace uno {
    class XComponentContext;
    class XInterface;
} } } }
namespace rtl { class OUString; }

namespace stoc { namespace uriproc {

namespace UriSchemeParser_vndDOTsunDOTstarDOTexpand {
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
    SAL_CALL create(
        ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XComponentContext > const &)
        SAL_THROW((::com::sun::star::uno::Exception));

    ::rtl::OUString SAL_CALL getImplementationName();

    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
    getSupportedServiceNames();
}

} }

#endif
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include "winscwtoolchain.h"

using namespace ProjectExplorer;
using namespace Qt4ProjectManager::Internal;

WINSCWToolChain::WINSCWToolChain(S60Devices::Device device, const QString &mwcDirectory)
    : m_carbidePath(mwcDirectory),
    m_deviceId(device.id),
    m_deviceName(device.name),
    m_deviceRoot(device.epocRoot)
{

}

ToolChain::ToolChainType WINSCWToolChain::type() const
{
    return ToolChain::WINSCW;
}

QByteArray WINSCWToolChain::predefinedMacros()
{
    // TODO
    return m_predefinedMacros;
}

QList<HeaderPath> WINSCWToolChain::systemHeaderPaths()
{
    if (m_systemHeaderPaths.isEmpty()) {
        foreach (const QString &value, systemIncludes()) {
            m_systemHeaderPaths.append(HeaderPath(value, HeaderPath::GlobalHeaderPath));
        }
    }
    return m_systemHeaderPaths;
}

QStringList WINSCWToolChain::systemIncludes() const
{
    QStringList symIncludes = QStringList()
        << "\\MSL\\MSL_C\\MSL_Common\\Include"
        << "\\MSL\\MSL_C\\MSL_Win32\\Include"
        << "\\MSL\\MSL_CMSL_X86"
        << "\\MSL\\MSL_C++\\MSL_Common\\Include"
        << "\\MSL\\MSL_Extras\\MSL_Common\\Include"
        << "\\MSL\\MSL_Extras\\MSL_Win32\\Include"
        << "\\Win32-x86 Support\\Headers\\Win32 SDK";
    for (int i = 0; i < symIncludes.size(); ++i)
        symIncludes[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
    return symIncludes;
}

void WINSCWToolChain::addToEnvironment(ProjectExplorer::Environment &env)
{
    env.set("MWCSYM2INCLUDES", systemIncludes().join(";"));
    QStringList symLibraries = QStringList()
        << "\\Win32-x86 Support\\Libraries\\Win32 SDK"
        << "\\Runtime\\Runtime_x86\\Runtime_Win32\\Libs";
    for (int i = 0; i < symLibraries.size(); ++i)
        symLibraries[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
    env.set("MWSYM2LIBRARIES", symLibraries.join(";"));
    env.set("MWSYM2LIBRARYFILES", "MSL_All_MSE_Symbian_D.lib;gdi32.lib;user32.lib;kernel32.lib");
    env.prependOrSetPath(QString("%1\\x86Build\\Symbian_Tools\\Command_Line_Tools").arg(m_carbidePath)); // compiler
    env.prependOrSetPath(QString("%1\\epoc32\\tools").arg(m_deviceRoot)); // e.g. make.exe
    env.prependOrSetPath(QString("%1\\epoc32\\gcc\\bin").arg(m_deviceRoot)); // e.g. gcc.exe
    env.set("EPOCDEVICE", QString("%1:%2").arg(m_deviceId, m_deviceName));
    env.set("EPOCROOT", S60Devices::cleanedRootPath(m_deviceRoot));
}

QString WINSCWToolChain::makeCommand() const
{
    return "make";
}

QString WINSCWToolChain::defaultMakeTarget() const
{
    return "debug-winscw";
}

bool WINSCWToolChain::equals(ToolChain *other) const
{
    return (other->type() == type()
            && m_deviceId == static_cast<WINSCWToolChain *>(other)->m_deviceId
            && m_deviceName == static_cast<WINSCWToolChain *>(other)->m_deviceName);
}
<commit_msg>If no mwc path is set explicitly, still don't destroy working environment.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include "winscwtoolchain.h"

#include <QtDebug>

using namespace ProjectExplorer;
using namespace Qt4ProjectManager::Internal;

WINSCWToolChain::WINSCWToolChain(S60Devices::Device device, const QString &mwcDirectory)
    : m_carbidePath(mwcDirectory),
    m_deviceId(device.id),
    m_deviceName(device.name),
    m_deviceRoot(device.epocRoot)
{

}

ToolChain::ToolChainType WINSCWToolChain::type() const
{
    return ToolChain::WINSCW;
}

QByteArray WINSCWToolChain::predefinedMacros()
{
    // TODO
    return m_predefinedMacros;
}

QList<HeaderPath> WINSCWToolChain::systemHeaderPaths()
{
    if (m_systemHeaderPaths.isEmpty()) {
        foreach (const QString &value, systemIncludes()) {
            m_systemHeaderPaths.append(HeaderPath(value, HeaderPath::GlobalHeaderPath));
        }
    }
    return m_systemHeaderPaths;
}

QStringList WINSCWToolChain::systemIncludes() const
{
    if (m_carbidePath.isEmpty()) {
        qDebug() << "no carbide path set";
        ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();
        QString symIncludesValue = env.value("MWCSYM2INCLUDES");
        qDebug() << "includes:" << symIncludesValue.split(";");
        if (!symIncludesValue.isEmpty())
            return symIncludesValue.split(";");
    } else {
        QStringList symIncludes = QStringList()
            << "\\MSL\\MSL_C\\MSL_Common\\Include"
            << "\\MSL\\MSL_C\\MSL_Win32\\Include"
            << "\\MSL\\MSL_CMSL_X86"
            << "\\MSL\\MSL_C++\\MSL_Common\\Include"
            << "\\MSL\\MSL_Extras\\MSL_Common\\Include"
            << "\\MSL\\MSL_Extras\\MSL_Win32\\Include"
            << "\\Win32-x86 Support\\Headers\\Win32 SDK";
        for (int i = 0; i < symIncludes.size(); ++i)
            symIncludes[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
        return symIncludes;
    }
    return QStringList();
}

void WINSCWToolChain::addToEnvironment(ProjectExplorer::Environment &env)
{
    if (!m_carbidePath.isEmpty()) {
        env.set("MWCSYM2INCLUDES", systemIncludes().join(";"));
        QStringList symLibraries = QStringList()
            << "\\Win32-x86 Support\\Libraries\\Win32 SDK"
            << "\\Runtime\\Runtime_x86\\Runtime_Win32\\Libs";
        for (int i = 0; i < symLibraries.size(); ++i)
            symLibraries[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
        env.set("MWSYM2LIBRARIES", symLibraries.join(";"));
        env.set("MWSYM2LIBRARYFILES", "MSL_All_MSE_Symbian_D.lib;gdi32.lib;user32.lib;kernel32.lib");
        env.prependOrSetPath(QString("%1\\x86Build\\Symbian_Tools\\Command_Line_Tools").arg(m_carbidePath)); // compiler
    }
    env.prependOrSetPath(QString("%1\\epoc32\\tools").arg(m_deviceRoot)); // e.g. make.exe
    env.prependOrSetPath(QString("%1\\epoc32\\gcc\\bin").arg(m_deviceRoot)); // e.g. gcc.exe
    env.set("EPOCDEVICE", QString("%1:%2").arg(m_deviceId, m_deviceName));
    env.set("EPOCROOT", S60Devices::cleanedRootPath(m_deviceRoot));
}

QString WINSCWToolChain::makeCommand() const
{
    return "make";
}

QString WINSCWToolChain::defaultMakeTarget() const
{
    return "debug-winscw";
}

bool WINSCWToolChain::equals(ToolChain *other) const
{
    return (other->type() == type()
            && m_deviceId == static_cast<WINSCWToolChain *>(other)->m_deviceId
            && m_deviceName == static_cast<WINSCWToolChain *>(other)->m_deviceName);
}
<|endoftext|>