<commit_before>/*
	This file is part of the E_Rendering library.
	Copyright (C) 2018 Sascha Brandt <sascha@brandt.graphics>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_VertexAccessor.h"
#include "E_Mesh.h"
#include <Rendering/Mesh/VertexAttributeIds.h>
#include <Util/StringIdentifier.h>
#include <E_Geometry/E_Vec2.h>
#include <E_Geometry/E_Vec3.h>
#include <E_Geometry/E_Vec4.h>
#include <E_Util/Graphics/E_Color.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>

namespace E_Rendering{
using namespace Rendering;

// ----------------------------------------
// E_VertexAccessor

//! (static)
EScript::Type * E_VertexAccessor::getTypeObject() {
	// E_VertexAccessor ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! (static) init members
void E_VertexAccessor::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = E_VertexAccessor::getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	//!	[ESMF] new Rendering.VertexAccessor( Mesh )
	ES_CTOR(typeObject, 1, 1, new VertexAccessor(parameter[0].to<Mesh*>(rt)->openVertexData()))

	//! [ESMF] Geometry.Vec3 VertexAccessor.getPosition(Number index, [String attribute])
	ES_MFUN(typeObject,const VertexAccessor,"getPosition",1,2,thisObj->getPosition(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::POSITION.toString())))

	//! [ESMF] thisEObj VertexAccessor.setPosition(Number index, Geometry.Vec3, [String attribute])
	ES_MFUN(typeObject,VertexAccessor,"setPosition",2,3,(thisObj->setPosition(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::POSITION.toString())),thisEObj))

	//! [ESMF] Geometry.Vec3 VertexAccessor.getNormal(Number index, [String attribute])
	ES_MFUN(typeObject,const VertexAccessor,"getNormal",1,2,thisObj->getNormal(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::NORMAL.toString())))

	//! [ESMF] thisEObj VertexAccessor.setNormal(Number index, Geometry.Vec3, [String attribute])
	ES_MFUN(typeObject,VertexAccessor,"setNormal",2,3,(thisObj->setPosition(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::NORMAL.toString())),thisEObj))

	//! [ESMF] Util.Color4f VertexAccessor.getColor4f(Number index, [String attribute])
	ES_MFUN(typeObject,const VertexAccessor,"getColor4f",1,2,thisObj->getColor4f(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::COLOR.toString())))

	//! [ESMF] thisEObj VertexAccessor.setColor(Number index, Util.Color, [String attribute])
	ES_MFUN(typeObject,VertexAccessor,"setColor",2,3,(thisObj->setColor(parameter[0].to<uint32_t>(rt), parameter[1].to<Util::Color4f>(rt), parameter[2].toString(VertexAttributeIds::COLOR.toString())),thisEObj))

	//! [ESMF] Geometry.Vec2 VertexAccessor.getTexCoord(Number index, [String attribute])
	ES_MFUN(typeObject,const VertexAccessor,"getTexCoord",1,2,thisObj->getTexCoord(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::TEXCOORD0.toString())))

	//! [ESMF] thisEObj VertexAccessor.setTexCoord(Number index, Geometry.Vec2, [String attribute])
	ES_MFUN(typeObject,VertexAccessor,"setTexCoord",2,3,(thisObj->setTexCoord(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec2>(rt), parameter[2].toString(VertexAttributeIds::TEXCOORD0.toString())),thisEObj))

	//! [ESMF] Geometry.Vec4 VertexAccessor.getVec4(Number index, String attribute)
	ES_MFUN(typeObject,const VertexAccessor,"getVec4",2,2,thisObj->getVec4(parameter[0].to<uint32_t>(rt), parameter[1].toString()))

	//! [ESMF] thisEObj VertexAccessor.setVec4(Number index, Geometry.Vec4, String attribute)
	ES_MFUN(typeObject,VertexAccessor,"setVec4",3,3,(thisObj->setVec4(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec4>(rt), parameter[2].toString()),thisEObj))

	//! [ESMF] Number VertexAccessor.getFloat(Number index, String attribute)
	ES_MFUN(typeObject,const VertexAccessor,"getFloat",2,2,thisObj->getFloat(parameter[0].to<uint32_t>(rt), parameter[1].toString()))

	//! [ESMF] Array VertexAccessor.getFloats(Number index, String attribute)
	ES_MFUN(typeObject,const VertexAccessor,"getFloats",2,2,EScript::Array::create(thisObj->getFloats(parameter[0].to<uint32_t>(rt), parameter[1].toString())))

	//! [ESMF] thisEObj VertexAccessor.setFloat(Number index, Number value, String attribute)
	ES_MFUN(typeObject,VertexAccessor,"setFloat",3,3,(thisObj->setFloat(parameter[0].to<uint32_t>(rt), parameter[1].toFloat(), parameter[2].toString()),thisEObj))

	//! [ESMF] thisEObj VertexAccessor.setFloats(Number index, Array values, String attribute)
	ES_MFUNCTION(typeObject,VertexAccessor,"setFloats",3,3,{
		EScript::Array * a=parameter[1].to<EScript::Array*>(rt);
		std::vector<float> values;
		for(auto v : *a)
			values.push_back(v.toFloat());
		thisObj->setFloats(parameter[0].to<uint32_t>(rt), values, parameter[2].toString());
		return thisEObj;
	})

	//! [ESMF] Number VertexAccessor.getUInt(Number index, String attribute)
	ES_MFUN(typeObject,const VertexAccessor,"getUInt",2,2,thisObj->getUInt(parameter[0].to<uint32_t>(rt), parameter[1].toString()))

	//! [ESMF] Array VertexAccessor.getUInts(Number index, String attribute)
	ES_MFUN(typeObject,const VertexAccessor,"getUInts",2,2,EScript::Array::create(thisObj->getUInts(parameter[0].to<uint32_t>(rt), parameter[1].toString())))

	//! [ESMF] thisEObj VertexAccessor.setUInt(Number index, Number value, String attribute)
	ES_MFUN(typeObject,VertexAccessor,"setUInt",3,3,(thisObj->setUInt(parameter[0].to<uint32_t>(rt), parameter[1].toUInt(), parameter[2].toString()),thisEObj))

	//! [ESMF] thisEObj VertexAccessor.setUInts(Number index, Array values, String attribute)
	ES_MFUNCTION(typeObject,VertexAccessor,"setUInts",3,3,{
		EScript::Array * a=parameter[1].to<EScript::Array*>(rt);
		std::vector<uint32_t> values;
		for(auto v : *a)
			values.push_back(v.toUInt());
		thisObj->setUInts(parameter[0].to<uint32_t>(rt), values, parameter[2].toString());
		return thisEObj;
	})
}

}
<commit_msg>Changed bindings for VertexAccessor<commit_after>/*
	This file is part of the E_Rendering library.
	Copyright (C) 2018 Sascha Brandt <sascha@brandt.graphics>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_VertexAccessor.h"
#include "E_Mesh.h"
#include <Rendering/Mesh/VertexAttributeIds.h>
#include <Util/StringIdentifier.h>
#include <E_Geometry/E_Vec2.h>
#include <E_Geometry/E_Vec3.h>
#include <E_Geometry/E_Vec4.h>
#include <E_Util/Graphics/E_Color.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>

namespace E_Rendering{
using namespace Rendering;

// ----------------------------------------
// E_VertexAccessor

//! (static)
EScript::Type * E_VertexAccessor::getTypeObject() {
	// E_VertexAccessor ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! (static) init members
void E_VertexAccessor::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = E_VertexAccessor::getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	//!	[ESMF] new Rendering.VertexAccessor( Mesh )
	ES_CTOR(typeObject, 1, 1, VertexAccessor::create(parameter[0].to<Mesh*>(rt)))

	//! [ESMF] Number VertexAccessor.getAttributeLocation(String attribute)
	ES_MFUN(typeObject,const VertexAccessor,"getAttributeLocation",1,1,thisObj->getAttributeLocation(parameter[0].toString()))

	//! [ESMF] Geometry.Vec3 VertexAccessor.getPosition(Number index, [String attribute | Number location])
	ES_MFUN(typeObject,const VertexAccessor,"getPosition",1,2,
		parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->getPosition(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::POSITION.toString())) :
		thisObj->getPosition(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] thisEObj VertexAccessor.setPosition(Number index, Geometry.Vec3, [String attribute | Number location])
	ES_MFUN(typeObject,VertexAccessor,"setPosition",2,3,(
		parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
		thisObj->setPosition(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::POSITION.toString())) :
		thisObj->setPosition(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].to<uint16_t>(rt))
	,thisEObj))

	//! [ESMF] Geometry.Vec3 VertexAccessor.getNormal(Number index, [String attribute | Number location])
	ES_MFUN(typeObject,const VertexAccessor,"getNormal",1,2,
		parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->getNormal(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::NORMAL.toString())) :
		thisObj->getNormal(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] thisEObj VertexAccessor.setNormal(Number index, Geometry.Vec3, [String attribute | Number location])
	ES_MFUN(typeObject,VertexAccessor,"setNormal",2,3,(
		parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
		thisObj->setNormal(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::NORMAL.toString())) :
		thisObj->setNormal(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].to<uint16_t>(rt))
	,thisEObj))

	//! [ESMF] Util.Color4f VertexAccessor.getColor4f(Number index, [String attribute | Number location])
	ES_MFUN(typeObject,const VertexAccessor,"getColor4f",1,2,
		parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->getColor4f(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::COLOR.toString())) :
		thisObj->getColor4f(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] thisEObj VertexAccessor.setColor(Number index, Util.Color4f, [String attribute | Number location])
	ES_MFUN(typeObject,VertexAccessor,"setColor",2,3,(
		parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
		thisObj->setColor(parameter[0].toUInt(), parameter[1].to<Util::Color4f>(rt), parameter[2].toString(VertexAttributeIds::COLOR.toString())) :
		thisObj->setColor(parameter[0].toUInt(), parameter[1].to<Util::Color4f>(rt), parameter[2].to<uint16_t>(rt))
	,thisEObj))

	//! [ESMF] Geometry.Vec2 VertexAccessor.getTexCoord(Number index, [String attribute | Number location])
	ES_MFUN(typeObject,const VertexAccessor,"getTexCoord",1,2,
		parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->getTexCoord(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::TEXCOORD0.toString())) :
		thisObj->getTexCoord(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] thisEObj VertexAccessor.setTexCoord(Number index, Geometry.Vec2, [String attribute | Number location])
	ES_MFUN(typeObject,VertexAccessor,"setTexCoord",2,3,(
		parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
		thisObj->setTexCoord(parameter[0].toUInt(), parameter[1].to<Geometry::Vec2>(rt), parameter[2].toString(VertexAttributeIds::TEXCOORD0.toString())) :
		thisObj->setTexCoord(parameter[0].toUInt(), parameter[1].to<Geometry::Vec2>(rt), parameter[2].to<uint16_t>(rt))
	,thisEObj))

	//! [ESMF] Geometry.Vec4 VertexAccessor.getVec4(Number index, String attribute | Number location)
	ES_MFUN(typeObject,const VertexAccessor,"getVec4",2,2,
		parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->getVec4(parameter[0].toUInt(), parameter[1].toString()) :
		thisObj->getVec4(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] thisEObj VertexAccessor.setVec4(Number index, Geometry.Vec4, String attribute | Number location)
	ES_MFUN(typeObject,VertexAccessor,"setVec4",3,3,(
		parameter[2]->isA(EScript::String::getTypeObject()) ?
		thisObj->setVec4(parameter[0].toUInt(), parameter[1].to<Geometry::Vec4>(rt), parameter[2].toString()) :
		thisObj->setVec4(parameter[0].toUInt(), parameter[1].to<Geometry::Vec4>(rt), parameter[2].to<uint16_t>(rt))
	,thisEObj))

	//! [ESMF] Number VertexAccessor.getFloat(Number index, String attribute | Number location)
	ES_MFUN(typeObject,const VertexAccessor,"getFloat",2,2,
		parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->readValue<float>(parameter[0].toUInt(), parameter[1].toString()) :
		thisObj->readValue<float>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] Number VertexAccessor.getFloats(Number index, String attribute | Number location, Number count)
	ES_MFUN(typeObject,const VertexAccessor,"getFloats",3,3,
		EScript::Array::create(parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->readValues<float>(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :
		thisObj->readValues<float>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toUInt()))
	)

	//! [ESMF] thisEObj VertexAccessor.setFloat(Number index, String attribute | Number location, Number value)
	ES_MFUN(typeObject,VertexAccessor,"setFloat",3,3,(
		parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->writeValue(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toFloat()) :
		thisObj->writeValue(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toFloat())
	,thisEObj))

	//! [ESMF] thisEObj VertexAccessor.setFloats(Number index, String attribute, Array values)
	ES_MFUNCTION(typeObject,VertexAccessor,"setFloats",3,3,{
		EScript::Array * a=parameter[2].to<EScript::Array*>(rt);
		std::vector<float> values;
		for(auto v : *a)
			values.push_back(v.toFloat());
		if(parameter[1]->isA(EScript::String::getTypeObject()))
			thisObj->writeValues(parameter[0].toUInt(), parameter[1].toString(), values);
		else
			thisObj->writeValues(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), values);
		return thisEObj;
	})

	//! [ESMF] Number VertexAccessor.getUInt(Number index, String attribute | Number location)
	ES_MFUN(typeObject,const VertexAccessor,"getUInt",2,2,
		parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->readValue<uint32_t>(parameter[0].toUInt(), parameter[1].toString()) :
		thisObj->readValue<uint32_t>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
	)

	//! [ESMF] Number VertexAccessor.getUInts(Number index, String attribute | Number location, Number count)
	ES_MFUN(typeObject,const VertexAccessor,"getUInts",3,3,
		EScript::Array::create(parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->readValues<uint32_t>(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :
		thisObj->readValues<uint32_t>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toUInt()))
	)

	//! [ESMF] thisEObj VertexAccessor.setUInt(Number index, String attribute | Number location, Number value)
	ES_MFUN(typeObject,VertexAccessor,"setUInt",3,3,(
		parameter[1]->isA(EScript::String::getTypeObject()) ?
		thisObj->writeValue(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :
		thisObj->writeValue(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toUInt())
	,thisEObj))

	//! [ESMF] thisEObj VertexAccessor.setUInts(Number index, String attribute, Array values)
	ES_MFUNCTION(typeObject,VertexAccessor,"setUInts",3,3,{
		EScript::Array * a=parameter[2].to<EScript::Array*>(rt);
		std::vector<uint32_t> values;
		for(auto v : *a)
			values.push_back(v.toUInt());
		if(parameter[1]->isA(EScript::String::getTypeObject()))
			thisObj->writeValues(parameter[0].toUInt(), parameter[1].toString(), values);
		else
			thisObj->writeValues(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), values);
		return thisEObj;
	})
}

}
<|endoftext|>


<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "Core.h"
#include "OrbitModule.h"
#include "Serialization.h"
#include "Pdb.h"
#include <string>

#ifndef WIN32
#include "LinuxUtils.h"
#include "Capture.h"
#include "ScopeTimer.h"
#include "OrbitUnreal.h"
#include "Params.h"
#include "OrbitProcess.h"
#include "Path.h"
#endif

//-----------------------------------------------------------------------------
Module::Module()
{
}

//-----------------------------------------------------------------------------
std::wstring Module::GetPrettyName()
{
    if( m_PrettyName.size() == 0 )
    {
        #ifdef WIN32
        m_PrettyName = Format( "%s [%I64x - %I64x] %s\r\n", m_Name.c_str(), m_AddressStart, m_AddressEnd, m_FullName.c_str() );
        m_AddressRange = Format( "[%I64x - %I64x]", m_AddressStart, m_AddressEnd );
        #else
        m_PrettyName = m_FullName;
        m_AddressRange = Format( "[%016llx - %016llx]", m_AddressStart, m_AddressEnd );
        m_PdbName = m_FullName;
        m_FoundPdb = true;
        #endif
    }

    return s2ws(m_PrettyName);
}

//-----------------------------------------------------------------------------
bool Module::IsDll() const
{
    return ToLower( Path::GetExtension( s2ws(m_FullName) ) ) == std::wstring( L".dll" ) ||
           Contains(m_Name, ".so" );
}

//-----------------------------------------------------------------------------
bool Module::LoadDebugInfo()
{
    std::wstring pdbName = s2ws(m_PdbName);
    m_Pdb = std::make_shared<Pdb>( pdbName.c_str() );
    m_Pdb->SetMainModule( (HMODULE)m_AddressStart );

    PRINT_VAR(m_FoundPdb);
    if( m_FoundPdb )
    {
        return m_Pdb->LoadDataFromPdb();
    }

    return false;
}

//-----------------------------------------------------------------------------
uint64_t Module::ValidateAddress( uint64_t a_Address )
{
    if( ContainsAddress(a_Address ) )
        return a_Address;

    // Treat input address as RVA
    uint64_t newAddress = m_AddressStart + a_Address;
    if( ContainsAddress(newAddress) )
        return newAddress;

    return 0xbadadd;
}

//-----------------------------------------------------------------------------
void Module::SetLoaded(bool a_Value)
{
    m_Loaded = a_Value;
}

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( Module, 0 )
{
    ORBIT_NVP_VAL( 0, m_Name );
    ORBIT_NVP_VAL( 0, m_FullName );
    ORBIT_NVP_VAL( 0, m_PdbName );
    ORBIT_NVP_VAL( 0, m_Directory );
    ORBIT_NVP_VAL( 0, m_PrettyName );
    ORBIT_NVP_VAL( 0, m_AddressRange );
    ORBIT_NVP_VAL( 0, m_DebugSignature );
    ORBIT_NVP_VAL( 0, m_AddressStart );
    ORBIT_NVP_VAL( 0, m_AddressEnd );
    ORBIT_NVP_VAL( 0, m_EntryPoint );
    ORBIT_NVP_VAL( 0, m_FoundPdb );
    ORBIT_NVP_VAL( 0, m_Selected );
    ORBIT_NVP_VAL( 0, m_Loaded );
    ORBIT_NVP_VAL( 0, m_PdbSize );
}

#ifndef WIN32

//-----------------------------------------------------------------------------
Function* Pdb::FunctionFromName( const std::string& a_Name )
{
    uint64_t hash = StringHash(a_Name);
    auto iter = m_StringFunctionMap.find(hash);
    return (iter == m_StringFunctionMap.end()) ? nullptr : iter->second;
}

//-----------------------------------------------------------------------------
void Pdb::LoadPdb( const wchar_t* a_PdbName )
{
    m_FileName = a_PdbName;
    m_Name = Path::GetFileName(m_FileName);

    {
        SCOPE_TIMER_LOG(L"nm");
        // nm
        std::string nmCommand = std::string("nm ") + ws2s(a_PdbName) + std::string(" -n -l");
        std::string nmResult = LinuxUtils::ExecuteCommand(nmCommand.c_str());
        std::stringstream nmStream(nmResult);
        std::string line;
        while (std::getline(nmStream, line, '\n'))
        {
            std::vector<std::string> tokens = Tokenize(line, " \t");
            if (tokens.size() > 2) // nm
            {
                Function func;
                func.m_Name = tokens[2];
                func.m_Address = std::stoull(tokens[0], nullptr, 16);
                func.m_PrettyName = LinuxUtils::Demangle(tokens[2].c_str());
                func.m_Module = ws2s(Path::GetFileName(a_PdbName));
                func.m_Pdb = this;
                this->AddFunction(func);

                // Debug - Temporary
                if (Contains(func.m_PrettyName, "btCollisionDispatcher::needsCollision"))
                {
                    PRINT_VAR(func.m_PrettyName);
                }
            }
        }
    }
    ProcessData();

    {
        SCOPE_TIMER_LOG(L"bpftrace -l");
        // find functions that can receive bpftrace uprobes
        std::string bpfCommand = std::string("bpftrace -l 'uprobe: ") + ws2s(a_PdbName) + std::string("'");
        std::string bpfResult = LinuxUtils::ExecuteCommand(bpfCommand.c_str());
        std::stringstream bpfStream(bpfResult);
        std::string line;
        while (std::getline(bpfStream, line, '\n'))
        {
            std::vector<std::string> tokens = Tokenize(line);
            if (tokens.size() == 2) // bpftrace
            {
                Function func;
                auto probeTokens = Tokenize(tokens[1], ":");
                if (probeTokens.size() == 2)
                {
                    std::string mangled = probeTokens[1];
                    std::string demangled = LinuxUtils::Demangle(probeTokens[1].c_str());

                    // Debug - Temporary
                    if (Contains(demangled, "btCollisionDispatcher::needsCollision"))
                        PRINT_VAR(demangled);
                    Function* func = FunctionFromName(demangled);
                    if (func && func->m_Probe.empty())
                    {
                        std::string probe = Replace(tokens[1], ".", "*");
                        func->m_Probe = probe;
                    }
                }
            }
        }
    }
}

//-----------------------------------------------------------------------------
void Pdb::LoadPdbAsync( const wchar_t* a_PdbName, std::function<void()> a_CompletionCallback )
{
    m_LoadingCompleteCallback = a_CompletionCallback;
    LoadPdb(a_PdbName);
    a_CompletionCallback();
}

//-----------------------------------------------------------------------------
void Pdb::ProcessData()
{
    SCOPE_TIMER_LOG( L"ProcessData" );
    ScopeLock lock( Capture::GTargetProcess->GetDataMutex() );

    auto & functions = Capture::GTargetProcess->GetFunctions();
    auto & globals   = Capture::GTargetProcess->GetGlobals();

    functions.reserve( functions.size() + m_Functions.size() );

    for( Function & func : m_Functions )
    {
        func.m_Pdb = this;
        functions.push_back( &func );
        GOrbitUnreal.OnFunctionAdded( &func );
    }

    if( GParams.m_FindFileAndLineInfo )
    {
        SCOPE_TIMER_LOG(L"Find File and Line info");
        for( Function & func : m_Functions )
        {
            func.FindFile();
        }
    }

    for( Type & type : m_Types )
    {
        type.m_Pdb = this;
        Capture::GTargetProcess->AddType( type );
        GOrbitUnreal.OnTypeAdded( &type );
    }

    for( Variable & var : m_Globals )
    {
        var.m_Pdb = this;
        globals.push_back( &var );
    }

    for( auto & it : m_TypeMap )
    {
        it.second.m_Pdb = this;
    }

    PopulateFunctionMap();
    PopulateStringFunctionMap();
}

//-----------------------------------------------------------------------------
void Pdb::PopulateFunctionMap()
{
    m_IsPopulatingFunctionMap = true;

    SCOPE_TIMER_LOG( L"Pdb::PopulateFunctionMap" );

    uint64_t baseAddress = (uint64_t)GetHModule();
    bool rvaAddresses = false;

    // It seems nm can return addresses as VA or RVA
    // TODO: investigate, use simple test to detect RVA
    for( Function & function : m_Functions )
    {
        if( function.m_Address > 0 && function.m_Address < baseAddress )
        {
            rvaAddresses = true;
            break;
        }
    }

    for( Function & Function : m_Functions )
    {
        uint64_t RVA = rvaAddresses ? Function.m_Address : Function.m_Address - (uint64_t)GetHModule();
        m_FunctionMap.insert( std::make_pair( RVA, &Function ) );
    }

    m_IsPopulatingFunctionMap = false;
}

//-----------------------------------------------------------------------------
void Pdb::PopulateStringFunctionMap()
{
    m_IsPopulatingFunctionStringMap = true;

    {
        //SCOPE_TIMER_LOG( L"Reserving map" );
        m_StringFunctionMap.reserve( unsigned ( 1.5f * (float)m_Functions.size() ) );
    }

    {
        //SCOPE_TIMER_LOG( L"Hash" );
        for( Function & Function : m_Functions )
        {
            Function.Hash();
        }
    }

    {
        //SCOPE_TIMER_LOG( L"Map inserts" );

        for( Function & Function : m_Functions )
        {
            m_StringFunctionMap[Function.m_NameHash] = &Function;
        }
    }

    m_IsPopulatingFunctionStringMap = false;
}

//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromExactAddress( uint64_t a_Address )
{
    uint64_t RVA = a_Address - (uint64_t)GetHModule();
    auto iter = m_FunctionMap.find(RVA);
    return (iter != m_FunctionMap.end()) ? iter->second : nullptr;
}

//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromProgramCounter( uint64_t a_Address )
{
    uint64_t RVA = a_Address - (uint64_t)GetHModule();

    auto it = m_FunctionMap.upper_bound( RVA );
    if (!m_FunctionMap.empty() && it != m_FunctionMap.begin())
    {
        --it;
        Function* func = it->second;
        return func;
    }

    return nullptr;
}

#endif

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(ModuleDebugInfo, 0)
{
    ORBIT_NVP_VAL(0, m_Pid);
    ORBIT_NVP_VAL(0, m_Name);
    ORBIT_NVP_VAL(0, m_Functions);
}<commit_msg>Fix Linux build.<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "Core.h"
#include "OrbitModule.h"
#include "Serialization.h"
#include "Pdb.h"
#include <string>

#ifndef WIN32
#include "LinuxUtils.h"
#include "Capture.h"
#include "ScopeTimer.h"
#include "OrbitUnreal.h"
#include "Params.h"
#include "OrbitProcess.h"
#include "Path.h"
#endif

//-----------------------------------------------------------------------------
Module::Module()
{
}

//-----------------------------------------------------------------------------
std::wstring Module::GetPrettyName()
{
    if( m_PrettyName.size() == 0 )
    {
        #ifdef WIN32
        m_PrettyName = Format( "%s [%I64x - %I64x] %s\r\n", m_Name.c_str(), m_AddressStart, m_AddressEnd, m_FullName.c_str() );
        m_AddressRange = Format( "[%I64x - %I64x]", m_AddressStart, m_AddressEnd );
        #else
        m_PrettyName = m_FullName;
        m_AddressRange = Format( "[%016llx - %016llx]", m_AddressStart, m_AddressEnd );
        m_PdbName = m_FullName;
        m_FoundPdb = true;
        #endif
    }

    return s2ws(m_PrettyName);
}

//-----------------------------------------------------------------------------
bool Module::IsDll() const
{
    return ToLower( Path::GetExtension( s2ws(m_FullName) ) ) == std::wstring( L".dll" ) ||
           Contains(m_Name, ".so" );
}

//-----------------------------------------------------------------------------
bool Module::LoadDebugInfo()
{
    std::wstring pdbName = s2ws(m_PdbName);
    m_Pdb = std::make_shared<Pdb>( pdbName.c_str() );
    m_Pdb->SetMainModule( (HMODULE)m_AddressStart );

    PRINT_VAR(m_FoundPdb);
    if( m_FoundPdb )
    {
        return m_Pdb->LoadDataFromPdb();
    }

    return false;
}

//-----------------------------------------------------------------------------
uint64_t Module::ValidateAddress( uint64_t a_Address )
{
    if( ContainsAddress(a_Address ) )
        return a_Address;

    // Treat input address as RVA
    uint64_t newAddress = m_AddressStart + a_Address;
    if( ContainsAddress(newAddress) )
        return newAddress;

    return 0xbadadd;
}

//-----------------------------------------------------------------------------
void Module::SetLoaded(bool a_Value)
{
    m_Loaded = a_Value;
}

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( Module, 0 )
{
    ORBIT_NVP_VAL( 0, m_Name );
    ORBIT_NVP_VAL( 0, m_FullName );
    ORBIT_NVP_VAL( 0, m_PdbName );
    ORBIT_NVP_VAL( 0, m_Directory );
    ORBIT_NVP_VAL( 0, m_PrettyName );
    ORBIT_NVP_VAL( 0, m_AddressRange );
    ORBIT_NVP_VAL( 0, m_DebugSignature );
    ORBIT_NVP_VAL( 0, m_AddressStart );
    ORBIT_NVP_VAL( 0, m_AddressEnd );
    ORBIT_NVP_VAL( 0, m_EntryPoint );
    ORBIT_NVP_VAL( 0, m_FoundPdb );
    ORBIT_NVP_VAL( 0, m_Selected );
    ORBIT_NVP_VAL( 0, m_Loaded );
    ORBIT_NVP_VAL( 0, m_PdbSize );
}

#ifndef WIN32

//-----------------------------------------------------------------------------
Function* Pdb::FunctionFromName( const std::string& a_Name )
{
    uint64_t hash = StringHash(a_Name);
    auto iter = m_StringFunctionMap.find(hash);
    return (iter == m_StringFunctionMap.end()) ? nullptr : iter->second;
}

//-----------------------------------------------------------------------------
bool Pdb::LoadPdb( const wchar_t* a_PdbName )
{
    m_FileName = a_PdbName;
    m_Name = Path::GetFileName(m_FileName);

    {
        SCOPE_TIMER_LOG(L"nm");
        // nm
        std::string nmCommand = std::string("nm ") + ws2s(a_PdbName) + std::string(" -n -l");
        std::string nmResult = LinuxUtils::ExecuteCommand(nmCommand.c_str());
        std::stringstream nmStream(nmResult);
        std::string line;
        while (std::getline(nmStream, line, '\n'))
        {
            std::vector<std::string> tokens = Tokenize(line, " \t");
            if (tokens.size() > 2) // nm
            {
                Function func;
                func.m_Name = tokens[2];
                func.m_Address = std::stoull(tokens[0], nullptr, 16);
                func.m_PrettyName = LinuxUtils::Demangle(tokens[2].c_str());
                func.m_Module = ws2s(Path::GetFileName(a_PdbName));
                func.m_Pdb = this;
                this->AddFunction(func);

                // Debug - Temporary
                if (Contains(func.m_PrettyName, "btCollisionDispatcher::needsCollision"))
                {
                    PRINT_VAR(func.m_PrettyName);
                }
            }
        }
    }
    ProcessData();

    {
        SCOPE_TIMER_LOG(L"bpftrace -l");
        // find functions that can receive bpftrace uprobes
        std::string bpfCommand = std::string("bpftrace -l 'uprobe: ") + ws2s(a_PdbName) + std::string("'");
        std::string bpfResult = LinuxUtils::ExecuteCommand(bpfCommand.c_str());
        std::stringstream bpfStream(bpfResult);
        std::string line;
        while (std::getline(bpfStream, line, '\n'))
        {
            std::vector<std::string> tokens = Tokenize(line);
            if (tokens.size() == 2) // bpftrace
            {
                Function func;
                auto probeTokens = Tokenize(tokens[1], ":");
                if (probeTokens.size() == 2)
                {
                    std::string mangled = probeTokens[1];
                    std::string demangled = LinuxUtils::Demangle(probeTokens[1].c_str());

                    // Debug - Temporary
                    if (Contains(demangled, "btCollisionDispatcher::needsCollision"))
                        PRINT_VAR(demangled);
                    Function* func = FunctionFromName(demangled);
                    if (func && func->m_Probe.empty())
                    {
                        std::string probe = Replace(tokens[1], ".", "*");
                        func->m_Probe = probe;
                    }
                }
            }
        }
    }

    return true;
}

//-----------------------------------------------------------------------------
void Pdb::LoadPdbAsync( const wchar_t* a_PdbName, std::function<void()> a_CompletionCallback )
{
    m_LoadingCompleteCallback = a_CompletionCallback;
    LoadPdb(a_PdbName);
    a_CompletionCallback();
}

//-----------------------------------------------------------------------------
void Pdb::ProcessData()
{
    SCOPE_TIMER_LOG( L"ProcessData" );
    ScopeLock lock( Capture::GTargetProcess->GetDataMutex() );

    auto & functions = Capture::GTargetProcess->GetFunctions();
    auto & globals   = Capture::GTargetProcess->GetGlobals();

    functions.reserve( functions.size() + m_Functions.size() );

    for( Function & func : m_Functions )
    {
        func.m_Pdb = this;
        functions.push_back( &func );
        GOrbitUnreal.OnFunctionAdded( &func );
    }

    if( GParams.m_FindFileAndLineInfo )
    {
        SCOPE_TIMER_LOG(L"Find File and Line info");
        for( Function & func : m_Functions )
        {
            func.FindFile();
        }
    }

    for( Type & type : m_Types )
    {
        type.m_Pdb = this;
        Capture::GTargetProcess->AddType( type );
        GOrbitUnreal.OnTypeAdded( &type );
    }

    for( Variable & var : m_Globals )
    {
        var.m_Pdb = this;
        globals.push_back( &var );
    }

    for( auto & it : m_TypeMap )
    {
        it.second.m_Pdb = this;
    }

    PopulateFunctionMap();
    PopulateStringFunctionMap();
}

//-----------------------------------------------------------------------------
void Pdb::PopulateFunctionMap()
{
    m_IsPopulatingFunctionMap = true;

    SCOPE_TIMER_LOG( L"Pdb::PopulateFunctionMap" );

    uint64_t baseAddress = (uint64_t)GetHModule();
    bool rvaAddresses = false;

    // It seems nm can return addresses as VA or RVA
    // TODO: investigate, use simple test to detect RVA
    for( Function & function : m_Functions )
    {
        if( function.m_Address > 0 && function.m_Address < baseAddress )
        {
            rvaAddresses = true;
            break;
        }
    }

    for( Function & Function : m_Functions )
    {
        uint64_t RVA = rvaAddresses ? Function.m_Address : Function.m_Address - (uint64_t)GetHModule();
        m_FunctionMap.insert( std::make_pair( RVA, &Function ) );
    }

    m_IsPopulatingFunctionMap = false;
}

//-----------------------------------------------------------------------------
void Pdb::PopulateStringFunctionMap()
{
    m_IsPopulatingFunctionStringMap = true;

    {
        //SCOPE_TIMER_LOG( L"Reserving map" );
        m_StringFunctionMap.reserve( unsigned ( 1.5f * (float)m_Functions.size() ) );
    }

    {
        //SCOPE_TIMER_LOG( L"Hash" );
        for( Function & Function : m_Functions )
        {
            Function.Hash();
        }
    }

    {
        //SCOPE_TIMER_LOG( L"Map inserts" );

        for( Function & Function : m_Functions )
        {
            m_StringFunctionMap[Function.m_NameHash] = &Function;
        }
    }

    m_IsPopulatingFunctionStringMap = false;
}

//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromExactAddress( uint64_t a_Address )
{
    uint64_t RVA = a_Address - (uint64_t)GetHModule();
    auto iter = m_FunctionMap.find(RVA);
    return (iter != m_FunctionMap.end()) ? iter->second : nullptr;
}

//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromProgramCounter( uint64_t a_Address )
{
    uint64_t RVA = a_Address - (uint64_t)GetHModule();

    auto it = m_FunctionMap.upper_bound( RVA );
    if (!m_FunctionMap.empty() && it != m_FunctionMap.begin())
    {
        --it;
        Function* func = it->second;
        return func;
    }

    return nullptr;
}

#endif

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(ModuleDebugInfo, 0)
{
    ORBIT_NVP_VAL(0, m_Pid);
    ORBIT_NVP_VAL(0, m_Name);
    ORBIT_NVP_VAL(0, m_Functions);
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <typeinfo>
#include <typeindex>

int main(int argc, char * argv[])
{
  return 0;
}
<commit_msg>added basic adobe example on which i will begin working<commit_after>#include <iostream>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <memory>
#include <string>
#include <vector>

using namespace std;

#if 0
class object_t
{
  public:
    virtual ~object_t() {}
    virtual void draw(ostream&, size_t) const = 0;
};

using document_t = vector<shared_ptr<object_t>>;

void draw(const document_t& x, ostream& out, size_t position)
{
  out << string(position, ' ') << "<document>" << endl;
  for (const auto& e : x )
    e->draw(out, position + 2);
  out << string(position, ' ') << "</document>" << endl;
}

class my_class_t : public object_t
{
  public:
    void draw(ostream &out, size_t position) const
    {
      out << string(position, ' ') << "my_class_t" << endl;
    }
};

int main(int argc, char * argv[])
{
  document_t document;
  document.emplace_back(new my_class_t{});
  draw(document,cout, 1);
  return 0;
}
#else
class object_t
{
  public:
    template<typename T>
      object_t(T x) : self_(make_shared<model<T>>(move(x))) {}
    void draw(ostream& out, size_t position) const
    {
      self_->draw_(out,position);
    }

  private:
    struct concept_t
    {
      virtual ~concept_t() = default;
      virtual void draw_(ostream&, size_t) const = 0;
    };

    template<typename T>
    struct model : concept_t
    {
      model(T x) : data_(move(x)) {}
      void draw_(ostream& out, size_t position) const
      {
        data_.draw(out,position);
      }
      T data_;
    };

    shared_ptr<const concept_t> self_;
};

using document_t = vector<object_t>;

void draw(const document_t& x, ostream& out, size_t position)
{
  out << string(position, ' ') << "<document>" << endl;
  for (const auto& e : x )
    e.draw(out, position + 2);
  out << string(position, ' ') << "</document>" << endl;
}

class my_class_t
{
  public:
    void draw(ostream& out, size_t position) const
    {
      out << string(position, ' ') << "my_class_t" << endl;
    }
};

int main()
{
  document_t document;
  document.emplace_back(my_class_t{});
  draw(document,cout,0);
}
#endif
<|endoftext|>


<commit_before>// SmallGames.cpp : Definiert die exportierten Funktionen fr die DLL-Anwendung.
// @author Florian Dahlitz

#include "stdafx.h"

#include "SmallGames.h"

void ISmallGames::HangingMan::setupGame()
{
	wordlist = getWordlist();
	word = getRandomWord(wordlist);
	boost::to_upper(word);
	userWord = "_";

	for (unsigned int i = 0; i < word.size() - 1; ++i)
		userWord += "_";

	return;
}

void ISmallGames::HangingMan::buildWindow()
{
	system("cls");

	std::cout << "THE HANGING MAN" << std::endl;

	for (it = hangingManParts.begin(); it != hangingManParts.end(); ++it)
		if (it->first == m_efforts)
			std::cout << it->second << std::endl << std::endl;

	for (int i = 0; i < (m_hangingMan - manHeight[m_efforts]); ++i)
		std::cout << "\n";

	std::cout << "" << std::endl << std::endl;	// clean buffer + better overview

	for (int i = 0; i < userWord.length(); i++)
		std::cout << userWord[i] << " ";

	std::cout << std::endl; // clean buffer

	return;
}

std::map<unsigned int, std::string> ISmallGames::HangingMan::getWordlist()
{
	unsigned int i = 0;
	std::string strWord;
	std::map<unsigned int, std::string> wordlist;
	std::ifstream worldlistFile(m_path);
	if (worldlistFile.fail())
		std::cout << m_path << std::endl;
	// TODO: change reading file w/ vectors -> read something about
	while (std::getline(worldlistFile, strWord))
	{
		wordlist[i] = strWord;
		std::cout << ++i << " - " << strWord << std::endl;
	}

	return wordlist;
}

std::string ISmallGames::HangingMan::getRandomWord(std::map<unsigned int, std::string> wordlist)
{
	std::string randomWord;
	auto iter = wordlist.begin();

	srand(time(NULL));
	std::advance(iter, rand() % wordlist.size());
	randomWord = iter->second;

	wordlist.erase(iter);

	return randomWord;
}

void ISmallGames::HangingMan::playGame()
{
	do {
		buildWindow();

		char userChar = getUserChar();
		addToUserWord(userChar);

	} while (userWord.compare(word) && (m_efforts != 6));

	return;
}

char ISmallGames::HangingMan::getUserChar()
{
	char userChar;

	do {
		std::cout << "Type in a character: ";
		std::cin >> userChar;
		userChar = toupper(userChar);
	} while ((usedChars.count(userChar) == 1) || (allowedChars.count(userChar) != 1));

	usedChars[userChar] = userChar;

	return userChar;
}

void ISmallGames::HangingMan::addToUserWord(char userChar)
{
	size_t found = word.find(userChar);

	if (found == std::string::npos)
		m_efforts++;

	while (found != std::string::npos)
	{
		userWord[found] = userChar;
		found = word.find(userChar, found+1);
	}

	return;
}
<commit_msg>fixed issue #2 -> multiple chars at one input<commit_after>// SmallGames.cpp : Definiert die exportierten Funktionen fr die DLL-Anwendung.
// @author Florian Dahlitz

#include "stdafx.h"

#include "SmallGames.h"

void ISmallGames::HangingMan::setupGame()
{
	wordlist = getWordlist();
	word = getRandomWord(wordlist);
	boost::to_upper(word);
	userWord = "_";

	for (unsigned int i = 0; i < word.size() - 1; ++i)
		userWord += "_";

	return;
}

void ISmallGames::HangingMan::buildWindow()
{
	system("cls");

	std::cout << "THE HANGING MAN" << std::endl;

	for (it = hangingManParts.begin(); it != hangingManParts.end(); ++it)
		if (it->first == m_efforts)
			std::cout << it->second << std::endl << std::endl;

	for (int i = 0; i < (m_hangingMan - manHeight[m_efforts]); ++i)
		std::cout << "\n";

	std::cout << "" << std::endl << std::endl;	// clean buffer + better overview

	for (int i = 0; i < userWord.length(); i++)
		std::cout << userWord[i] << " ";

	std::cout << std::endl; // clean buffer

	return;
}

std::map<unsigned int, std::string> ISmallGames::HangingMan::getWordlist()
{
	unsigned int i = 0;
	std::string strWord;
	std::map<unsigned int, std::string> wordlist;
	std::ifstream worldlistFile(m_path);
	if (worldlistFile.fail())
		std::cout << m_path << std::endl;
	// TODO: change reading file w/ vectors -> read something about
	while (std::getline(worldlistFile, strWord))
	{
		wordlist[i] = strWord;
		std::cout << ++i << " - " << strWord << std::endl;
	}

	return wordlist;
}

std::string ISmallGames::HangingMan::getRandomWord(std::map<unsigned int, std::string> wordlist)
{
	std::string randomWord;
	auto iter = wordlist.begin();

	srand(time(NULL));
	std::advance(iter, rand() % wordlist.size());
	randomWord = iter->second;

	wordlist.erase(iter);

	return randomWord;
}

void ISmallGames::HangingMan::playGame()
{
	do {
		buildWindow();

		char userChar = getUserChar();
		addToUserWord(userChar);

	} while (userWord.compare(word) && (m_efforts != 6));

	return;
}

char ISmallGames::HangingMan::getUserChar()
{
	std::string userInput;
	char userChar;

	do {
		std::cout << "Type in a character: ";
		std::cin >> userInput;
		userChar = userInput[0];
		userChar = toupper(userChar);
	} while ((usedChars.count(userChar) == 1) || (allowedChars.count(userChar) != 1));

	usedChars[userChar] = userChar;

	return userChar;
}

void ISmallGames::HangingMan::addToUserWord(char userChar)
{
	size_t found = word.find(userChar);

	if (found == std::string::npos)
		m_efforts++;

	while (found != std::string::npos)
	{
		userWord[found] = userChar;
		found = word.find(userChar, found+1);
	}

	return;
}
<|endoftext|>


<commit_before>#include "Iop_Sysmem.h"
#include "../Log.h"
#include "Iop_SifMan.h"

using namespace Iop;

#define LOG_NAME ("iop_sysmem")

#define FUNCTION_ALLOCATEMEMORY			"AllocateMemory"
#define FUNCTION_FREEMEMORY				"FreeMemory"
#define FUNCTION_PRINTF					"printf"
#define FUNCTION_QUERYMEMSIZE			"QueryMemSize"
#define FUNCTION_QUERYMAXFREEMEMSIZE	"QueryMaxFreeMemSize"

#define MIN_BLOCK_SIZE  0x20

CSysmem::CSysmem(uint8* ram, uint32 memoryBegin, uint32 memoryEnd, uint32 blockBase, CStdio& stdio, CIoman& ioman, CSifMan& sifMan)
: m_iopRam(ram)
, m_memoryBegin(memoryBegin)
, m_memoryEnd(memoryEnd)
, m_stdio(stdio)
, m_ioman(ioman)
, m_memorySize(memoryEnd - memoryBegin)
, m_blocks(reinterpret_cast<BLOCK*>(&ram[blockBase]), 1, MAX_BLOCKS)
{
	//Initialize block map
	m_headBlockId = m_blocks.Allocate();
	BLOCK* block = m_blocks[m_headBlockId];
	block->address		= m_memorySize;
	block->size			= 0;
	block->nextBlock	= 0;

	//Register sif module
	sifMan.RegisterModule(MODULE_ID, this);
}

CSysmem::~CSysmem()
{

}

std::string CSysmem::GetId() const
{
	return "sysmem";
}

std::string CSysmem::GetFunctionName(unsigned int functionId) const
{
	switch(functionId)
	{
	case 4:
		return FUNCTION_ALLOCATEMEMORY;
		break;
	case 5:
		return FUNCTION_FREEMEMORY;
		break;
	case 6:
		return FUNCTION_QUERYMEMSIZE;
		break;
	case 7:
		return FUNCTION_QUERYMAXFREEMEMSIZE;
		break;
	case 14:
		return FUNCTION_PRINTF;
		break;
	default:
		return "unknown";
		break;
	}
}

void CSysmem::Invoke(CMIPS& context, unsigned int functionId)
{
	switch(functionId)
	{
	case 4:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(AllocateMemory(
			context.m_State.nGPR[CMIPS::A1].nV[0],
			context.m_State.nGPR[CMIPS::A0].nV[0],
			context.m_State.nGPR[CMIPS::A2].nV[0]
			));
		break;
	case 5:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(FreeMemory(
			context.m_State.nGPR[CMIPS::A0].nV[0]
			));
		break;
	case 6:
		context.m_State.nGPR[CMIPS::V0].nD0 = m_memorySize;
		break;
	case 7:
		context.m_State.nGPR[CMIPS::V0].nD0 = QueryMaxFreeMemSize();
		break;
	case 14:
		m_stdio.__printf(context);
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "%s(%0.8X): Unknown function (%d) called.\r\n", __FUNCTION__, context.m_State.nPC, functionId);
		break;
	}
}

bool CSysmem::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
	switch(method)
	{
	case 0x01:
		assert(retSize == 4);
		ret[0] = SifAllocate(args[0]);
		break;
	case 0x02:
		assert(argsSize == 4);
		ret[0] = SifFreeMemory(args[0]);
		break;
	case 0x03:
		assert(argsSize >= 4);
		assert(retSize == 4);
		ret[0] = SifLoadMemory(args[0], reinterpret_cast<const char*>(args) + 4);
		break;
	case 0x04:
		assert(retSize == 4);
		ret[0] = SifAllocateSystemMemory(args[0], args[1], args[2]);
		break;
	case 0x06:
		ret[0] = m_memorySize;
		break;
	case 0x07:
		ret[0] = QueryMaxFreeMemSize();
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "Unknown method invoked (0x%0.8X).\r\n", method);
		break;
	}
	return true;
}

uint32 CSysmem::QueryMaxFreeMemSize()
{
	uint32 maxSize = 0;
	uint32 begin = 0;
	uint32* nextBlockId = &m_headBlockId;
	BLOCK* nextBlock = m_blocks[*nextBlockId];
	while (nextBlock != NULL)
	{
		uint32 end = nextBlock->address;
		if ((end - begin) >= maxSize)
		{
			maxSize = end - begin;
		}
		begin = nextBlock->address + nextBlock->size;
		nextBlockId = &nextBlock->nextBlock;
		nextBlock = m_blocks[*nextBlockId];
	}
	return maxSize;
}

uint32 CSysmem::AllocateMemory(uint32 size, uint32 flags, uint32 wantedAddress)
{
	CLog::GetInstance().Print(LOG_NAME, "AllocateMemory(size = 0x%0.8X, flags = 0x%0.8X, wantedAddress = 0x%0.8X);\r\n",
		size, flags, wantedAddress);

	const uint32 blockSize = MIN_BLOCK_SIZE;
	size = ((size + (blockSize - 1)) / blockSize) * blockSize;

	if(flags == 0 || flags == 1)
	{
		uint32 begin = 0;
		uint32* nextBlockId = &m_headBlockId;
		BLOCK* nextBlock = m_blocks[*nextBlockId];
		while(nextBlock != NULL)
		{
			uint32 end = nextBlock->address;
			if((end - begin) >= size)
			{
				break;
			}
			begin = nextBlock->address + nextBlock->size;
			nextBlockId = &nextBlock->nextBlock;
			nextBlock = m_blocks[*nextBlockId];
		}

		if(nextBlock != NULL)
		{
			uint32 newBlockId = m_blocks.Allocate();
			assert(newBlockId != 0);
			if(newBlockId == 0)
			{
				return 0;
			}
			BLOCK* newBlock = m_blocks[newBlockId];
			newBlock->address	= begin;
			newBlock->size		= size;
			newBlock->nextBlock	= *nextBlockId;
			*nextBlockId = newBlockId;
			return begin + m_memoryBegin;
		}
	}
	else if(flags == 2)
	{
		assert(wantedAddress != 0);
		wantedAddress -= m_memoryBegin;

		uint32 begin = 0;
		uint32* nextBlockId = &m_headBlockId;
		BLOCK* nextBlock = m_blocks[*nextBlockId];
		while(nextBlock != NULL)
		{
			uint32 end = nextBlock->address;
			if(begin > wantedAddress)
			{
				//Couldn't find suitable space
				nextBlock = NULL;
				break;
			}
			if(
				(begin <= wantedAddress) &&
				((end - begin) >= size)
				)
			{
				break;
			}
			begin = nextBlock->address + nextBlock->size;
			nextBlockId = &nextBlock->nextBlock;
			nextBlock = m_blocks[*nextBlockId];
		}

		if(nextBlock != NULL)
		{
			uint32 newBlockId = m_blocks.Allocate();
			assert(newBlockId != 0);
			if(newBlockId == 0)
			{
				return 0;
			}
			BLOCK* newBlock = m_blocks[newBlockId];
			newBlock->address	= wantedAddress;
			newBlock->size		= size;
			newBlock->nextBlock	= *nextBlockId;
			*nextBlockId = newBlockId;
			return wantedAddress + m_memoryBegin;
		}
	}
	else
	{
		assert(0);
	}

	assert(0);
	return NULL;
}

uint32 CSysmem::FreeMemory(uint32 address)
{
	CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);

	address -= m_memoryBegin;
	//Search for block pointing at the address
	uint32* nextBlockId = &m_headBlockId;
	BLOCK* nextBlock = m_blocks[*nextBlockId];
	while(nextBlock != NULL)
	{
		if(nextBlock->address == address)
		{
			break;
		}
		nextBlockId = &nextBlock->nextBlock;
		nextBlock = m_blocks[*nextBlockId];
	}

	if(nextBlock != NULL)
	{
		m_blocks.Free(*nextBlockId);
		*nextBlockId = nextBlock->nextBlock;
	}
	else
	{
		CLog::GetInstance().Print(LOG_NAME, "%s: Trying to unallocate an unexisting memory block (0x%0.8X).\r\n", __FUNCTION__, address);
	}
	return 0;
}

uint32 CSysmem::SifAllocate(uint32 nSize)
{
	uint32 result = AllocateMemory(nSize, 0, 0);
	CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = Allocate(size = 0x%0.8X);\r\n",
		result, nSize);
	return result;
}

uint32 CSysmem::SifAllocateSystemMemory(uint32 nSize, uint32 nFlags, uint32 nPtr)
{
	uint32 result = AllocateMemory(nSize, nFlags, nPtr);
	CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = AllocateSystemMemory(flags = 0x%0.8X, size = 0x%0.8X, ptr = 0x%0.8X);\r\n",
		result, nFlags, nSize, nPtr);
	return result;
}

uint32 CSysmem::SifLoadMemory(uint32 address, const char* filePath)
{
	CLog::GetInstance().Print(LOG_NAME, "LoadMemory(address = 0x%0.8X, filePath = '%s');\r\n",
		address, filePath);

	auto fd = m_ioman.Open(Ioman::CDevice::OPEN_FLAG_RDONLY, filePath);
	if(static_cast<int32>(fd) < 0)
	{
		return fd;
	}
	uint32 fileSize = m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_END);
	m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_SET);
	m_ioman.Read(fd, fileSize, m_iopRam + address);
	m_ioman.Close(fd);
	return 0;
}

uint32 CSysmem::SifFreeMemory(uint32 address)
{
	CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);
	FreeMemory(address);
	return 0;
}
<commit_msg>Changed minimum memory alloc block size to 256 bytes.<commit_after>#include "Iop_Sysmem.h"
#include "../Log.h"
#include "Iop_SifMan.h"

using namespace Iop;

#define LOG_NAME ("iop_sysmem")

#define FUNCTION_ALLOCATEMEMORY			"AllocateMemory"
#define FUNCTION_FREEMEMORY				"FreeMemory"
#define FUNCTION_PRINTF					"printf"
#define FUNCTION_QUERYMEMSIZE			"QueryMemSize"
#define FUNCTION_QUERYMAXFREEMEMSIZE	"QueryMaxFreeMemSize"

#define MIN_BLOCK_SIZE  0x100

CSysmem::CSysmem(uint8* ram, uint32 memoryBegin, uint32 memoryEnd, uint32 blockBase, CStdio& stdio, CIoman& ioman, CSifMan& sifMan)
: m_iopRam(ram)
, m_memoryBegin(memoryBegin)
, m_memoryEnd(memoryEnd)
, m_stdio(stdio)
, m_ioman(ioman)
, m_memorySize(memoryEnd - memoryBegin)
, m_blocks(reinterpret_cast<BLOCK*>(&ram[blockBase]), 1, MAX_BLOCKS)
{
	//Initialize block map
	m_headBlockId = m_blocks.Allocate();
	BLOCK* block = m_blocks[m_headBlockId];
	block->address		= m_memorySize;
	block->size			= 0;
	block->nextBlock	= 0;

	//Register sif module
	sifMan.RegisterModule(MODULE_ID, this);
}

CSysmem::~CSysmem()
{

}

std::string CSysmem::GetId() const
{
	return "sysmem";
}

std::string CSysmem::GetFunctionName(unsigned int functionId) const
{
	switch(functionId)
	{
	case 4:
		return FUNCTION_ALLOCATEMEMORY;
		break;
	case 5:
		return FUNCTION_FREEMEMORY;
		break;
	case 6:
		return FUNCTION_QUERYMEMSIZE;
		break;
	case 7:
		return FUNCTION_QUERYMAXFREEMEMSIZE;
		break;
	case 14:
		return FUNCTION_PRINTF;
		break;
	default:
		return "unknown";
		break;
	}
}

void CSysmem::Invoke(CMIPS& context, unsigned int functionId)
{
	switch(functionId)
	{
	case 4:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(AllocateMemory(
			context.m_State.nGPR[CMIPS::A1].nV[0],
			context.m_State.nGPR[CMIPS::A0].nV[0],
			context.m_State.nGPR[CMIPS::A2].nV[0]
			));
		break;
	case 5:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(FreeMemory(
			context.m_State.nGPR[CMIPS::A0].nV[0]
			));
		break;
	case 6:
		context.m_State.nGPR[CMIPS::V0].nD0 = m_memorySize;
		break;
	case 7:
		context.m_State.nGPR[CMIPS::V0].nD0 = QueryMaxFreeMemSize();
		break;
	case 14:
		m_stdio.__printf(context);
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "%s(%0.8X): Unknown function (%d) called.\r\n", __FUNCTION__, context.m_State.nPC, functionId);
		break;
	}
}

bool CSysmem::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
	switch(method)
	{
	case 0x01:
		assert(retSize == 4);
		ret[0] = SifAllocate(args[0]);
		break;
	case 0x02:
		assert(argsSize == 4);
		ret[0] = SifFreeMemory(args[0]);
		break;
	case 0x03:
		assert(argsSize >= 4);
		assert(retSize == 4);
		ret[0] = SifLoadMemory(args[0], reinterpret_cast<const char*>(args) + 4);
		break;
	case 0x04:
		assert(retSize == 4);
		ret[0] = SifAllocateSystemMemory(args[0], args[1], args[2]);
		break;
	case 0x06:
		ret[0] = m_memorySize;
		break;
	case 0x07:
		ret[0] = QueryMaxFreeMemSize();
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "Unknown method invoked (0x%0.8X).\r\n", method);
		break;
	}
	return true;
}

uint32 CSysmem::QueryMaxFreeMemSize()
{
	uint32 maxSize = 0;
	uint32 begin = 0;
	uint32* nextBlockId = &m_headBlockId;
	BLOCK* nextBlock = m_blocks[*nextBlockId];
	while (nextBlock != NULL)
	{
		uint32 end = nextBlock->address;
		if ((end - begin) >= maxSize)
		{
			maxSize = end - begin;
		}
		begin = nextBlock->address + nextBlock->size;
		nextBlockId = &nextBlock->nextBlock;
		nextBlock = m_blocks[*nextBlockId];
	}
	return maxSize;
}

uint32 CSysmem::AllocateMemory(uint32 size, uint32 flags, uint32 wantedAddress)
{
	CLog::GetInstance().Print(LOG_NAME, "AllocateMemory(size = 0x%0.8X, flags = 0x%0.8X, wantedAddress = 0x%0.8X);\r\n",
		size, flags, wantedAddress);

	const uint32 blockSize = MIN_BLOCK_SIZE;
	size = ((size + (blockSize - 1)) / blockSize) * blockSize;

	if(flags == 0 || flags == 1)
	{
		uint32 begin = 0;
		uint32* nextBlockId = &m_headBlockId;
		BLOCK* nextBlock = m_blocks[*nextBlockId];
		while(nextBlock != NULL)
		{
			uint32 end = nextBlock->address;
			if((end - begin) >= size)
			{
				break;
			}
			begin = nextBlock->address + nextBlock->size;
			nextBlockId = &nextBlock->nextBlock;
			nextBlock = m_blocks[*nextBlockId];
		}

		if(nextBlock != NULL)
		{
			uint32 newBlockId = m_blocks.Allocate();
			assert(newBlockId != 0);
			if(newBlockId == 0)
			{
				return 0;
			}
			BLOCK* newBlock = m_blocks[newBlockId];
			newBlock->address	= begin;
			newBlock->size		= size;
			newBlock->nextBlock	= *nextBlockId;
			*nextBlockId = newBlockId;
			return begin + m_memoryBegin;
		}
	}
	else if(flags == 2)
	{
		assert(wantedAddress != 0);
		wantedAddress -= m_memoryBegin;

		uint32 begin = 0;
		uint32* nextBlockId = &m_headBlockId;
		BLOCK* nextBlock = m_blocks[*nextBlockId];
		while(nextBlock != NULL)
		{
			uint32 end = nextBlock->address;
			if(begin > wantedAddress)
			{
				//Couldn't find suitable space
				nextBlock = NULL;
				break;
			}
			if(
				(begin <= wantedAddress) &&
				((end - begin) >= size)
				)
			{
				break;
			}
			begin = nextBlock->address + nextBlock->size;
			nextBlockId = &nextBlock->nextBlock;
			nextBlock = m_blocks[*nextBlockId];
		}

		if(nextBlock != NULL)
		{
			uint32 newBlockId = m_blocks.Allocate();
			assert(newBlockId != 0);
			if(newBlockId == 0)
			{
				return 0;
			}
			BLOCK* newBlock = m_blocks[newBlockId];
			newBlock->address	= wantedAddress;
			newBlock->size		= size;
			newBlock->nextBlock	= *nextBlockId;
			*nextBlockId = newBlockId;
			return wantedAddress + m_memoryBegin;
		}
	}
	else
	{
		assert(0);
	}

	assert(0);
	return NULL;
}

uint32 CSysmem::FreeMemory(uint32 address)
{
	CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);

	address -= m_memoryBegin;
	//Search for block pointing at the address
	uint32* nextBlockId = &m_headBlockId;
	BLOCK* nextBlock = m_blocks[*nextBlockId];
	while(nextBlock != NULL)
	{
		if(nextBlock->address == address)
		{
			break;
		}
		nextBlockId = &nextBlock->nextBlock;
		nextBlock = m_blocks[*nextBlockId];
	}

	if(nextBlock != NULL)
	{
		m_blocks.Free(*nextBlockId);
		*nextBlockId = nextBlock->nextBlock;
	}
	else
	{
		CLog::GetInstance().Print(LOG_NAME, "%s: Trying to unallocate an unexisting memory block (0x%0.8X).\r\n", __FUNCTION__, address);
	}
	return 0;
}

uint32 CSysmem::SifAllocate(uint32 nSize)
{
	uint32 result = AllocateMemory(nSize, 0, 0);
	CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = Allocate(size = 0x%0.8X);\r\n",
		result, nSize);
	return result;
}

uint32 CSysmem::SifAllocateSystemMemory(uint32 nSize, uint32 nFlags, uint32 nPtr)
{
	uint32 result = AllocateMemory(nSize, nFlags, nPtr);
	CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = AllocateSystemMemory(flags = 0x%0.8X, size = 0x%0.8X, ptr = 0x%0.8X);\r\n",
		result, nFlags, nSize, nPtr);
	return result;
}

uint32 CSysmem::SifLoadMemory(uint32 address, const char* filePath)
{
	CLog::GetInstance().Print(LOG_NAME, "LoadMemory(address = 0x%0.8X, filePath = '%s');\r\n",
		address, filePath);

	auto fd = m_ioman.Open(Ioman::CDevice::OPEN_FLAG_RDONLY, filePath);
	if(static_cast<int32>(fd) < 0)
	{
		return fd;
	}
	uint32 fileSize = m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_END);
	m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_SET);
	m_ioman.Read(fd, fileSize, m_iopRam + address);
	m_ioman.Close(fd);
	return 0;
}

uint32 CSysmem::SifFreeMemory(uint32 address)
{
	CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);
	FreeMemory(address);
	return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
File: KeyMappings.cpp
Created: 10/3/2017 11:57:46 AM
Copyright (c) 2017 Turn Tactics

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Purpose: Contains all of the key mapping functions and data for keyboard input
from SDL

Author: James Womack

********************************************************************************/
#include "KeyMappings.h"
#include "../Math/Common.h"
#include <SDL.h>

namespace lse {

  // A map that maps KeyType to a string.
  const containers::UnorderedMap<KeyType, String> gc_keyTextMappings{
    { KeyType::Key0, "0" },{ KeyType::Key1, "1" },
    { KeyType::Key2, "2" },{ KeyType::Key3, "3" },
    { KeyType::Key4, "4" },{ KeyType::Key5, "5" },
    { KeyType::Key6, "6" },{ KeyType::Key7, "7" },
    { KeyType::Key8, "8" },{ KeyType::Key9, "9" },
    { KeyType::KeyA, "a" },{ KeyType::KeyB, "b" },
    { KeyType::KeyC, "c" },{ KeyType::KeyD, "d" },
    { KeyType::KeyE, "e" },{ KeyType::KeyF, "f" },
    { KeyType::KeyG, "g" },{ KeyType::KeyH, "h" },
    { KeyType::KeyI, "i" },{ KeyType::KeyJ, "j" },
    { KeyType::KeyL, "l" },{ KeyType::KeyK, "k" },
    { KeyType::KeyN, "n" },{ KeyType::KeyM, "m" },
    { KeyType::KeyP, "p" },{ KeyType::KeyO, "o" },
    { KeyType::KeyR, "r" },{ KeyType::KeyQ, "q" },
    { KeyType::KeyT, "t" },{ KeyType::KeyS, "s" },
    { KeyType::KeyV, "v" },{ KeyType::KeyU, "u" },
    { KeyType::KeyW, "w" },{ KeyType::KeyX, "x" },
    { KeyType::KeyY, "y" },{ KeyType::KeyZ, "z" },
    { KeyType::KeyTab, "\t" },{ KeyType::KeyEnter, "\n" },
    { KeyType::KeyBracketLeft, "[" },{ KeyType::KeyBracketRight, "]" },
    { KeyType::KeyLeftParenthesis, "(" },{ KeyType::KeyRightParenthesis, ")" },
    { KeyType::KeyCurlyBracketLeft, "{" },{ KeyType::KeyCurlyBracketRight, "}" },
    { KeyType::KeyAngleBracketLeft, "{" },{ KeyType::KeyAngleBracketRight, "}" },
    { KeyType::KeyColon, ":" },{ KeyType::KeySemicolon, ";" },
    { KeyType::KeyComma, "," },{ KeyType::KeyEnter, "\n" },
    { KeyType::KeySlash, "/" },{ KeyType::KeyBackslash, "\\" },
    { KeyType::KeyExclamation, "!" },{ KeyType::KeyAt, "@" },
    { KeyType::KeyHash, "#" },{ KeyType::KeyPercent, "%" },
    { KeyType::KeyHat, "^" },{ KeyType::KeyAmpersand, "&" },
    { KeyType::KeyStar, "*" },{ KeyType::KeyMinus, "-" },
    { KeyType::KeyUnderscore, "_" },{ KeyType::KeyEquals, "=" },
    { KeyType::KeyPlus, "+" },
    { KeyType::KeyApostrophe, "'" },{ KeyType::KeyQuotes, "\"" },
    { KeyType::KeyBacktick, "`" },{ KeyType::KeyQuestion, "?" },
    { KeyType::KeyBackspace, "\\backspace\\" },{ KeyType::KeyDelete, "\\delete\\" },
    { KeyType::KeyDollar, "$" },{ KeyType::KeyHome, "\\home\\" },
    { KeyType::KeyPageDown, "\\pg-down\\" },{ KeyType::KeyPageUp, "\\pg-up\\" },
    { KeyType::KeyEnd, "\\end\\" },{ KeyType::KeyInsert, "\\insert\\" },
    { KeyType::KeyF1, "\\f1\\" },{ KeyType::KeyF2, "\\f2\\" },
    { KeyType::KeyF3, "\\f3\\" },{ KeyType::KeyF4, "\\f4\\" },
    { KeyType::KeyF5, "\\f5\\" },{ KeyType::KeyF6, "\\f6\\" },
    { KeyType::KeyF7, "\\f7\\" },{ KeyType::KeyF8, "\\f8\\" },
    { KeyType::KeyF9, "\\f9\\" },{ KeyType::KeyF10, "\\f10\\" },
    { KeyType::KeyF11, "\\f11\\" },{ KeyType::KeyF12, "\\f12\\" },
    { KeyType::KeyArrowUp, "\\^\\" },{ KeyType::KeyArrowDown, "\\v\\" },
    { KeyType::KeyArrowLeft, "\\<\\" },{ KeyType::KeyArrowRight, "\\>\\" },
    { KeyType::KeyPeriod, "." },{KeyType::KeyPipe, "|" },
    { KeyType::KeyNone, "" }
  };

  const containers::UnorderedMap<KeyModiferType, String> gc_keyModiferTextMappings {
    { KeyModiferType::KeyNone, "" }, { KeyModiferType::KeyAlt, "Alt" },
    { KeyModiferType::KeyCtrl, "Ctrl" }, { KeyModiferType::KeyCtrlAlt, "Ctrl+Alt"},
    { KeyModiferType::KeyCtrlShift, "Ctrl+Shift" }, { KeyModiferType::KeyCtrlShiftAlt, "Ctrl+Shift+Alt"},
    { KeyModiferType::KeyShift, "Shift" }, { KeyModiferType::KeyShiftAlt, "Shift+Alt" }
  };

  const containers::UnorderedMap<SDL_Keycode, KeyType> gc_sdlKeyMapping {
    { SDLK_0, KeyType::Key0 },{ SDLK_1, KeyType::Key1 },
    { SDLK_2, KeyType::Key2 },{ SDLK_3, KeyType::Key3 },
    { SDLK_4, KeyType::Key4 },{ SDLK_5, KeyType::Key5 },
    { SDLK_6, KeyType::Key6 },{ SDLK_7, KeyType::Key7 },
    { SDLK_8, KeyType::Key8 },{ SDLK_9, KeyType::Key9 },
    { SDLK_a, KeyType::KeyA },{ SDLK_b, KeyType::KeyB },
    { SDLK_c, KeyType::KeyC },{ SDLK_d, KeyType::KeyD },
    { SDLK_e, KeyType::KeyE },{ SDLK_f, KeyType::KeyF },
    { SDLK_g, KeyType::KeyG },{ SDLK_h, KeyType::KeyH },
    { SDLK_i, KeyType::KeyI },{ SDLK_j, KeyType::KeyJ },
    { SDLK_k, KeyType::KeyK },{ SDLK_l, KeyType::KeyL },
    { SDLK_m, KeyType::KeyM },{ SDLK_n, KeyType::KeyN },
    { SDLK_o, KeyType::KeyO },{ SDLK_p, KeyType::KeyP },
    { SDLK_q, KeyType::KeyQ },{ SDLK_r, KeyType::KeyR },
    { SDLK_s, KeyType::KeyS },{ SDLK_t, KeyType::KeyT },
    { SDLK_u, KeyType::KeyU },{ SDLK_v, KeyType::KeyV },
    { SDLK_w, KeyType::KeyW },{ SDLK_x, KeyType::KeyX },
    { SDLK_y, KeyType::KeyY },{ SDLK_z, KeyType::KeyZ },
    { SDLK_y, KeyType::KeyY },{ SDLK_z, KeyType::KeyAccent },
  };

  // Maps SDL_Event type to a KeyState type if applicable
  inline KeyState get_sdl_key_state(SDL_Event& e)
  {
    return e.type == SDL_KEYDOWN ? KeyState::KeyDown
      : e.type == SDL_KEYUP ? KeyState::KeyUp : KeyState::KeyNone;
  }

  inline

  inline String get_text_character(KeyEvent& keyEvent)
  {
    auto keyStr = gc_keyTextMappings.at(keyEvent.key());

    if (is_alpha_keystroke(keyEvent) && keyEvent.modifier() == KeyModiferType::KeyShift)
    {
        return to_upper(keyStr);
    }

    return keyStr;
  }

  inline String get_key_event_string(KeyEvent& keyEvent)
  {
    auto keyStr = to_upper(gc_keyTextMappings.at(keyEvent.key()));
    auto modiferStr = to_upper(gc_keyModiferTextMappings.at(keyEvent.modifier()));

    if (keyStr.length() > 0 && modiferStr.length() > 0)
    {
      return modiferStr + "+" + keyStr;
    } else if (keyStr.length() > 0)
    {
      return keyStr;
    } else if (modiferStr.length() > 0)
    {
      return modiferStr;
    } else
    {
      return "\\none\\";
    }
  }
}
<commit_msg>Revert "i dont know"<commit_after>/******************************************************************************
File: KeyMappings.cpp
Created: 10/3/2017 11:57:46 AM
Copyright (c) 2017 Turn Tactics
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Purpose: Contains all of the key mapping functions and data for keyboard input
from SDL
Author: James Womack
********************************************************************************/
#include "KeyMappings.h"
#include "../Math/Common.h"
#include <SDL.h>

namespace lse {

	// A map that maps KeyType to a string.
	const containers::UnorderedMap<KeyType, String> gc_keyTextMappings {
		{ KeyType::Key0, "0" }, { KeyType::Key1, "1" },
		{ KeyType::Key2, "2" }, { KeyType::Key3, "3" },
		{ KeyType::Key4, "4" }, { KeyType::Key5, "5" },
		{ KeyType::Key6, "6" }, { KeyType::Key7, "7" },
		{ KeyType::Key8, "8" }, { KeyType::Key9, "9" },
		{ KeyType::KeyA, "a" }, { KeyType::KeyB, "b" },
		{ KeyType::KeyC, "c" }, { KeyType::KeyD, "d" },
		{ KeyType::KeyE, "e" }, { KeyType::KeyF, "f" },
		{ KeyType::KeyG, "g" }, { KeyType::KeyH, "h" },
		{ KeyType::KeyI, "i" }, { KeyType::KeyJ, "j" },
		{ KeyType::KeyL, "l" }, { KeyType::KeyK, "k" },
		{ KeyType::KeyN, "n" }, { KeyType::KeyM, "m" },
		{ KeyType::KeyP, "p" }, { KeyType::KeyO, "o" },
		{ KeyType::KeyR, "r" }, { KeyType::KeyQ, "q" },
		{ KeyType::KeyT, "t" }, { KeyType::KeyS, "s" },
		{ KeyType::KeyV, "v" }, { KeyType::KeyU, "u" },
		{ KeyType::KeyW, "w" }, { KeyType::KeyX, "x" },
		{ KeyType::KeyY, "y" }, { KeyType::KeyZ, "z" },
		{ KeyType::KeyTab, "\t" }, { KeyType::KeyEnter, "\n" },
		{ KeyType::KeyBracketLeft, "[" }, { KeyType::KeyBracketRight, "]" },
		{ KeyType::KeyLeftParenthesis, "(" }, { KeyType::KeyRightParenthesis, ")" },
		{ KeyType::KeyCurlyBracketLeft, "{" }, { KeyType::KeyCurlyBracketRight, "}" },
		{ KeyType::KeyAngleBracketLeft, "{" }, { KeyType::KeyAngleBracketRight, "}" },
		{ KeyType::KeyColon, ":" }, { KeyType::KeySemicolon, ";" },
		{ KeyType::KeyComma, "," }, { KeyType::KeyEnter, "\n" },
		{ KeyType::KeySlash, "/" }, { KeyType::KeyBackslash, "\\" },
		{ KeyType::KeyExclamation, "!" }, { KeyType::KeyAt, "@" },
		{ KeyType::KeyHash, "#" }, { KeyType::KeyPercent, "%" },
		{ KeyType::KeyHat, "^" }, { KeyType::KeyAmpersand, "&" },
		{ KeyType::KeyStar, "*" }, { KeyType::KeyMinus, "-" },
		{ KeyType::KeyUnderscore, "_" }, { KeyType::KeyEquals, "=" },
		{ KeyType::KeyPlus, "+" },
		{ KeyType::KeyApostrophe, "'" }, { KeyType::KeyQuotes, "\"" },
		{ KeyType::KeyBacktick, "`" }, { KeyType::KeyQuestion, "?" },
		{ KeyType::KeyBackspace, "\\backspace\\" }, { KeyType::KeyDelete, "\\delete\\" },
		{ KeyType::KeyDollar, "$" }, { KeyType::KeyHome, "\\home\\" },
		{ KeyType::KeyPageDown, "\\pg-down\\" }, { KeyType::KeyPageUp, "\\pg-up\\" },
		{ KeyType::KeyEnd, "\\end\\" }, { KeyType::KeyInsert, "\\insert\\" },
		{ KeyType::KeyF1, "\\f1\\" }, { KeyType::KeyF2, "\\f2\\" },
		{ KeyType::KeyF3, "\\f3\\" }, { KeyType::KeyF4, "\\f4\\" },
		{ KeyType::KeyF5, "\\f5\\" }, { KeyType::KeyF6, "\\f6\\" },
		{ KeyType::KeyF7, "\\f7\\" }, { KeyType::KeyF8, "\\f8\\" },
		{ KeyType::KeyF9, "\\f9\\" }, { KeyType::KeyF10, "\\f10\\" },
		{ KeyType::KeyF11, "\\f11\\" }, { KeyType::KeyF12, "\\f12\\" },
		{ KeyType::KeyArrowUp, "\\^\\" }, { KeyType::KeyArrowDown, "\\v\\" },
		{ KeyType::KeyArrowLeft, "\\<\\" }, { KeyType::KeyArrowRight, "\\>\\" },
		{ KeyType::KeyPeriod, "." }, { KeyType::KeyPipe, "|" },
		{ KeyType::KeyNone, "" }
	};

	const containers::UnorderedMap<KeyModiferType, String> gc_keyModiferTextMappings {
		{ KeyModiferType::KeyNone, "" }, { KeyModiferType::KeyAlt, "Alt" },
		{ KeyModiferType::KeyCtrl, "Ctrl" }, { KeyModiferType::KeyCtrlAlt, "Ctrl+Alt" },
		{ KeyModiferType::KeyCtrlShift, "Ctrl+Shift" }, { KeyModiferType::KeyCtrlShiftAlt, "Ctrl+Shift+Alt" },
		{ KeyModiferType::KeyShift, "Shift" }, { KeyModiferType::KeyShiftAlt, "Shift+Alt" }
	};

	const containers::UnorderedMap<SDL_Keycode, KeyType> gc_sdlKeyMapping {
		{ SDLK_0, KeyType::Key0 }, { SDLK_1, KeyType::Key1 },
		{ SDLK_2, KeyType::Key2 }, { SDLK_3, KeyType::Key3 },
		{ SDLK_4, KeyType::Key4 }, { SDLK_5, KeyType::Key5 },
		{ SDLK_6, KeyType::Key6 }, { SDLK_7, KeyType::Key7 },
		{ SDLK_8, KeyType::Key8 }, { SDLK_9, KeyType::Key9 },
		{ SDLK_a, KeyType::KeyA }, { SDLK_b, KeyType::KeyB },
		{ SDLK_c, KeyType::KeyC }, { SDLK_d, KeyType::KeyD },
		{ SDLK_e, KeyType::KeyE }, { SDLK_f, KeyType::KeyF },
		{ SDLK_g, KeyType::KeyG }, { SDLK_h, KeyType::KeyH },
		{ SDLK_i, KeyType::KeyI }, { SDLK_j, KeyType::KeyJ },
		{ SDLK_k, KeyType::KeyK }, { SDLK_l, KeyType::KeyL },
		{ SDLK_m, KeyType::KeyM }, { SDLK_n, KeyType::KeyN },
		{ SDLK_o, KeyType::KeyO }, { SDLK_p, KeyType::KeyP },
		{ SDLK_q, KeyType::KeyQ }, { SDLK_r, KeyType::KeyR },
		{ SDLK_s, KeyType::KeyS }, { SDLK_t, KeyType::KeyT },
		{ SDLK_u, KeyType::KeyU }, { SDLK_v, KeyType::KeyV },
		{ SDLK_w, KeyType::KeyW }, { SDLK_x, KeyType::KeyX },
		{ SDLK_y, KeyType::KeyY }, { SDLK_z, KeyType::KeyZ },
		{ SDLK_y, KeyType::KeyY }, { SDLK_z, KeyType::KeyAccent },
	};

	// Maps SDL_Event type to a KeyState type if applicable
	inline KeyState get_sdl_key_state(SDL_Event& e) {
		return e.type == SDL_KEYDOWN ? KeyState::KeyDown
			: e.type == SDL_KEYUP ? KeyState::KeyUp : KeyState::KeyNone;
	}

	inline

		inline String get_text_character(KeyEvent& keyEvent) {
		auto keyStr = gc_keyTextMappings.at(keyEvent.key());

		if(is_alpha_keystroke(keyEvent) && keyEvent.modifier() == KeyModiferType::KeyShift) {
			return to_upper(keyStr);
		}

		return keyStr;
	}

	inline String get_key_event_string(KeyEvent& keyEvent) {
		auto keyStr = to_upper(gc_keyTextMappings.at(keyEvent.key()));
		auto modiferStr = to_upper(gc_keyModiferTextMappings.at(keyEvent.modifier()));

		if(keyStr.length() > 0 && modiferStr.length() > 0) {
			return modiferStr + "+" + keyStr;
		} else if(keyStr.length() > 0) {
			return keyStr;
		} else if(modiferStr.length() > 0) {
			return modiferStr;
		} else {
			return "\\none\\";
		}
	}
}<|endoftext|>


<commit_before>#include "TableToTreeProxyModel.h"

#include <QItemSelection>
#include <QSqlQueryModel>
#include <QDebug>
#include <QStringList>

struct TreeNode {
    TreeNode(int row=-1, int column=-1, TreeNode *parent=0)
        : row(row), column(column), parent(parent)
    {
        if (parent)
            parent->children.append(this);
    };
    int row;
    int column;
    TreeNode *parent;
    QList<TreeNode*> children;
    QString text;
};

TableToTreeProxyModel::TableToTreeProxyModel(QObject *parent)
    : QAbstractProxyModel(parent)
{
}

QModelIndex	TableToTreeProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
{
    TreeNode *node = tableNodes.at(sourceIndex.column()).at(sourceIndex.row());
    Q_ASSERT(node);
    if (!node)
        return QModelIndex();

    Q_ASSERT(false);
    return index(sourceIndex.row(), 0);
}

QModelIndex	TableToTreeProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
    if (!proxyIndex.isValid())
        return QModelIndex();

    const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
    Q_ASSERT(node);
    if (!node)
        return QModelIndex();

    return sourceModel()->index(node->row, node->column);
}

QVariant TableToTreeProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
    if (!proxyIndex.isValid())
        return QVariant();

    const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
    Q_ASSERT(node);
    if (!node)
        return QVariant();

    const QModelIndex index = sourceModel()->index(node->row, node->column);
    return sourceModel()->data(index, role);
}

QModelIndex TableToTreeProxyModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!hasIndex(row, column, parent))
        return QModelIndex();

    const TreeNode *parentNode = static_cast<TreeNode*>(parent.internalPointer());
    if (!parentNode)
        parentNode = rootNode;

    TreeNode *node = parentNode->children.at(row);
    Q_ASSERT(node);
    if (!node)
        return QModelIndex();

    return createIndex(row, column, node);
}

QModelIndex TableToTreeProxyModel::parent(const QModelIndex &child) const
{
    if (!child.isValid())
        return QModelIndex();

    const TreeNode *childNode = static_cast<TreeNode*>(child.internalPointer());
    Q_ASSERT(childNode);
    if (!childNode)
        return QModelIndex();

    TreeNode *parentNode = childNode->parent;
    Q_ASSERT(parentNode);
    if (!parentNode)
        return QModelIndex();

    return createIndex(parentNode->row, parentNode->column, parentNode);
}

int TableToTreeProxyModel::rowCount(const QModelIndex &parent) const
{
    const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
    if (!node)
        node = rootNode;

    return node->children.size();
}

int TableToTreeProxyModel::columnCount(const QModelIndex &) const
{
    return 1;
}

bool TableToTreeProxyModel::hasChildren(const QModelIndex &parent) const
{
    const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
    if (!node)
        node = rootNode;

    return node->children.size() > 0;
}

void TableToTreeProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
{
    // TODO: cleanup on already existing
    tableNodes.clear();
    rootNode = new TreeNode;

    for (int row=0; row < sourceModel->rowCount(); ++row) {
        QList<TreeNode*> rowNodes;
        TreeNode *previousNode = rootNode;
        for (int column=0; column < sourceModel->columnCount(); ++column) {
            const QString &nodeText = sourceModel->data(sourceModel->index(row, column)).toString();
            TreeNode *node = 0;
            foreach (TreeNode *siblingNode, previousNode->children) {
                Q_ASSERT(siblingNode);
                if (!siblingNode)
                    continue;
                if (siblingNode->text == nodeText) {
                    node = siblingNode;
                    break;
                }
            }

            if (!node) {
                node = new TreeNode(row, column, previousNode);
                node->text = nodeText;
            }
            rowNodes.insert(column, node);
            previousNode = node;
        }
        tableNodes.insert(row, rowNodes);
    }

    QAbstractProxyModel::setSourceModel(sourceModel);
}
<commit_msg>Remove ugly tabs.<commit_after>#include "TableToTreeProxyModel.h"

#include <QItemSelection>
#include <QSqlQueryModel>
#include <QDebug>
#include <QStringList>

struct TreeNode {
    TreeNode(int row=-1, int column=-1, TreeNode *parent=0)
        : row(row), column(column), parent(parent)
    {
        if (parent)
            parent->children.append(this);
    };
    int row;
    int column;
    TreeNode *parent;
    QList<TreeNode*> children;
    QString text;
};

TableToTreeProxyModel::TableToTreeProxyModel(QObject *parent)
    : QAbstractProxyModel(parent)
{
}

QModelIndex TableToTreeProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
{
    TreeNode *node = tableNodes.at(sourceIndex.column()).at(sourceIndex.row());
    Q_ASSERT(node);
    if (!node)
        return QModelIndex();

    Q_ASSERT(false);
    return index(sourceIndex.row(), 0);
}

QModelIndex TableToTreeProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
    if (!proxyIndex.isValid())
        return QModelIndex();

    const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
    Q_ASSERT(node);
    if (!node)
        return QModelIndex();

    return sourceModel()->index(node->row, node->column);
}

QVariant TableToTreeProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
    if (!proxyIndex.isValid())
        return QVariant();

    const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
    Q_ASSERT(node);
    if (!node)
        return QVariant();

    const QModelIndex index = sourceModel()->index(node->row, node->column);
    return sourceModel()->data(index, role);
}

QModelIndex TableToTreeProxyModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!hasIndex(row, column, parent))
        return QModelIndex();

    const TreeNode *parentNode = static_cast<TreeNode*>(parent.internalPointer());
    if (!parentNode)
        parentNode = rootNode;

    TreeNode *node = parentNode->children.at(row);
    Q_ASSERT(node);
    if (!node)
        return QModelIndex();

    return createIndex(row, column, node);
}

QModelIndex TableToTreeProxyModel::parent(const QModelIndex &child) const
{
    if (!child.isValid())
        return QModelIndex();

    const TreeNode *childNode = static_cast<TreeNode*>(child.internalPointer());
    Q_ASSERT(childNode);
    if (!childNode)
        return QModelIndex();

    TreeNode *parentNode = childNode->parent;
    Q_ASSERT(parentNode);
    if (!parentNode)
        return QModelIndex();

    return createIndex(parentNode->row, parentNode->column, parentNode);
}

int TableToTreeProxyModel::rowCount(const QModelIndex &parent) const
{
    const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
    if (!node)
        node = rootNode;

    return node->children.size();
}

int TableToTreeProxyModel::columnCount(const QModelIndex &) const
{
    return 1;
}

bool TableToTreeProxyModel::hasChildren(const QModelIndex &parent) const
{
    const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
    if (!node)
        node = rootNode;

    return node->children.size() > 0;
}

void TableToTreeProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
{
    // TODO: cleanup on already existing
    tableNodes.clear();
    rootNode = new TreeNode;

    for (int row=0; row < sourceModel->rowCount(); ++row) {
        QList<TreeNode*> rowNodes;
        TreeNode *previousNode = rootNode;
        for (int column=0; column < sourceModel->columnCount(); ++column) {
            const QString &nodeText = sourceModel->data(sourceModel->index(row, column)).toString();
            TreeNode *node = 0;
            foreach (TreeNode *siblingNode, previousNode->children) {
                Q_ASSERT(siblingNode);
                if (!siblingNode)
                    continue;
                if (siblingNode->text == nodeText) {
                    node = siblingNode;
                    break;
                }
            }

            if (!node) {
                node = new TreeNode(row, column, previousNode);
                node->text = nodeText;
            }
            rowNodes.insert(column, node);
            previousNode = node;
        }
        tableNodes.insert(row, rowNodes);
    }

    QAbstractProxyModel::setSourceModel(sourceModel);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ifstream;
	using std::ios_base;
	using std::ostrstream;
	using std::string;
#endif

// XERCES HEADERS...
//	Are included by HarnessInit.hpp

// XALAN HEADERS...
//	Are included by FileUtility.hpp

// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>

#if defined(XALAN_NO_NAMESPACES)
	typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> >	Hashtable;
#else
	typedef std::map<XalanDOMString, XalanDOMString>  Hashtable;
#endif

// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

FileUtility		h;

void
setHelp()
{
	h.args.help << endl
		 << "compare dirname [-out -gold]"
		 << endl
		 << endl
		 << "dirname		(base directory for testcases)"
		 << endl
		 << "-out dirname	(base directory for output)"
		 << endl
		 << "-gold dirname	(base directory for gold files)"
		 << endl;
}

int
main(int			argc,
	 const char*	argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	HarnessInit xmlPlatformUtils;
	XalanTransformer::initialize();

	{
		int transResult = 0;
		bool setGold = true;
		XalanDOMString fileName;

		// Set the program help string,  then get the command line parameters.
		//
		setHelp();

		if (h.getParams(argc, argv, "DOMCOM-RESULTS", setGold) == true)
		{
			//
			// Call the static initializers for xerces and xalan, and create a transformer
			//
			XalanTransformer xalan;

			XalanSourceTreeDOMSupport domSupport;
			XalanSourceTreeParserLiaison parserLiaison(domSupport);
			domSupport.setParserLiaison(&parserLiaison);

			// Generate Unique Run id and processor info
			const XalanDOMString UniqRunid = h.generateUniqRunid();
			const XalanDOMString  resultFilePrefix("cpp");
			const XalanDOMString  resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);

			XMLFileReporter	logFile(resultsFile);
			logFile.logTestFileInit("Comparison Testing:");

			// Specify the "test" directory for both input and output.
			//
			const XalanDOMString  currentDir("domcomtests");
			const XalanDOMString  theOutputDir = h.args.output + currentDir;
			h.checkAndCreateDir(theOutputDir);

			// Get the files found in the test directory
			//
			logFile.logTestCaseInit(currentDir);
			const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);

			for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
			{
				fileName = files[i];
				h.data.reset();
				h.data.testOrFile = fileName;

				const XalanDOMString  theXSLFile= h.args.base + currentDir + pathSep + fileName;
				const XalanDOMString  theXMLFile = h.generateFileName(theXSLFile,"xml");
				XalanDOMString  theGoldFile = h.args.gold + currentDir + pathSep + fileName;
				theGoldFile = h.generateFileName(theGoldFile, "out");

				const XalanDOMString  outbase =  h.args.output + currentDir + pathSep + fileName;
				const XalanDOMString  theOutputFile = h.generateFileName(outbase, "out");

				const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
				const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));
				const XSLTInputSource	goldInputSource(c_wstr(theGoldFile));

				// Use a XalanSourceTreeDocument to create the XSLTResultTarget.
				//
				XalanSourceTreeDocument* dom = parserLiaison.createXalanSourceTreeDocument();
				FormatterToSourceTree domOut(dom);
				XSLTResultTarget domResultTarget;
				domResultTarget.setDocumentHandler(&domOut);

				// Parsing(compile) the XSL stylesheet and report the results..
				//
				const XalanCompiledStylesheet*	compiledSS = 0;
				xalan.compileStylesheet(xslInputSource, compiledSS);
				if (compiledSS == 0 )
				{
					continue;
				}

				// Parsing the input XML and report the results..
				//
				const XalanParsedSource*  parsedSource = 0;
				xalan.parseSource(xmlInputSource, parsedSource);
				if (parsedSource == 0)
				{
					continue;
				}

				// Perform One transform using parsed stylesheet and unparsed xml source, report results...
				//
				xalan.transform(*parsedSource, compiledSS, domResultTarget);
				h.checkDOMResults(theOutputFile, compiledSS, dom, goldInputSource, logFile);

				parserLiaison.reset();
				xalan.destroyParsedSource(parsedSource);
				xalan.destroyStylesheet(compiledSS);
			}

		logFile.logTestCaseClose("Done", "Pass");
		h.reportPassFail(logFile, UniqRunid);
		logFile.logTestFileClose("DomCom ", "Done");
		logFile.close();

		h.analyzeResults(xalan, resultsFile);
		}
	}

	XalanTransformer::terminate();

	return 0;
}
<commit_msg>Clean of includes.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ifstream;
	using std::ios_base;
	using std::ostrstream;
	using std::string;
#endif

// XERCES HEADERS...
//	Are included by HarnessInit.hpp

// XALAN HEADERS...
#include <XalanSourceTree/FormatterToSourceTree.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>

#if defined(XALAN_NO_NAMESPACES)
	typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> >	Hashtable;
#else
	typedef std::map<XalanDOMString, XalanDOMString>  Hashtable;
#endif

// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

void
setHelp(FileUtility&	h)
{
	h.args.getHelpStream() << endl
		 << "compare dirname [-out -gold]"
		 << endl
		 << endl
		 << "dirname		(base directory for testcases)"
		 << endl
		 << "-out dirname	(base directory for output)"
		 << endl
		 << "-gold dirname	(base directory for gold files)"
		 << endl;
}

int
main(int			argc,
	 const char*	argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	HarnessInit xmlPlatformUtils;

	{
		FileUtility		h;

		int transResult = 0;
		bool setGold = true;
		XalanDOMString fileName;

		// Set the program help string,  then get the command line parameters.
		//
		setHelp(h);

		if (h.getParams(argc, argv, "DOMCOM-RESULTS", setGold) == true)
		{
			XalanTransformer::initialize();

			{
				//
				// Call the static initializers for xerces and xalan, and create a transformer
				//
				XalanTransformer xalan;

				XalanSourceTreeDOMSupport domSupport;
				XalanSourceTreeParserLiaison parserLiaison(domSupport);
				domSupport.setParserLiaison(&parserLiaison);

				// Generate Unique Run id and processor info
				const XalanDOMString UniqRunid = h.generateUniqRunid();
				const XalanDOMString  resultFilePrefix("cpp");
				const XalanDOMString  resultsFile(h.args.output + resultFilePrefix + UniqRunid + FileUtility::s_xmlSuffix);

				XMLFileReporter	logFile(resultsFile);
				logFile.logTestFileInit("Comparison Testing:");

				// Specify the "test" directory for both input and output.
				//
				const XalanDOMString  currentDir("domcomtests");
				const XalanDOMString  theOutputDir = h.args.output + currentDir;
				h.checkAndCreateDir(theOutputDir);

				// Get the files found in the test directory
				//
				logFile.logTestCaseInit(currentDir);
				const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);

				for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
				{
					fileName = files[i];
					h.data.reset();
					h.data.testOrFile = fileName;

					const XalanDOMString  theXSLFile= h.args.base + currentDir + FileUtility::s_pathSep + fileName;
					const XalanDOMString  theXMLFile = h.generateFileName(theXSLFile,"xml");
					XalanDOMString  theGoldFile = h.args.gold + currentDir + FileUtility::s_pathSep + fileName;
					theGoldFile = h.generateFileName(theGoldFile, "out");

					const XalanDOMString  outbase =  h.args.output + currentDir + FileUtility::s_pathSep + fileName;
					const XalanDOMString  theOutputFile = h.generateFileName(outbase, "out");

					const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
					const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));
					const XSLTInputSource	goldInputSource(c_wstr(theGoldFile));

					// Use a XalanSourceTreeDocument to create the XSLTResultTarget.
					//
					XalanSourceTreeDocument* dom = parserLiaison.createXalanSourceTreeDocument();
					FormatterToSourceTree domOut(dom);
					XSLTResultTarget domResultTarget;
					domResultTarget.setDocumentHandler(&domOut);

					// Parsing(compile) the XSL stylesheet and report the results..
					//
					const XalanCompiledStylesheet*	compiledSS = 0;
					xalan.compileStylesheet(xslInputSource, compiledSS);
					if (compiledSS == 0 )
					{
						continue;
					}

					// Parsing the input XML and report the results..
					//
					const XalanParsedSource*  parsedSource = 0;
					xalan.parseSource(xmlInputSource, parsedSource);
					if (parsedSource == 0)
					{
						continue;
					}

					// Perform One transform using parsed stylesheet and unparsed xml source, report results...
					//
					xalan.transform(*parsedSource, compiledSS, domResultTarget);
					h.checkDOMResults(theOutputFile, compiledSS, dom, goldInputSource, logFile);

					parserLiaison.reset();
					xalan.destroyParsedSource(parsedSource);
					xalan.destroyStylesheet(compiledSS);
				}

				logFile.logTestCaseClose("Done", "Pass");
				h.reportPassFail(logFile, UniqRunid);
				logFile.logTestFileClose("DomCom ", "Done");
				logFile.close();

				h.analyzeResults(xalan, resultsFile);
			}

			XalanTransformer::terminate();
		}
	}

	return 0;
}
<|endoftext|>