<commit_before>/*
For more information, please see: http://software.sci.utah.edu

The MIT License

Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.

License for the specific language governing rights and limitations under
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.
*/

#include <Testing/Utils/SCIRunUnitTests.h>

#include <fstream>
#include <boost/filesystem.hpp>
#include <Core/Algorithms/Math/LinearSystem/SolveLinearSystemAlgo.h>
#include <Core/Algorithms/DataIO/ReadMatrix.h>
#include <Core/Algorithms/DataIO/WriteMatrix.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Testing/Utils/MatrixTestUtilities.h>

using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::DataIO;
using namespace SCIRun::TestUtils;
using namespace SCIRun;
using namespace ::testing;
//
//void CanSolveDarrellWithMethod(const std::string& method, double solutionError)
//{
//	auto Afile = TestResources::rootDir() / "CGDarrell" / "A.mat";
//	auto rhsFile = TestResources::rootDir() / "CGDarrell" / "RHS.mat";
//	if (!boost::filesystem::exists(Afile) || !boost::filesystem::exists(rhsFile))
//	{
//		FAIL() << "TODO: Issue #142 will standardize these file locations other than being on Dan's hard drive." << std::endl
//			<< "Once that issue is done however, this will be a user setup error." << std::endl;
//		return;
//	}
//
//	ReadMatrixAlgorithm reader;
//	SparseRowMatrixHandle A;
//	{
//		ScopedTimer t("reading sparse matrix");
//		A = matrix_cast::as_sparse(reader.run(Afile.string()));
//	}
//	ASSERT_TRUE(A.get() != nullptr);
//	EXPECT_EQ(428931, A->nrows());
//	EXPECT_EQ(428931, A->ncols());
//
//	DenseMatrixHandle rhs;
//	{
//		ScopedTimer t("reading rhs");
//		rhs = matrix_cast::as_dense(reader.run(rhsFile.string()));
//	}
//	ASSERT_TRUE(rhs.get() != nullptr);
//	EXPECT_EQ(428931, rhs->nrows());
//	EXPECT_EQ(1, rhs->ncols());
//
//	DenseColumnMatrixHandle x0;
//	ASSERT_FALSE(x0); // algo object will initialize x0 to the zero vector
//
//	SolveLinearSystemAlgo algo;
//	algo.set(Variables::MaxIterations, 500);
//	algo.set(Variables::TargetError, 7e-4);
//	algo.set_option(Variables::Method, method);
//	algo.setUpdaterFunc([](double x) {});
//
//	DenseColumnMatrixHandle solution;
//	{
//		ScopedTimer t("Running solver");
//		ASSERT_TRUE(algo.run(A, matrix_convert::to_column(rhs), x0, solution));
//	}
//	ASSERT_TRUE(solution.get() != nullptr);
//	EXPECT_EQ(428931, solution->nrows());
//	EXPECT_EQ(1, solution->ncols());
//
//	auto solutionFile = TestResources::rootDir() / "CGDarrell" / ("dan_sol_" + method + ".mat");
//	auto scirun4solution = reader.run(solutionFile.string());
//	ASSERT_TRUE(scirun4solution.get() != nullptr);
//	DenseColumnMatrixHandle expected = matrix_convert::to_column(scirun4solution);
//
//	EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*expected, *solution, solutionError);
//
//	WriteMatrixAlgorithm writer;
//	auto portedSolutionFile = TestResources::rootDir() / "CGDarrell" / ("portedSolution_" + method + ".txt");
//	writer.run(solution, portedSolutionFile.string());
//
//	auto diff = *expected - *solution;
//	auto maxDiff = diff.maxCoeff();
//	std::cout << "max diff is: " << maxDiff << std::endl;
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_CG)
//{
//	double solutionError;
//	//TODO: investigate this significant difference
//#ifdef WIN32
//	solutionError = 0.15;
//#else
//	solutionError = 0.23;
//#endif
//	CanSolveDarrellWithMethod("cg", solutionError);
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_BICG)
//{
//	double solutionError = 0.001;
//	CanSolveDarrellWithMethod("bicg", solutionError);
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_Jacobi)
//{
//	//TODO: doesn't converge for this system. Problem?
//	double solutionError = 105;
//	CanSolveDarrellWithMethod("jacobi", solutionError);
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_MINRES)
//{
//	//TODO: converges but not as accurate.
//	double solutionError = 2.4;
//	CanSolveDarrellWithMethod("minres", solutionError);
//}

#if GTEST_HAS_COMBINE

using ::testing::Values;
using ::testing::Combine;
using ::testing::Range;

class SolveLinearSystemTestsAlgoParameterized : public ::testing::TestWithParam < ::std::tr1::tuple<const char*, int> >
{
public:
	~SolveLinearSystemTestsAlgoParameterized() {}
protected:
	virtual void SetUp()
	{
		auto Afile = TestResources::rootDir() / "CGDarrell" / "A.mat";
		auto rhsFile = TestResources::rootDir() / "CGDarrell" / "RHS.mat";
		if (!boost::filesystem::exists(Afile) || !boost::filesystem::exists(rhsFile))
		{
			FAIL() << "TODO: Issue #142 will standardize these file locations other than being on Dan's hard drive." << std::endl
				<< "Once that issue is done however, this will be a user setup error." << std::endl;
			return;
		}

		ReadMatrixAlgorithm reader;
		SparseRowMatrixHandle A;
		{
			ScopedTimer t("reading sparse matrix");
			A = matrix_cast::as_sparse(reader.run(Afile.string()));
		}
		ASSERT_TRUE(A.get() != nullptr);
		EXPECT_EQ(428931, A->nrows());
		EXPECT_EQ(428931, A->ncols());

		DenseMatrixHandle rhs;
		{
			ScopedTimer t("reading rhs");
			rhs = matrix_cast::as_dense(reader.run(rhsFile.string()));
		}
		ASSERT_TRUE(rhs.get() != nullptr);
		EXPECT_EQ(428931, rhs->nrows());
		EXPECT_EQ(1, rhs->ncols());

		DenseColumnMatrixHandle x0;
		ASSERT_FALSE(x0); // algo object will initialize x0 to the zero vector

		SolveLinearSystemAlgo algo;
		algo.set(Variables::MaxIterations, 500);
		algo.set(Variables::TargetError, 7e-4);
		algo.set_option(Variables::Method, ::std::tr1::get<0>(GetParam()));
		algo.setUpdaterFunc([](double x) {});

		DenseColumnMatrixHandle solution;
		{
			ScopedTimer t("Running solver");
			ASSERT_TRUE(algo.run(A, matrix_convert::to_column(rhs), x0, solution));
		}
		ASSERT_TRUE(solution.get() != nullptr);
		EXPECT_EQ(428931, solution->nrows());
		EXPECT_EQ(1, solution->ncols());

        const std::string& c = ::std::tr1::get<0>(GetParam());
		auto solutionFile = TestResources::rootDir() / "CGDarrell" / ("dan_sol_" + c + ".mat");

		auto scirun4solution = reader.run(solutionFile.string());
		ASSERT_TRUE(scirun4solution.get() != nullptr);
		DenseColumnMatrixHandle expected = matrix_convert::to_column(scirun4solution);

		EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*expected, *solution, ::std::tr1::get<1>(GetParam()));

		WriteMatrixAlgorithm writer;
		auto portedSolutionFile = TestResources::rootDir() / "CGDarrell" / ("portedSolution_" +  c + ".txt");
		writer.run(solution, portedSolutionFile.string());

		auto diff = *expected - *solution;
		auto maxDiff = diff.maxCoeff();
		std::cout << "max diff is: " << maxDiff << std::endl;
	}
	virtual void TearDown(){}
};

TEST_P(SolveLinearSystemTestsAlgoParameterized, CanSolveDarrellParameterized)
{
	EXPECT_NO_FATAL_FAILURE(SolveLinearSystemTestsAlgoParameterized);
}

INSTANTIATE_TEST_CASE_P(
	CanSolveDarrellParameterized,
	SolveLinearSystemTestsAlgoParameterized,
	Combine(Values(
		"cg",
		"bigcg",
		"jacobi",
		"minres"
		),
	//Range(1, 10, 0.1))
	Values(0.15, 0.23, 0.001, 105, 2.4))
	);
#else
TEST(DummyTest, CombineIsNotSupportedOnThisPlatform(){}
#endif
<commit_msg>updated for Moritz_A/b<commit_after>/*
For more information, please see: http://software.sci.utah.edu

The MIT License

Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.

License for the specific language governing rights and limitations under
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.
*/

#include <Testing/Utils/SCIRunUnitTests.h>

#include <fstream>
#include <boost/filesystem.hpp>
#include <Core/Algorithms/Math/LinearSystem/SolveLinearSystemAlgo.h>
#include <Core/Algorithms/DataIO/ReadMatrix.h>
#include <Core/Algorithms/DataIO/WriteMatrix.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Testing/Utils/MatrixTestUtilities.h>

using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::DataIO;
using namespace SCIRun::TestUtils;
using namespace SCIRun;
using namespace ::testing;
//
//void CanSolveDarrellWithMethod(const std::string& method, double solutionError)
//{
//	auto Afile = TestResources::rootDir() / "CGDarrell" / "A.mat";
//	auto rhsFile = TestResources::rootDir() / "CGDarrell" / "RHS.mat";
//	if (!boost::filesystem::exists(Afile) || !boost::filesystem::exists(rhsFile))
//	{
//		FAIL() << "TODO: Issue #142 will standardize these file locations other than being on Dan's hard drive." << std::endl
//			<< "Once that issue is done however, this will be a user setup error." << std::endl;
//		return;
//	}
//
//	ReadMatrixAlgorithm reader;
//	SparseRowMatrixHandle A;
//	{
//		ScopedTimer t("reading sparse matrix");
//		A = matrix_cast::as_sparse(reader.run(Afile.string()));
//	}
//	ASSERT_TRUE(A.get() != nullptr);
//	EXPECT_EQ(428931, A->nrows());
//	EXPECT_EQ(428931, A->ncols());
//
//	DenseMatrixHandle rhs;
//	{
//		ScopedTimer t("reading rhs");
//		rhs = matrix_cast::as_dense(reader.run(rhsFile.string()));
//	}
//	ASSERT_TRUE(rhs.get() != nullptr);
//	EXPECT_EQ(428931, rhs->nrows());
//	EXPECT_EQ(1, rhs->ncols());
//
//	DenseColumnMatrixHandle x0;
//	ASSERT_FALSE(x0); // algo object will initialize x0 to the zero vector
//
//	SolveLinearSystemAlgo algo;
//	algo.set(Variables::MaxIterations, 500);
//	algo.set(Variables::TargetError, 7e-4);
//	algo.set_option(Variables::Method, method);
//	algo.setUpdaterFunc([](double x) {});
//
//	DenseColumnMatrixHandle solution;
//	{
//		ScopedTimer t("Running solver");
//		ASSERT_TRUE(algo.run(A, matrix_convert::to_column(rhs), x0, solution));
//	}
//	ASSERT_TRUE(solution.get() != nullptr);
//	EXPECT_EQ(428931, solution->nrows());
//	EXPECT_EQ(1, solution->ncols());
//
//	auto solutionFile = TestResources::rootDir() / "CGDarrell" / ("dan_sol_" + method + ".mat");
//	auto scirun4solution = reader.run(solutionFile.string());
//	ASSERT_TRUE(scirun4solution.get() != nullptr);
//	DenseColumnMatrixHandle expected = matrix_convert::to_column(scirun4solution);
//
//	EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*expected, *solution, solutionError);
//
//	WriteMatrixAlgorithm writer;
//	auto portedSolutionFile = TestResources::rootDir() / "CGDarrell" / ("portedSolution_" + method + ".txt");
//	writer.run(solution, portedSolutionFile.string());
//
//	auto diff = *expected - *solution;
//	auto maxDiff = diff.maxCoeff();
//	std::cout << "max diff is: " << maxDiff << std::endl;
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_CG)
//{
//	double solutionError;
//	//TODO: investigate this significant difference
//#ifdef WIN32
//	solutionError = 0.15;
//#else
//	solutionError = 0.23;
//#endif
//	CanSolveDarrellWithMethod("cg", solutionError);
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_BICG)
//{
//	double solutionError = 0.001;
//	CanSolveDarrellWithMethod("bicg", solutionError);
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_Jacobi)
//{
//	//TODO: doesn't converge for this system. Problem?
//	double solutionError = 105;
//	CanSolveDarrellWithMethod("jacobi", solutionError);
//}
//
//TEST(SolveLinearSystemTests, CanSolveDarrellWithMethod_MINRES)
//{
//	//TODO: converges but not as accurate.
//	double solutionError = 2.4;
//	CanSolveDarrellWithMethod("minres", solutionError);
//}

#if GTEST_HAS_COMBINE

using ::testing::Values;
using ::testing::Combine;
using ::testing::Range;

class SolveLinearSystemTestsAlgoParameterized : public ::testing::TestWithParam < ::std::tr1::tuple<const char*, int> >
{
public:
	~SolveLinearSystemTestsAlgoParameterized() {}
protected:
	virtual void SetUp()
	{
		auto Afile = TestResources::rootDir() / "CGDarrell" / "A.mat";
		auto rhsFile = TestResources::rootDir() / "CGDarrell" / "RHS.mat";
		if (!boost::filesystem::exists(Afile) || !boost::filesystem::exists(rhsFile))
		{
			FAIL() << "TODO: Issue #142 will standardize these file locations other than being on Dan's hard drive." << std::endl
				<< "Once that issue is done however, this will be a user setup error." << std::endl;
			return;
		}

		ReadMatrixAlgorithm reader;
		SparseRowMatrixHandle A;
		{
			ScopedTimer t("reading sparse matrix");
			A = matrix_cast::as_sparse(reader.run(Afile.string()));
		}
		ASSERT_TRUE(A.get() != nullptr);
		EXPECT_EQ(428931, A->nrows());
		EXPECT_EQ(428931, A->ncols());

		DenseMatrixHandle rhs;
		{
			ScopedTimer t("reading rhs");
			rhs = matrix_cast::as_dense(reader.run(rhsFile.string()));
		}
		ASSERT_TRUE(rhs.get() != nullptr);
		EXPECT_EQ(428931, rhs->nrows());
		EXPECT_EQ(1, rhs->ncols());

		DenseColumnMatrixHandle x0;
		ASSERT_FALSE(x0); // algo object will initialize x0 to the zero vector

		SolveLinearSystemAlgo algo;
		algo.set(Variables::MaxIterations, 500);
		algo.set(Variables::TargetError, 7e-4);
		algo.set_option(Variables::Method, ::std::tr1::get<0>(GetParam()));
		algo.setUpdaterFunc([](double x) {});

		DenseColumnMatrixHandle solution;
		{
			ScopedTimer t("Running solver");
			ASSERT_TRUE(algo.run(A, matrix_convert::to_column(rhs), x0, solution));
		}
		ASSERT_TRUE(solution.get() != nullptr);
		EXPECT_EQ(428931, solution->nrows());
		EXPECT_EQ(1, solution->ncols());

        const std::string& c = ::std::tr1::get<0>(GetParam());
		auto solutionFile = TestResources::rootDir() / "CGDarrell" / ("dan_sol_" + c + ".mat");

		auto scirun4solution = reader.run(solutionFile.string());
		ASSERT_TRUE(scirun4solution.get() != nullptr);
		DenseColumnMatrixHandle expected = matrix_convert::to_column(scirun4solution);

		EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*expected, *solution, ::std::tr1::get<1>(GetParam()));

		WriteMatrixAlgorithm writer;
		auto portedSolutionFile = TestResources::rootDir() / "CGDarrell" / ("portedSolution_" +  c + ".txt");
		writer.run(solution, portedSolutionFile.string());

		auto diff = *expected - *solution;
		auto maxDiff = diff.maxCoeff();
		std::cout << "max diff is: " << maxDiff << std::endl;
	}
	virtual void TearDown(){}
};

TEST_P(SolveLinearSystemTestsAlgoParameterized, CanSolveDarrellParameterized)
{
	EXPECT_NO_FATAL_FAILURE(SolveLinearSystemTestsAlgoParameterized);
}

INSTANTIATE_TEST_CASE_P(
	CanSolveDarrellParameterized,
	SolveLinearSystemTestsAlgoParameterized,
	Combine(Values(
		"cg",
		"bigcg",
		"jacobi",
		"minres"
		),
	//Range(1, 10, 0.1))
	Values(0.15, 0.23, 0.001, 105, 2.4))
	);
#else
TEST(DummyTest, CombineIsNotSupportedOnThisPlatform(){}
#endif
<|endoftext|>


<commit_before>#include "SymbolFile.h"
#include "SymbolType.h"
#include "FileHelper.h"

#include <sprite2/SymType.h>
#include <gum/SymbolFile.h>

#include <json/json.h>

#include <fstream>

namespace ee
{

SINGLETON_DEFINITION(SymbolFile);

static const char* TAG_GEN = "gen";

SymbolFile::SymbolFile()
{
	Regist(SYM_ANIS,		"anis");
	Regist(SYM_FONTBLANK,	"fontblank");
	Regist(SYM_FREETYPE,	"freetype");
	Regist(SYM_SCRIPTS,		"scripts");
	Regist(SYM_P3DINV,		"p3dinv");
	Regist(SYM_EJOY2D,		"ejoy2d");
	Regist(SYM_TERRAIN2D,	"terrain2d");
	Regist(SYM_SHADOW,		"shadow");
	Regist(SYM_UI,			"ui");
	Regist(SYM_PSD,			"psd");
	Regist(SYM_UIWND,		"uiwnd");

	Regist(s2::SYM_SCALE9,		"scale9");
	Regist(s2::SYM_ICON,		"icon");
	Regist(s2::SYM_TEXTURE,		"texture");
	Regist(s2::SYM_TEXTBOX,		"text");
	Regist(s2::SYM_COMPLEX,		"complex");
	Regist(s2::SYM_ANIMATION,	"anim");
	Regist(s2::SYM_PARTICLE3D,	"particle");
	Regist(s2::SYM_PARTICLE2D,	"particle2d");
	Regist(s2::SYM_SHAPE,		"shape");
	Regist(s2::SYM_MESH,		"mesh");
	Regist(s2::SYM_MASK,		"mask");
	Regist(s2::SYM_TRAIL,		"trail");
	Regist(s2::SYM_SKELETON,	"skeleton");
}

int SymbolFile::Type(const std::string& filepath) const
{
	int type = gum::SymbolFile::Instance()->Type(filepath);
	if (type != s2::SYM_UNKNOWN && type != s2::SYM_INVALID) {
		return type;
	}

	int pos = filepath.rfind('.');
	std::string ext = filepath.substr(pos + 1);
	if (ext == "json")
	{
		const std::string filename = filepath.substr(0, filepath.find_last_of('.'));
		int pos = filename.find_last_of('_');
		if (pos == -1) {
			return s2::SYM_UNKNOWN;
		}

		std::string tag = filename.substr(pos + 1);
		pos = tag.find(TAG_GEN);
		if (pos != std::string::npos) {
			tag = tag.substr(0, pos - 1);
		}

		std::map<std::string, int>::const_iterator itr = m_tag2type.find(tag);
		if (itr != m_tag2type.end()) {
			return itr->second;
		}

		Json::Value val;
		Json::Reader reader;
		std::locale::global(std::locale(""));
		std::ifstream fin(filepath.c_str());
		std::locale::global(std::locale("C"));
		reader.parse(fin, val);
		fin.close();

		if (val.isMember("skeleton") && !val["skeleton"].isArray() && val["skeleton"].isMember("spine")) {
			return s2::SYM_ANIM2;
		}

		return s2::SYM_UNKNOWN;
	}
	else if (ext == "lua")
	{
		const std::string name = filepath.substr(0, filepath.find_last_of('.'));
		if (name.find('_') == -1) {
			return s2::SYM_UNKNOWN;
		}
		const std::string json_ext = name.substr(name.find_last_of('_') + 1);
		if (json_ext == "scripts") {
			return SYM_SCRIPTS;
		} else {
			return s2::SYM_UNKNOWN;
		}
	}
	else if (ext == "ttf")
	{
		return SYM_FREETYPE;
	}
	else
	{
		std::string filename = FileHelper::GetFilename(filepath);
		if (filename == SYM_GROUP_TAG) {
			return s2::SYM_COMPLEX;
		}
	}

	return s2::SYM_UNKNOWN;
}

const std::string& SymbolFile::Tag(int type) const
{
	const std::string& tag = gum::SymbolFile::Instance()->Tag(type);
	if (tag != gum::SymbolFile::UNKNOWN_TAG) {
		return tag;
	}

	std::map<int, std::string>::const_iterator itr = m_type2tag.find(type);
	if (itr != m_type2tag.end()) {
		return itr->second;
	} else {
		return gum::SymbolFile::UNKNOWN_TAG;
	}
}

void SymbolFile::Regist(int type, const std::string& tag)
{
	m_type2tag.insert(std::make_pair(type, tag));
	m_tag2type.insert(std::make_pair(tag, type));
}

}<commit_msg>[FIXED] get sym type from file<commit_after>#include "SymbolFile.h"
#include "SymbolType.h"
#include "FileHelper.h"

#include <sprite2/SymType.h>
#include <gum/SymbolFile.h>

#include <json/json.h>

#include <fstream>

namespace ee
{

SINGLETON_DEFINITION(SymbolFile);

static const char* TAG_GEN = "gen";

SymbolFile::SymbolFile()
{
	Regist(SYM_ANIS,		"anis");
	Regist(SYM_FONTBLANK,	"fontblank");
	Regist(SYM_FREETYPE,	"freetype");
	Regist(SYM_SCRIPTS,		"scripts");
	Regist(SYM_P3DINV,		"p3dinv");
	Regist(SYM_EJOY2D,		"ejoy2d");
	Regist(SYM_TERRAIN2D,	"terrain2d");
	Regist(SYM_SHADOW,		"shadow");
	Regist(SYM_UI,			"ui");
	Regist(SYM_PSD,			"psd");
	Regist(SYM_UIWND,		"uiwnd");

	Regist(s2::SYM_SCALE9,		"scale9");
	Regist(s2::SYM_ICON,		"icon");
	Regist(s2::SYM_TEXTURE,		"texture");
	Regist(s2::SYM_TEXTBOX,		"text");
	Regist(s2::SYM_COMPLEX,		"complex");
	Regist(s2::SYM_ANIMATION,	"anim");
	Regist(s2::SYM_PARTICLE3D,	"particle");
	Regist(s2::SYM_PARTICLE2D,	"particle2d");
	Regist(s2::SYM_SHAPE,		"shape");
	Regist(s2::SYM_MESH,		"mesh");
	Regist(s2::SYM_MASK,		"mask");
	Regist(s2::SYM_TRAIL,		"trail");
	Regist(s2::SYM_SKELETON,	"skeleton");
}

int SymbolFile::Type(const std::string& filepath) const
{
	int type = gum::SymbolFile::Instance()->Type(filepath);
	if (type != s2::SYM_UNKNOWN && type != s2::SYM_INVALID) {
		return type;
	}

	int pos = filepath.rfind('.');
	std::string ext = filepath.substr(pos + 1);
	if (ext == "json")
	{
		const std::string filename = filepath.substr(0, filepath.find_last_of('.'));
		int pos = filename.find_last_of('_');
		if (pos == -1) {
			return s2::SYM_UNKNOWN;
		}

		std::string tag = filename.substr(pos + 1);
		pos = tag.find(TAG_GEN);
		if (pos != std::string::npos) {
			tag = tag.substr(0, pos - 1);
		}

		std::map<std::string, int>::const_iterator itr = m_tag2type.find(tag);
		if (itr != m_tag2type.end()) {
			return itr->second;
		}

		Json::Value val;
		Json::Reader reader;
		std::locale::global(std::locale(""));
		std::ifstream fin(filepath.c_str());
		std::locale::global(std::locale("C"));
		reader.parse(fin, val);
		fin.close();

		if (!val.isArray() && val.isMember("skeleton") && !val["skeleton"].isArray() && val["skeleton"].isMember("spine")) {
			return s2::SYM_ANIM2;
		}

		return s2::SYM_UNKNOWN;
	}
	else if (ext == "lua")
	{
		const std::string name = filepath.substr(0, filepath.find_last_of('.'));
		if (name.find('_') == -1) {
			return s2::SYM_UNKNOWN;
		}
		const std::string json_ext = name.substr(name.find_last_of('_') + 1);
		if (json_ext == "scripts") {
			return SYM_SCRIPTS;
		} else {
			return s2::SYM_UNKNOWN;
		}
	}
	else if (ext == "ttf")
	{
		return SYM_FREETYPE;
	}
	else
	{
		std::string filename = FileHelper::GetFilename(filepath);
		if (filename == SYM_GROUP_TAG) {
			return s2::SYM_COMPLEX;
		}
	}

	return s2::SYM_UNKNOWN;
}

const std::string& SymbolFile::Tag(int type) const
{
	const std::string& tag = gum::SymbolFile::Instance()->Tag(type);
	if (tag != gum::SymbolFile::UNKNOWN_TAG) {
		return tag;
	}

	std::map<int, std::string>::const_iterator itr = m_type2tag.find(type);
	if (itr != m_type2tag.end()) {
		return itr->second;
	} else {
		return gum::SymbolFile::UNKNOWN_TAG;
	}
}

void SymbolFile::Regist(int type, const std::string& tag)
{
	m_type2tag.insert(std::make_pair(type, tag));
	m_tag2type.insert(std::make_pair(tag, type));
}

}<|endoftext|>


<commit_before>#include <iostream>

#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"

#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"

#include "protocol/hello.pb.h" /// hello protocol

#include "boost/lexical_cast.hpp"

using namespace vtrc;

namespace {

class  hello_service_impl: public howto::hello_service {

    void send_hello(::google::protobuf::RpcController*  controller,
                    const ::howto::request_message*     request,
                    ::howto::response_message*          response,
                    ::google::protobuf::Closure*        done) /*override*/
    {
        std::ostringstream oss;

        oss << "Hello " << request->name( )
            << " from hello_service_impl::send_hello!";

        response->set_hello( oss.str( ) );
        done->Run( );
    }
};

class hello_application: public server::application {

    typedef vtrc::shared_ptr<common::rpc_service_wrapper> wrapper_sptr;

public:
    hello_application( vtrc::common::pool_pair &pp )
        :vtrc::server::application(pp)
    { }

    wrapper_sptr get_service_by_name( common::connection_iface* connection,
                                      const std::string &service_name )
    {
        if( service_name == hello_service_impl::descriptor( )->full_name( ) ) {

             hello_service_impl *new_impl = new  hello_service_impl;

             return vtrc::make_shared<common::rpc_service_wrapper>( new_impl );

        }
        return wrapper_sptr( );
    }

};

}

int main( int argc, const char **argv )
{
    common::pool_pair pp( 1, 1 );

    hello_application app( pp );

    unsigned short port = 56560;

    if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>(argv[1]);
    }

    vtrc::shared_ptr<server::listener>
            tcp( server::listeners::tcp::create( app, "0.0.0.0", port ) );

    tcp->start( );

    pp.join_all( );

    return 0;
}

<commit_msg>proto<commit_after>#include <iostream>

#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"

#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"

#include "protocol/hello.pb.h" /// hello protocol

#include "boost/lexical_cast.hpp"

using namespace vtrc;

namespace {

class  hello_service_impl: public howto::hello_service {

    void send_hello(::google::protobuf::RpcController*  controller,
                    const ::howto::request_message*     request,
                    ::howto::response_message*          response,
                    ::google::protobuf::Closure*        done) /*override*/
    {
        std::ostringstream oss;

        oss << "Hello " << request->name( )
            << " from hello_service_impl::send_hello!";

        response->set_hello( oss.str( ) );
        done->Run( );
    }

public:
    static std::string const &service_name(  )
    {
        return howto::hello_service::descriptor( )->full_name( );
    }

};

class hello_application: public server::application {

    typedef vtrc::shared_ptr<common::rpc_service_wrapper> wrapper_sptr;

public:

    hello_application( vtrc::common::pool_pair &pp )
        :vtrc::server::application(pp)
    { }

    wrapper_sptr get_service_by_name( common::connection_iface* connection,
                                      const std::string &service_name )
    {
        if( service_name == hello_service_impl::service_name( ) ) {

             hello_service_impl *new_impl = new  hello_service_impl;

             return vtrc::make_shared<common::rpc_service_wrapper>( new_impl );

        }
        return wrapper_sptr( );
    }

};

}

int main( int argc, const char **argv )
{
    common::pool_pair pp( 1, 1 );

    hello_application app( pp );

    unsigned short port = 56560;

    if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>(argv[1]);
    }

    vtrc::shared_ptr<server::listener>
            tcp( server::listeners::tcp::create( app, "0.0.0.0", port ) );

    tcp->start( );

    pp.join_all( );

    return 0;
}

<|endoftext|>


<commit_before>/*If you are using uWebSockets,
  remember to change this to uwebsockets_websocket.h*/
#include "sleepy_discord/websocketpp_websocket.h"

class myClientClass : public SleepyDiscord::DiscordClient {
public:
	using SleepyDiscord::DiscordClient::DiscordClient;
	void onMessage(SleepyDiscord::Message message) {
		if (message.startsWith("whcg hello"))
			sendMessage(message.channelID, "Hello " + message.author.username);
	}
};

int main() {
	myClientClass client("token", 2);
	client.run();
}
<commit_msg>Hello example: change class name myClientClass to MyClientClass<commit_after>/*If you are using uWebSockets,
  remember to change this to uwebsockets_websocket.h*/
#include "sleepy_discord/websocketpp_websocket.h"

class MyClientClass : public SleepyDiscord::DiscordClient {
public:
	using SleepyDiscord::DiscordClient::DiscordClient;
	void onMessage(SleepyDiscord::Message message) {
		if (message.startsWith("whcg hello"))
			sendMessage(message.channelID, "Hello " + message.author.username);
	}
};

int main() {
	MyClientClass client("token", 2);
	client.run();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: testloader.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-23 16:17:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _OSL_MODULE_H_
#include <osl/module.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#include <com/sun/star/loader/XImplementationLoader.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XSingleComponentFactory.hpp>

#include <cppuhelper/implbase1.hxx>
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

#if defined ( UNX ) || defined ( MAC )
#include <limits.h>
#define _MAX_PATH PATH_MAX
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::loader;
using namespace com::sun::star::lang;
using namespace osl;
using namespace rtl;
using namespace cppu;

#if OSL_DEBUG_LEVEL > 0
#define TEST_ENSHURE(c, m)   OSL_ENSURE(c, m)
#else
#define TEST_ENSHURE(c, m)   OSL_VERIFY(c)
#endif

class EmptyComponentContext : public WeakImplHelper1< XComponentContext >
{
public:
    virtual Any SAL_CALL getValueByName( const OUString& Name )
        throw (RuntimeException)
        {
            return Any();
        }
    virtual Reference< XMultiComponentFactory > SAL_CALL getServiceManager(  )
        throw (RuntimeException)
        {
            return Reference< XMultiComponentFactory > ();
        }

};

#if (defined UNX) || (defined OS2)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
    Reference<XInterface> xIFace;

    Module module;

    OUString dllName(
        RTL_CONSTASCII_USTRINGPARAM("shlibloader.uno" SAL_DLLEXTENSION) );

    if (module.load(dllName))
    {
        // try to get provider from module
        component_getFactoryFunc pCompFactoryFunc = (component_getFactoryFunc)
            module.getSymbol( OUString::createFromAscii(COMPONENT_GETFACTORY) );

        if (pCompFactoryFunc)
        {
            XSingleServiceFactory * pRet = (XSingleServiceFactory *)(*pCompFactoryFunc)(
                "com.sun.star.comp.stoc.DLLComponentLoader", 0, 0 );
            if (pRet)
            {
                xIFace = pRet;
                pRet->release();
            }
        }
    }

    TEST_ENSHURE( xIFace.is(), "testloader error1");

    Reference<XSingleComponentFactory> xFactory( Reference<XSingleComponentFactory>::query(xIFace) );

    TEST_ENSHURE( xFactory.is(), "testloader error2");

    Reference<XInterface> xLoader = xFactory->createInstanceWithContext( new EmptyComponentContext );

    TEST_ENSHURE( xLoader.is(), "testloader error3");

    Reference<XServiceInfo> xServInfo( Reference<XServiceInfo>::query(xLoader) );

    TEST_ENSHURE( xServInfo.is(), "testloader error4");

    TEST_ENSHURE( xServInfo->getImplementationName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.comp.stoc.DLLComponentLoader") ), "testloader error5");
    TEST_ENSHURE( xServInfo->supportsService(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")) ), "testloader error6");
    TEST_ENSHURE( xServInfo->getSupportedServiceNames().getLength() == 1, "testloader error7");

    xIFace.clear();
    xFactory.clear();
    xLoader.clear();
    xServInfo.clear();

    printf("Test Dll ComponentLoader, OK!\n");

    return(0);
}

<commit_msg>INTEGRATION: CWS cd02 (1.9.120); FILE MERGED 2004/11/15 17:29:01 dbo 1.9.120.1: #i24030# general cleanup to make buildable again<commit_after>/*************************************************************************
 *
 *  $RCSfile: testloader.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-13 19:00:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#include <sal/main.h>
#ifndef _OSL_MODULE_H_
#include <osl/module.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#include <com/sun/star/loader/XImplementationLoader.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XSingleComponentFactory.hpp>

#include <cppuhelper/implbase1.hxx>
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

#if defined ( UNX ) || defined ( MAC )
#include <limits.h>
#define _MAX_PATH PATH_MAX
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::loader;
using namespace com::sun::star::lang;
using namespace osl;
using namespace rtl;
using namespace cppu;

#if OSL_DEBUG_LEVEL > 0
#define TEST_ENSHURE(c, m)   OSL_ENSURE(c, m)
#else
#define TEST_ENSHURE(c, m)   OSL_VERIFY(c)
#endif

class EmptyComponentContext : public WeakImplHelper1< XComponentContext >
{
public:
    virtual Any SAL_CALL getValueByName( const OUString& Name )
        throw (RuntimeException)
        {
            return Any();
        }
    virtual Reference< XMultiComponentFactory > SAL_CALL getServiceManager(  )
        throw (RuntimeException)
        {
            return Reference< XMultiComponentFactory > ();
        }

};

SAL_IMPLEMENT_MAIN()
{
    Reference<XInterface> xIFace;

    Module module;

    OUString dllName(
        RTL_CONSTASCII_USTRINGPARAM("shlibloader.uno" SAL_DLLEXTENSION) );

    if (module.load(dllName))
    {
        // try to get provider from module
        component_getFactoryFunc pCompFactoryFunc = (component_getFactoryFunc)
            module.getSymbol( OUString::createFromAscii(COMPONENT_GETFACTORY) );

        if (pCompFactoryFunc)
        {
            XSingleServiceFactory * pRet = (XSingleServiceFactory *)(*pCompFactoryFunc)(
                "com.sun.star.comp.stoc.DLLComponentLoader", 0, 0 );
            if (pRet)
            {
                xIFace = pRet;
                pRet->release();
            }
        }
    }

    TEST_ENSHURE( xIFace.is(), "testloader error1");

    Reference<XSingleComponentFactory> xFactory( Reference<XSingleComponentFactory>::query(xIFace) );

    TEST_ENSHURE( xFactory.is(), "testloader error2");

    Reference<XInterface> xLoader = xFactory->createInstanceWithContext( new EmptyComponentContext );

    TEST_ENSHURE( xLoader.is(), "testloader error3");

    Reference<XServiceInfo> xServInfo( Reference<XServiceInfo>::query(xLoader) );

    TEST_ENSHURE( xServInfo.is(), "testloader error4");

    TEST_ENSHURE( xServInfo->getImplementationName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.comp.stoc.DLLComponentLoader") ), "testloader error5");
    TEST_ENSHURE( xServInfo->supportsService(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")) ), "testloader error6");
    TEST_ENSHURE( xServInfo->getSupportedServiceNames().getLength() == 1, "testloader error7");

    xIFace.clear();
    xFactory.clear();
    xLoader.clear();
    xServInfo.clear();

    printf("Test Dll ComponentLoader, OK!\n");

    return(0);
}

<|endoftext|>


<commit_before>//===- DriverUtils.cpp ----------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains utility functions for the driver. Because there
// are so many small functions, we created this separate file to make
// Driver.cpp less cluttered.
//
//===----------------------------------------------------------------------===//

#include "Driver.h"
#include "Error.h"
#include "lld/Config/Version.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/StringSaver.h"

using namespace llvm;

using namespace lld;
using namespace lld::elf;

// Create OptTable

// Create prefix string literals used in Options.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX

// Create table mapping all options defined in Options.td
static const opt::OptTable::Info infoTable[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10)            \
  {                                                                            \
    X1, X2, X9, X10, OPT_##ID, opt::Option::KIND##Class, X8, X7, OPT_##GROUP,  \
        OPT_##ALIAS, X6                                                        \
  }                                                                            \
  ,
#include "Options.inc"
#undef OPTION
};

ELFOptTable::ELFOptTable() : OptTable(infoTable) {}

// Parses a given list of options.
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
  // Make InputArgList from string vectors.
  unsigned MissingIndex;
  unsigned MissingCount;

  // Expand response files. '@<filename>' is replaced by the file's contents.
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
  StringSaver Saver(Alloc);
  llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, Vec);

  // Parse options and then do error checking.
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
  if (MissingCount)
    error(Twine("missing arg value for \"") + Args.getArgString(MissingIndex) +
          "\", expected " + Twine(MissingCount) +
          (MissingCount == 1 ? " argument.\n" : " arguments"));

  iterator_range<opt::arg_iterator> Unknowns = Args.filtered(OPT_UNKNOWN);
  for (auto *Arg : Unknowns)
    warning("warning: unknown argument: " + Arg->getSpelling());
  if (Unknowns.begin() != Unknowns.end())
    error("unknown argument(s) found");
  return Args;
}

void elf::printHelp(const char *Argv0) {
  ELFOptTable Table;
  Table.PrintHelp(outs(), Argv0, "lld", false);
}

void elf::printVersion() {
  outs() << "LLD " << getLLDVersion();
  std::string S = getLLDRepositoryVersion();
  if (!S.empty())
    outs() << " " << S;
  outs() << "\n";
}

std::string elf::findFromSearchPaths(StringRef Path) {
  for (StringRef Dir : Config->SearchPaths) {
    std::string FullPath = buildSysrootedPath(Dir, Path);
    if (sys::fs::exists(FullPath))
      return FullPath;
  }
  return "";
}

// Searches a given library from input search paths, which are filled
// from -L command line switches. Returns a path to an existent library file.
std::string elf::searchLibrary(StringRef Path) {
  std::vector<std::string> Names;
  if (Path[0] == ':') {
    Names.push_back(Path.drop_front());
  } else {
    if (!Config->Static)
      Names.push_back(("lib" + Path + ".so").str());
    Names.push_back(("lib" + Path + ".a").str());
  }
  for (const std::string &Name : Names) {
    std::string S = findFromSearchPaths(Name);
    if (!S.empty())
      return S;
  }
  return "";
}

// Makes a path by concatenating Dir and File.
// If Dir starts with '=' the result will be preceded by Sysroot,
// which can be set with --sysroot command line switch.
std::string elf::buildSysrootedPath(StringRef Dir, StringRef File) {
  SmallString<128> Path;
  if (Dir.startswith("="))
    sys::path::append(Path, Config->Sysroot, Dir.substr(1), File);
  else
    sys::path::append(Path, Dir, File);
  return Path.str();
}
<commit_msg>Simplify. NFC.<commit_after>//===- DriverUtils.cpp ----------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains utility functions for the driver. Because there
// are so many small functions, we created this separate file to make
// Driver.cpp less cluttered.
//
//===----------------------------------------------------------------------===//

#include "Driver.h"
#include "Error.h"
#include "lld/Config/Version.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/StringSaver.h"

using namespace llvm;

using namespace lld;
using namespace lld::elf;

// Create OptTable

// Create prefix string literals used in Options.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX

// Create table mapping all options defined in Options.td
static const opt::OptTable::Info infoTable[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10)            \
  {                                                                            \
    X1, X2, X9, X10, OPT_##ID, opt::Option::KIND##Class, X8, X7, OPT_##GROUP,  \
        OPT_##ALIAS, X6                                                        \
  }                                                                            \
  ,
#include "Options.inc"
#undef OPTION
};

ELFOptTable::ELFOptTable() : OptTable(infoTable) {}

// Parses a given list of options.
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
  // Make InputArgList from string vectors.
  unsigned MissingIndex;
  unsigned MissingCount;

  // Expand response files. '@<filename>' is replaced by the file's contents.
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
  StringSaver Saver(Alloc);
  llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, Vec);

  // Parse options and then do error checking.
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
  if (MissingCount)
    error(Twine("missing arg value for \"") + Args.getArgString(MissingIndex) +
          "\", expected " + Twine(MissingCount) +
          (MissingCount == 1 ? " argument.\n" : " arguments"));

  iterator_range<opt::arg_iterator> Unknowns = Args.filtered(OPT_UNKNOWN);
  for (auto *Arg : Unknowns)
    warning("warning: unknown argument: " + Arg->getSpelling());
  if (Unknowns.begin() != Unknowns.end())
    error("unknown argument(s) found");
  return Args;
}

void elf::printHelp(const char *Argv0) {
  ELFOptTable Table;
  Table.PrintHelp(outs(), Argv0, "lld", false);
}

void elf::printVersion() {
  outs() << "LLD " << getLLDVersion();
  std::string S = getLLDRepositoryVersion();
  if (!S.empty())
    outs() << " " << S;
  outs() << "\n";
}

std::string elf::findFromSearchPaths(StringRef Path) {
  for (StringRef Dir : Config->SearchPaths) {
    std::string FullPath = buildSysrootedPath(Dir, Path);
    if (sys::fs::exists(FullPath))
      return FullPath;
  }
  return "";
}

// Searches a given library from input search paths, which are filled
// from -L command line switches. Returns a path to an existent library file.
std::string elf::searchLibrary(StringRef Path) {
  if (Path.startswith(":"))
    return findFromSearchPaths(Path.substr(1));
  if (!Config->Static) {
    std::string S = findFromSearchPaths(("lib" + Path + ".so").str());
    if (!S.empty())
      return S;
  }
  return findFromSearchPaths(("lib" + Path + ".a").str());
}

// Makes a path by concatenating Dir and File.
// If Dir starts with '=' the result will be preceded by Sysroot,
// which can be set with --sysroot command line switch.
std::string elf::buildSysrootedPath(StringRef Dir, StringRef File) {
  SmallString<128> Path;
  if (Dir.startswith("="))
    sys::path::append(Path, Config->Sysroot, Dir.substr(1), File);
  else
    sys::path::append(Path, Dir, File);
  return Path.str();
}
<|endoftext|>


<commit_before>#include <solution.h>

bool isCycle(int n, vector<bool>& visitFlag, vector<bool>& pollFlag, vector<vector<int>> courses){
	if(pollFlag[n]){
		return true;
	}
	pollFlag[n] = true;
	visitFlag[n] = true;
	for(auto i : courses[n]){
		if(isCycle(i, visitFlag, pollFlag, courses)){
			return true;
		}
	}
	pollFlag[n] = false;
	return false;
}

bool Solution::canFinish(int numCourses, vector<vector<int>>& prerequisites){
	if(numCourses <= 0){
		return true;
	}

	vector<vector<int>> courses(numCourses);
	for(auto& prerequire : prerequisites){
		courses[prerequire[0]].push_back(prerequire[1]);
	}

	vector<bool> visitFlag(numCourses, false);
	for(size_t i = 0; i < courses.size(); ++i){
		if(courses[i].empty() || visitFlag[i]){
			continue;
		}

		vector<bool> pollFlag(numCourses, false);
		if(isCycle(i, visitFlag, pollFlag, courses)){
			return false;
		}
	}
	return true;
}
<commit_msg>fix(207): 1000ms<commit_after>#include <solution.h>

bool isCycle(int n, vector<bool>& visitFlag, vector<bool>& pollFlag, vector<vector<int>> courses){
	if(pollFlag[n]){
		return true;
	}
	if(visitFlag[n]){
		return false;
	}
	pollFlag[n] = true;
	visitFlag[n] = true;
	for(auto i : courses[n]){
		if(isCycle(i, visitFlag, pollFlag, courses)){
			return true;
		}
	}
	pollFlag[n] = false;
	return false;
}

bool Solution::canFinish(int numCourses, vector<vector<int>>& prerequisites){
	if(numCourses <= 0){
		return true;
	}

	vector<vector<int>> courses(numCourses);
	for(auto& prerequire : prerequisites){
		courses[prerequire[0]].push_back(prerequire[1]);
	}

	vector<bool> visitFlag(numCourses, false);
	for(size_t i = 0; i < courses.size(); ++i){
		if(courses[i].empty() || visitFlag[i]){
			continue;
		}

		vector<bool> pollFlag(numCourses, false);
		if(isCycle(i, visitFlag, pollFlag, courses)){
			return false;
		}
	}
	return true;
}
<|endoftext|>


<commit_before>#include "hermes1d.h"

#include "python_api.h"

#include "_hermes1d_api.h"

static int N_eq = 1;
int N_elem = 100;                         // number of elements
double A = 0, B = 20;                     // domain end points
int P_init = 2;                           // initial polynomal degree

double l = 0;

double lhs(int num, double *x, double *weights,
                double *u, double *dudx, double *v, double *dvdx,
                double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                void *user_data)
{
    double val = 0;
    for(int i = 0; i<num; i++) {
        double coeff;
        double r = x[i];
        // specify r^2*V:
        double rrV = -r; // r^2 * (-1/r) = -r
        coeff = 0.5*r*r*dudx[i]*dvdx[i] + (rrV + 0.5 * (l + 1)*l) *u[i]*v[i];
        val += coeff*weights[i];
    }
    return val;
}

double rhs(int num, double *x, double *weights,
                double *u, double *dudx, double *v, double *dvdx,
                double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                void *user_data)
{
    double val = 0;
    for(int i = 0; i < num; i++) {
        double r = x[i];
        val += u[i]*v[i]*r*r*weights[i];
    }
    return val;
}

double E;

double residual(int num, double *x, double *weights,
                double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double *v, double *dvdx, void *user_data)
{
    double *u = &u_prev[0][0][0];
    double *dudx = &du_prevdx[0][0][0];
    double val = 0;
    for(int i = 0; i<num; i++) {
        double coeff;
        coeff = 0.5*x[i]*x[i]*dudx[i]*dvdx[i] -u[i]*v[i]*x[i]
            + 0.5 * (l + 1)*l *u[i]*v[i];
        coeff -= E*u[i]*v[i]*x[i]*x[i];
        val += coeff*weights[i];
    }
    return val;
}

void insert_matrix(DenseMatrix *mat, int len)
{
  double _mat[len*len];
  for(int i=0; i<len; i++)
      for(int j=0; j<len; j++)
          _mat[i*len+j] = mat->get(i, j);
  insert_object("len", c2py_int(len));
  insert_object("mat", c2numpy_double(_mat, len*len));
  cmd("_ = mat.reshape((len, len))");
  cmd("del len");
  cmd("del mat");
}

/******************************************************************************/
int main(int argc, char* argv[]) {
  // create mesh
  Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq);
  // you can set the zero dirichlet at the right hand side
  //mesh.set_bc_right_dirichlet(0, 0);

  // variable for the total number of DOF
  int N_dof = mesh->assign_dofs();
  printf("ndofs: %d", N_dof);

  // register weak forms
  DiscreteProblem *dp1 = new DiscreteProblem();
  dp1->add_matrix_form(0, 0, lhs);
  DiscreteProblem *dp2 = new DiscreteProblem();
  dp2->add_matrix_form(0, 0, rhs);

  DiscreteProblem *dp3 = new DiscreteProblem();
  dp3->add_vector_form(0, residual);

  // allocate Jacobi matrix and residual
  DenseMatrix *mat1 = new DenseMatrix(N_dof);
  DenseMatrix *mat2 = new DenseMatrix(N_dof);
  double *y_prev = new double[N_dof];

  dp1->assemble_jacobian(mesh, mat1);
  dp2->assemble_jacobian(mesh, mat2);

  printf("Importing hermes1d\n");
  Python p;

  p.exec("print 'Python initialized'");
  insert_matrix(mat1, N_dof); cmd("A = _");
  insert_matrix(mat2, N_dof); cmd("B = _");
  cmd("from utils import solve");
  cmd("eigs = solve(A, B)");
  cmd("E, v = eigs[0]");
  //cmd("print 'v[0]', v[0]");
  //cmd("print E");
  //double *v;
  int n;
  //numpy2c_double_inplace(get_object("v"), &v, &n);

  double *res = new double[N_dof];
  E = py2c_double(get_object("E"));
  printf("E=%.10f\n", E);
  E = -0.5;
  dp3->assemble_residual(mesh, res);
  // calculate L2 norm of residual vector
  double res_norm = 0;
  for(int i=0; i<N_dof; i++) res_norm += res[i]*res[i];
  res_norm = sqrt(res_norm);
  printf("L2 norm of the residual: %f\n", res_norm);

  Linearizer l(mesh);
  const char *out_filename = "solution.gp";
  l.plot_solution(out_filename);

  printf("still ok\n");
  if (import_hermes1d___hermes1d())
      throw std::runtime_error("");
  p.push("mesh",  c2py_Mesh(mesh));
  printf("2\n");
  cmd("from plot import plot_eigs, plot_file");
  cmd("plot_eigs(mesh, eigs)");
  //cmd("plot_eigs(eigs)");
  printf("Done.\n");
  return 0;
}
<commit_msg>Update insert_matrix in Schroedinger<commit_after>#include "hermes1d.h"

#include "python_api.h"

#include "_hermes1d_api.h"

static int N_eq = 1;
int N_elem = 100;                         // number of elements
double A = 0, B = 20;                     // domain end points
int P_init = 2;                           // initial polynomal degree

double l = 0;

double lhs(int num, double *x, double *weights,
                double *u, double *dudx, double *v, double *dvdx,
                double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                void *user_data)
{
    double val = 0;
    for(int i = 0; i<num; i++) {
        double coeff;
        double r = x[i];
        // specify r^2*V:
        double rrV = -r; // r^2 * (-1/r) = -r
        coeff = 0.5*r*r*dudx[i]*dvdx[i] + (rrV + 0.5 * (l + 1)*l) *u[i]*v[i];
        val += coeff*weights[i];
    }
    return val;
}

double rhs(int num, double *x, double *weights,
                double *u, double *dudx, double *v, double *dvdx,
                double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                void *user_data)
{
    double val = 0;
    for(int i = 0; i < num; i++) {
        double r = x[i];
        val += u[i]*v[i]*r*r*weights[i];
    }
    return val;
}

double E;

double residual(int num, double *x, double *weights,
                double u_prev[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double du_prevdx[MAX_SLN_NUM][MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
                double *v, double *dvdx, void *user_data)
{
    double *u = &u_prev[0][0][0];
    double *dudx = &du_prevdx[0][0][0];
    double val = 0;
    for(int i = 0; i<num; i++) {
        double coeff;
        coeff = 0.5*x[i]*x[i]*dudx[i]*dvdx[i] -u[i]*v[i]*x[i]
            + 0.5 * (l + 1)*l *u[i]*v[i];
        coeff -= E*u[i]*v[i]*x[i]*x[i];
        val += coeff*weights[i];
    }
    return val;
}

void insert_matrix(Python *p, DenseMatrix *mat, int len)
{
  double _mat[len*len];
  for(int i=0; i<len; i++)
      for(int j=0; j<len; j++)
          _mat[i*len+j] = mat->get(i, j);
  p->push("len", c2py_int(len));
  p->push("mat", c2numpy_double(_mat, len*len));
  p->exec("_ = mat.reshape((len, len))");
  p->exec("del len");
  p->exec("del mat");
}

/******************************************************************************/
int main(int argc, char* argv[]) {
  // create mesh
  Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq);
  // you can set the zero dirichlet at the right hand side
  //mesh.set_bc_right_dirichlet(0, 0);

  // variable for the total number of DOF
  int N_dof = mesh->assign_dofs();
  printf("ndofs: %d", N_dof);

  // register weak forms
  DiscreteProblem *dp1 = new DiscreteProblem();
  dp1->add_matrix_form(0, 0, lhs);
  DiscreteProblem *dp2 = new DiscreteProblem();
  dp2->add_matrix_form(0, 0, rhs);

  DiscreteProblem *dp3 = new DiscreteProblem();
  dp3->add_vector_form(0, residual);

  // allocate Jacobi matrix and residual
  DenseMatrix *mat1 = new DenseMatrix(N_dof);
  DenseMatrix *mat2 = new DenseMatrix(N_dof);
  double *y_prev = new double[N_dof];

  dp1->assemble_jacobian(mesh, mat1);
  dp2->assemble_jacobian(mesh, mat2);

  printf("Importing hermes1d\n");
  Python p;

  p.exec("print 'Python initialized'");
  insert_matrix(&p, mat1, N_dof); p.exec("A = _");
  insert_matrix(&p, mat2, N_dof); p.exec("B = _");
  p.exec("from utils import solve");
  p.exec("eigs = solve(A, B)");
  p.exec("E, v = eigs[0]");
  int n;

  double *res = new double[N_dof];
  E = py2c_double(get_object("E"));
  printf("E=%.10f\n", E);
  E = -0.5;
  dp3->assemble_residual(mesh, res);
  // calculate L2 norm of residual vector
  double res_norm = 0;
  for(int i=0; i<N_dof; i++) res_norm += res[i]*res[i];
  res_norm = sqrt(res_norm);
  printf("L2 norm of the residual: %f\n", res_norm);

  Linearizer l(mesh);
  const char *out_filename = "solution.gp";
  l.plot_solution(out_filename);

  printf("still ok\n");
  if (import_hermes1d___hermes1d())
      throw std::runtime_error("");
  p.push("mesh",  c2py_Mesh(mesh));
  printf("2\n");
  cmd("from plot import plot_eigs, plot_file");
  cmd("plot_eigs(mesh, eigs)");
  //cmd("plot_eigs(eigs)");
  printf("Done.\n");
  return 0;
}
<|endoftext|>


<commit_before>#include "SM_Matrix2D.h"

namespace sm
{

Matrix2D::Matrix2D()
{
	Identity();
}

Matrix2D::Matrix2D(const mat4& mt)
{
	x[0] = mt.x[0];
	x[1] = mt.x[1];
	x[2] = mt.x[4];
	x[3] = mt.x[5];
	x[4] = mt.x[12];
	x[5] = mt.x[13];
}

Matrix2D::Matrix2D(const Matrix2D& mt)
{
	memcpy(x, mt.x, sizeof(x));
}

Matrix2D& Matrix2D::operator = (const Matrix2D& mt)
{
	memcpy(x, mt.x, sizeof(x));
	return *this;
}

vec2 Matrix2D::operator * (const vec2& v) const
{
	vec2 ret;
	ret.x = (v.x * x[0] + v.y * x[2]) + x[4];
	ret.y = (v.x * x[1] + v.y * x[3]) + x[5];
	return ret;
}

mat4 Matrix2D::ToMat4() const
{
	mat4 mt;
	mt.x[0]  = x[0];
	mt.x[1]  = x[1];
	mt.x[4]  = x[2];
	mt.x[5]  = x[3];
	mt.x[12] = x[4];
	mt.x[13] = x[5];
	return mt;
}

}<commit_msg>fix head<commit_after>#include "SM_Matrix2D.h"
#include "string.h"

namespace sm
{

Matrix2D::Matrix2D()
{
	Identity();
}

Matrix2D::Matrix2D(const mat4& mt)
{
	x[0] = mt.x[0];
	x[1] = mt.x[1];
	x[2] = mt.x[4];
	x[3] = mt.x[5];
	x[4] = mt.x[12];
	x[5] = mt.x[13];
}

Matrix2D::Matrix2D(const Matrix2D& mt)
{
	memcpy(x, mt.x, sizeof(x));
}

Matrix2D& Matrix2D::operator = (const Matrix2D& mt)
{
	memcpy(x, mt.x, sizeof(x));
	return *this;
}

vec2 Matrix2D::operator * (const vec2& v) const
{
	vec2 ret;
	ret.x = (v.x * x[0] + v.y * x[2]) + x[4];
	ret.y = (v.x * x[1] + v.y * x[3]) + x[5];
	return ret;
}

mat4 Matrix2D::ToMat4() const
{
	mat4 mt;
	mt.x[0]  = x[0];
	mt.x[1]  = x[1];
	mt.x[4]  = x[2];
	mt.x[5]  = x[3];
	mt.x[12] = x[4];
	mt.x[13] = x[5];
	return mt;
}

}
<|endoftext|>


<commit_before>
// Implementation for the class Structure
//
// jhrg 9/14/94

// $Log: Sequence.cc,v $
// Revision 1.3  1994/10/17 23:34:49  jimg
// Added code to print_decl so that variable declarations are pretty
// printed.
// Added private mfunc duplicate().
// Added ptr_duplicate().
// Added Copy ctor, dtor and operator=.
//
// Revision 1.2  1994/09/23  14:48:31  jimg
// Fixed some errors in comments.
//

#ifdef _GNUG_
#pragma implementation
#endif

#include "debug.h"
#include "Sequence.h"

// private

void
Sequence::duplicate(const Sequence &s)
{
    set_var_name(s.get_var_name());
    set_var_type(s.get_var_type());

    for (Pix p = first_var(); p; next_var(p))
	add_var(var(p)->ptr_duplicate());
}

// protected

BaseType *
Sequence::ptr_duplicate()
{
    return new Sequence(*this);
}

// This ctor is silly -- in order to add fields to a Structure or Sequence,
// you must use add_var (a mfunc of Structure).

Sequence::Sequence(const String &n, const String &t)
{
    set_var_name(n);
    set_var_type(t);
}

Sequence::Sequence(const Sequence &rhs)
{
    duplicate(rhs);
}

// NB: since Sequence is a child of Structure, Structure's dtor will be
// called and will delete the pointers in Structure's mvar `var'.

Sequence::~Sequence()
{
    DBG(cerr << "Entering Sequence dtor" << endl);
}

const Sequence &
Sequence::operator=(const Sequence &rhs)
{
    if (this == &rhs)
	return *this;

    duplicate(rhs);

    return *this;
}
<commit_msg>Added data transmission member functions serialize() and deserialize() Modified size() member function to return cumulative size of all members. Fixed the duplicate() member function to correctly access the data members of the sequence being duplicated.<commit_after>
// Implementation for the class Structure
//
// jhrg 9/14/94

// $Log: Sequence.cc,v $
// Revision 1.4  1994/12/08 15:55:58  dan
// Added data transmission member functions serialize() and deserialize()
// Modified size() member function to return cumulative size of all members.
// Fixed the duplicate() member function to correctly access the data members
// of the sequence being duplicated.
//
// Revision 1.3  1994/10/17  23:34:49  jimg
// Added code to print_decl so that variable declarations are pretty
// printed.
// Added private mfunc duplicate().
// Added ptr_duplicate().
// Added Copy ctor, dtor and operator=.
//
// Revision 1.2  1994/09/23  14:48:31  jimg
// Fixed some errors in comments.
//

#ifdef _GNUG_
#pragma implementation
#endif

#include "debug.h"
#include "Sequence.h"

// private

void
Sequence::duplicate(const Sequence &s)
{
    set_var_name(s.get_var_name());
    set_var_type(s.get_var_type());

    Sequence &cs = (Sequence)s; // cast away const

    for (Pix p = cs.first_var(); p; cs.next_var(p))
	add_var(cs.var(p)->ptr_duplicate());
}

// protected

BaseType *
Sequence::ptr_duplicate()
{
    return new Sequence(*this);
}

// This ctor is silly -- in order to add fields to a Structure or Sequence,
// you must use add_var (a mfunc of Structure).

Sequence::Sequence(const String &n, const String &t, FILE *in, FILE *out)
{
    set_var_name(n);
    set_var_type(t);
}

Sequence::Sequence(const Sequence &rhs)
{
    duplicate(rhs);
}

// NB: since Sequence is a child of Structure, Structure's dtor will be
// called and will delete the pointers in Structure's mvar `var'.

Sequence::~Sequence()
{
    DBG(cerr << "Entering Sequence dtor" << endl);
}

const Sequence &
Sequence::operator=(const Sequence &rhs)
{
    if (this == &rhs)
	return *this;

    duplicate(rhs);

    return *this;
}

unsigned int
Sequence::size()
{
  unsigned int sz = 0;
  for( Pix p = first_var(); p; next_var(p))
    sz += var(p)->size();

  return sz;
}

bool
Sequence::serialize(bool flush, unsigned int num)
{
    bool status;

    for (Pix p = first_var(); p; next_var(p))
      {
	if ( !(status = var(p)->serialize(true)) ) break;
      }
    if (status && flush)
	status = expunge();

    return status;
}

unsigned int
Sequence::deserialize()
{
    unsigned int num, sz = 0;

    for (Pix p = first_var(); p; next_var(p)) {
      if ( !(num = var(p)->deserialize()) ) break;
      else sz += num;
    }
    return num ? sz : (unsigned int)FALSE;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2006 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include "DocumentObjectGroup.h"
#include "DocumentObjectGroupPy.h"
#include "GroupExtensionPy.h"
#include "Document.h"
#include "FeaturePythonPyImp.h"

using namespace App;

EXTENSION_PROPERTY_SOURCE(App::GroupExtension, App::DocumentObjectExtension)

GroupExtension::GroupExtension()
{
    initExtension(GroupExtension::getExtensionClassTypeId());

    EXTENSION_ADD_PROPERTY_TYPE(Group,(0),"Base",(App::PropertyType)(Prop_Output),"List of referenced objects");
}

GroupExtension::~GroupExtension()
{
    Base::Console().Message("Delete group extension\n");
}

DocumentObject* GroupExtension::addObject(const char* sType, const char* pObjectName)
{
    DocumentObject* obj = getExtendedObject()->getDocument()->addObject(sType, pObjectName);
    if(!allowObject(obj)) {
        getExtendedObject()->getDocument()->remObject(obj->getNameInDocument());
        return nullptr;
    }
    if (obj) addObject(obj);
    return obj;
}

void GroupExtension::addObject(DocumentObject* obj)
{
    if(!allowObject(obj))
        return;

    if (!hasObject(obj)) {
        std::vector<DocumentObject*> grp = Group.getValues();
        grp.push_back(obj);
        Group.setValues(grp);
    }
}

void GroupExtension::removeObject(DocumentObject* obj)
{
    const std::vector<DocumentObject*> & grp = Group.getValues();
    std::vector<DocumentObject*> newGrp;

    std::remove_copy (grp.begin(), grp.end(), std::back_inserter (newGrp), obj);
    if (grp.size() != newGrp.size()) {
        Group.setValues (newGrp);
    }
}

void GroupExtension::removeObjectsFromDocument()
{
    const std::vector<DocumentObject*> & grp = Group.getValues();
    // Use set so iterate on each linked object exactly one time (in case of multiple links to the same document)
    std::set<DocumentObject*> grpSet (grp.begin(), grp.end());

    for (std::set<DocumentObject*>::iterator it = grpSet.begin(); it != grpSet.end(); ++it) {
        removeObjectFromDocument(*it);
    }
}

void GroupExtension::removeObjectFromDocument(DocumentObject* obj)
{
    // remove all children
    if (obj->hasExtension(GroupExtension::getExtensionClassTypeId())) {
        GroupExtension *grp = static_cast<GroupExtension*>(obj->getExtension(GroupExtension::getExtensionClassTypeId()));

        // recursive call to remove all subgroups
        grp->removeObjectsFromDocument();
    }

    getExtendedObject()->getDocument()->remObject(obj->getNameInDocument());
}

DocumentObject *GroupExtension::getObject(const char *Name) const
{
    DocumentObject* obj = getExtendedObject()->getDocument()->getObject(Name);
    if (obj && hasObject(obj))
        return obj;
    return 0;
}

bool GroupExtension::hasObject(const DocumentObject* obj, bool recursive) const
{
    const std::vector<DocumentObject*>& grp = Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if (*it == obj) {
            return true;
        } else if ( recursive && (*it)->hasExtension(GroupExtension::getExtensionClassTypeId()) ) {
            App::GroupExtension *subGroup = static_cast<App::GroupExtension *> (
                                    (*it)->getExtension(GroupExtension::getExtensionClassTypeId()));

            if (subGroup->hasObject (obj, recursive)) {
                return true;
            }
        }
    }

    return false;
}

bool GroupExtension::isChildOf(const GroupExtension* group) const
{
    const std::vector<DocumentObject*>& grp = group->Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if (*it == getExtendedObject())
            return true;
        if ((*it)->hasExtension(GroupExtension::getExtensionClassTypeId())) {
            if (this->isChildOf(static_cast<GroupExtension*>((*it)->getExtension(GroupExtension::getExtensionClassTypeId()))))

                return true;
        }
    }

    return false;
}

std::vector<DocumentObject*> GroupExtension::getObjects() const
{
    return Group.getValues();
}

std::vector<DocumentObject*> GroupExtension::getObjectsOfType(const Base::Type& typeId) const
{
    std::vector<DocumentObject*> type;
    const std::vector<DocumentObject*>& grp = Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if ( (*it)->getTypeId().isDerivedFrom(typeId))
            type.push_back(*it);
    }

    return type;
}

int GroupExtension::countObjectsOfType(const Base::Type& typeId) const
{
    int type=0;
    const std::vector<DocumentObject*>& grp = Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if ( (*it)->getTypeId().isDerivedFrom(typeId))
            type++;
    }

    return type;
}

DocumentObject* GroupExtension::getGroupOfObject(const DocumentObject* obj)
{
    const Document* doc = obj->getDocument();
    std::vector<DocumentObject*> grps = doc->getObjectsOfType(GroupExtension::getExtensionClassTypeId());
    for (std::vector<DocumentObject*>::const_iterator it = grps.begin(); it != grps.end(); ++it) {
        GroupExtension* grp = (GroupExtension*)(*it);
        if (grp->hasObject(obj))
            return *it;
    }

    return 0;
}

PyObject* GroupExtension::getExtensionPyObject(void) {

    if (ExtensionPythonObject.is(Py::_None())){
        // ref counter is set to 1
        auto grp = new GroupExtensionPy(this);
        ExtensionPythonObject = Py::Object(grp,true);
    }
    return Py::new_reference_to(ExtensionPythonObject);
}

namespace App {
EXTENSION_PROPERTY_SOURCE_TEMPLATE(App::GroupExtensionPython, App::GroupExtension)

// explicit template instantiation
template class AppExport ExtensionPythonT<GroupExtensionPythonT<GroupExtension>>;
}
<commit_msg>Remove unneeded console output<commit_after>/***************************************************************************
 *   Copyright (c) 2006 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include "DocumentObjectGroup.h"
#include "DocumentObjectGroupPy.h"
#include "GroupExtensionPy.h"
#include "Document.h"
#include "FeaturePythonPyImp.h"

using namespace App;

EXTENSION_PROPERTY_SOURCE(App::GroupExtension, App::DocumentObjectExtension)

GroupExtension::GroupExtension()
{
    initExtension(GroupExtension::getExtensionClassTypeId());

    EXTENSION_ADD_PROPERTY_TYPE(Group,(0),"Base",(App::PropertyType)(Prop_Output),"List of referenced objects");
}

GroupExtension::~GroupExtension()
{
}

DocumentObject* GroupExtension::addObject(const char* sType, const char* pObjectName)
{
    DocumentObject* obj = getExtendedObject()->getDocument()->addObject(sType, pObjectName);
    if(!allowObject(obj)) {
        getExtendedObject()->getDocument()->remObject(obj->getNameInDocument());
        return nullptr;
    }
    if (obj) addObject(obj);
    return obj;
}

void GroupExtension::addObject(DocumentObject* obj)
{
    if(!allowObject(obj))
        return;

    if (!hasObject(obj)) {
        std::vector<DocumentObject*> grp = Group.getValues();
        grp.push_back(obj);
        Group.setValues(grp);
    }
}

void GroupExtension::removeObject(DocumentObject* obj)
{
    const std::vector<DocumentObject*> & grp = Group.getValues();
    std::vector<DocumentObject*> newGrp;

    std::remove_copy (grp.begin(), grp.end(), std::back_inserter (newGrp), obj);
    if (grp.size() != newGrp.size()) {
        Group.setValues (newGrp);
    }
}

void GroupExtension::removeObjectsFromDocument()
{
    const std::vector<DocumentObject*> & grp = Group.getValues();
    // Use set so iterate on each linked object exactly one time (in case of multiple links to the same document)
    std::set<DocumentObject*> grpSet (grp.begin(), grp.end());

    for (std::set<DocumentObject*>::iterator it = grpSet.begin(); it != grpSet.end(); ++it) {
        removeObjectFromDocument(*it);
    }
}

void GroupExtension::removeObjectFromDocument(DocumentObject* obj)
{
    // remove all children
    if (obj->hasExtension(GroupExtension::getExtensionClassTypeId())) {
        GroupExtension *grp = static_cast<GroupExtension*>(obj->getExtension(GroupExtension::getExtensionClassTypeId()));

        // recursive call to remove all subgroups
        grp->removeObjectsFromDocument();
    }

    getExtendedObject()->getDocument()->remObject(obj->getNameInDocument());
}

DocumentObject *GroupExtension::getObject(const char *Name) const
{
    DocumentObject* obj = getExtendedObject()->getDocument()->getObject(Name);
    if (obj && hasObject(obj))
        return obj;
    return 0;
}

bool GroupExtension::hasObject(const DocumentObject* obj, bool recursive) const
{
    const std::vector<DocumentObject*>& grp = Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if (*it == obj) {
            return true;
        } else if ( recursive && (*it)->hasExtension(GroupExtension::getExtensionClassTypeId()) ) {
            App::GroupExtension *subGroup = static_cast<App::GroupExtension *> (
                                    (*it)->getExtension(GroupExtension::getExtensionClassTypeId()));

            if (subGroup->hasObject (obj, recursive)) {
                return true;
            }
        }
    }

    return false;
}

bool GroupExtension::isChildOf(const GroupExtension* group) const
{
    const std::vector<DocumentObject*>& grp = group->Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if (*it == getExtendedObject())
            return true;
        if ((*it)->hasExtension(GroupExtension::getExtensionClassTypeId())) {
            if (this->isChildOf(static_cast<GroupExtension*>((*it)->getExtension(GroupExtension::getExtensionClassTypeId()))))

                return true;
        }
    }

    return false;
}

std::vector<DocumentObject*> GroupExtension::getObjects() const
{
    return Group.getValues();
}

std::vector<DocumentObject*> GroupExtension::getObjectsOfType(const Base::Type& typeId) const
{
    std::vector<DocumentObject*> type;
    const std::vector<DocumentObject*>& grp = Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if ( (*it)->getTypeId().isDerivedFrom(typeId))
            type.push_back(*it);
    }

    return type;
}

int GroupExtension::countObjectsOfType(const Base::Type& typeId) const
{
    int type=0;
    const std::vector<DocumentObject*>& grp = Group.getValues();
    for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
        if ( (*it)->getTypeId().isDerivedFrom(typeId))
            type++;
    }

    return type;
}

DocumentObject* GroupExtension::getGroupOfObject(const DocumentObject* obj)
{
    const Document* doc = obj->getDocument();
    std::vector<DocumentObject*> grps = doc->getObjectsOfType(GroupExtension::getExtensionClassTypeId());
    for (std::vector<DocumentObject*>::const_iterator it = grps.begin(); it != grps.end(); ++it) {
        GroupExtension* grp = (GroupExtension*)(*it);
        if (grp->hasObject(obj))
            return *it;
    }

    return 0;
}

PyObject* GroupExtension::getExtensionPyObject(void) {

    if (ExtensionPythonObject.is(Py::_None())){
        // ref counter is set to 1
        auto grp = new GroupExtensionPy(this);
        ExtensionPythonObject = Py::Object(grp,true);
    }
    return Py::new_reference_to(ExtensionPythonObject);
}

namespace App {
EXTENSION_PROPERTY_SOURCE_TEMPLATE(App::GroupExtensionPython, App::GroupExtension)

// explicit template instantiation
template class AppExport ExtensionPythonT<GroupExtensionPythonT<GroupExtension>>;
}
<|endoftext|>


<commit_before>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <Beard/ui/Defs.hpp>
#include <Beard/ui/ProtoGrid.hpp>

namespace Beard {
namespace ui {

// class ProtoGrid implementation

ProtoGrid::~ProtoGrid() noexcept = default;

// internals

namespace {
inline void
expand_range(
	Vec2& range,
	ui::index_type const begin,
	ui::index_type const end
) noexcept {
	if (-1 != range.x) {
		if (range.x == range.y) {
			range.x = begin;
			range.y = end;
		} else if (-1 == begin) {
			range.x = -1;
			range.y = -1;
		} else {
			range.x = min_ce(range.x, begin);
			range.y = max_ce(range.y, end);
		}
	}
}
} // anonymous namespace

void
ProtoGrid::update_view(
	ui::index_type row_begin,
	ui::index_type row_end,
	ui::index_type col_begin,
	ui::index_type col_end,
	bool const retain_intersection
) noexcept {
	row_begin = value_clamp(row_begin, 0, m_row_count);
	row_end = min_ce(
		value_clamp(row_end, row_begin, m_row_count),
		row_begin + m_view.fit_count
	);
	col_begin = value_clamp(col_begin, 0, m_col_count);
	col_end = value_clamp(col_end, col_begin, m_col_count);

	Vec2 const nrr{row_begin, row_end};
	auto const orc = m_view.row_count;
	Vec2 const orr = m_view.row_range;

	m_view.col_count = m_col_count - col_begin;
	m_view.row_count = row_end - row_begin;
	m_view.col_range = {col_begin, m_col_count};
	m_view.row_range = nrr;

	/*DUCT_DEBUGF(
		"update_view(): fit_count = %3d, row_count = %3d, col_count = %3d,\n"
		"  row_range = {%3d, %3d}, col_range = {%3d, %3d}"
		", orc = %3d"
		", dirty.rows.size = %zu",
		m_view.fit_count, m_view.row_count, m_view.col_count,
		m_view.row_range.x, m_view.row_range.y,
		m_view.col_range.x, m_view.col_range.y,
		orc, m_dirty.rows.size()
	);*/

	if (retain_intersection) {
		Vec2 const v_refresh{-1, -1};
		switch (range_rel(nrr, orr)) {
		case RangeRel::equal:
			// Nothing to do
			break;

		case RangeRel::disjoint_before:
		case RangeRel::disjoint_after:
			std::fill(
				m_dirty.rows.begin(),
				m_dirty.rows.end(),
				v_refresh
			);
			break;

		case RangeRel::subset:
		case RangeRel::intersection_after:
			// fall-through

		case RangeRel::superset:
		case RangeRel::intersection_before:
			auto const head = m_dirty.rows.begin();
			if (nrr.x > orr.x) {
				auto const idx = nrr.x - orr.x;
				auto const amt = min_ce(m_view.row_count, orc - idx);
				std::copy(head + idx, head + idx + amt, head);
				std::fill(head + idx + amt, m_dirty.rows.end(), v_refresh);
			} else if (nrr.x < orr.x) {
				auto const idx = orr.x - nrr.x;
				auto const amt = min_ce(orc, m_view.row_count - idx);
				std::copy_backward(head, head + amt, head + idx + amt);
				std::fill(head, head + amt, v_refresh);
				std::fill(head + idx + amt, m_dirty.rows.end(), v_refresh);
			} else {
				std::fill(
					m_dirty.rows.begin() + m_view.row_count,
					m_dirty.rows.end(),
					v_refresh
				);
			}
			break;
		}
	}
}

void
ProtoGrid::content_action_internal(
	ui::ProtoGrid::ContentAction const action,
	ui::index_type row_begin,
	ui::index_type count
) noexcept {
	if (0 >= count) {
		return;
	}

	row_begin = max_ce(0, row_begin);
	switch (action) {
	case ContentAction::insert_after:
		// Cast insert_after in terms of insert_before
		++row_begin;
		// fall-through

	case ContentAction::insert_before:
	case ContentAction::erase:
		// We only handle these three actions
		break;

	default:
		// Nothing to do for other actions
		return;
	}

	row_begin = min_ce(row_begin, m_row_count);
	auto const row_end = min_ce(row_begin + count, m_row_count);

	RangeRel const rel = range_rel(Vec2{row_begin, row_end}, m_view.row_range);
	bool const not_disjoint = RangeRel::disjoint_after != rel;

	// For both erasure and insertion, queue everything from
	// push_begin to the end of the view.
	// Bound-checked for a tiny bit of optimization (don't need to
	// mark anything outside the view itself)
	auto const push_begin = max_ce(row_begin, m_view.row_range.x);
	if (not_disjoint && push_begin < m_view.row_range.y) {
		std::fill(
			m_dirty.rows.begin() + (push_begin - m_view.row_range.x),
			m_dirty.rows.begin() + m_view.row_count,
			Vec2{-1, -1}
		);
	}

	if (ContentAction::erase == action) {
		// Erasure is bound (row_end is bound to m_row_count)
		set_row_count(m_row_count - (row_end - row_begin));
		// TODO: Shift view up if it contains no rows
	} else {
		// Insertion is unbound
		set_row_count(m_row_count + count);
	}
	if (not_disjoint) {
		update_view(
			m_view.row_range.x,
			m_view.row_range.x + m_view.fit_count,
			m_view.col_range.x,
			m_view.col_range.y,
			true
		);
	}
}

void
ProtoGrid::queue_header_render(
	ui::index_type col_begin,
	ui::index_type col_end
) noexcept {
	if (is_header_enabled()) {
		if (-1 == col_begin) {
			col_end = -1;
			m_dirty.header = {-1, -1};
		} else {
			col_begin = value_clamp(col_begin, m_view.col_range);
			col_end = value_clamp(col_end, col_begin, m_view.col_range.y);
			if (col_begin != col_end) {
				expand_range(m_dirty.header, col_begin, col_end);
			}
		}
	}
}

void
ProtoGrid::queue_cell_render(
	ui::index_type row_begin,
	ui::index_type row_end,
	ui::index_type col_begin,
	ui::index_type col_end
) noexcept {
	// NB: row_begin will be clamped to the view range, which is
	// already clamped to the number of rows. Also, row_begin needn't
	// be clamped to m_row_count because row_end is clamped to that,
	// and the bound comparison is row_end > row.
	if (-1 == col_begin) {
		col_end = -1;
	} else {
		col_begin = value_clamp(col_begin, m_view.col_range);
		col_end = value_clamp(col_end, col_begin, m_view.col_range.y);
		if (col_begin == col_end) {
			return;
		}
	}

	// Make row range relative to view
	row_begin = value_clamp(row_begin - m_view.row_range.x, 0, m_row_count);
	row_end = min_ce(
		max_ce(
			index_type{0},
			min_ce(row_end, m_row_count) - m_view.row_range.x
		),
		m_view.row_count
	);

	for (
		auto row = row_begin;
		row_end > row;
		++row
	) {
		expand_range(m_dirty.rows[row], col_begin, col_end);
	}
}

void
ProtoGrid::reflow_view(
	Rect const& view_frame
) noexcept {
	if (
		m_header_enabled == m_header_enabled_next &&
		view_frame == m_view.frame
	) {
		return;
	}

	m_header_enabled = m_header_enabled_next;

	m_view.frame = view_frame;
	vec2_clamp_min(m_view.frame.size, Vec2{0, 0});
	m_view.content_frame = m_view.frame;
	if (is_header_enabled()) {
		// Clamps here are to avoid sneaking outside the view frame
		m_view.header_frame = m_view.frame;
		m_view.header_frame.size.height = min_ce(
			1,
			m_view.frame.size.height
		);

		m_view.content_frame.pos.y = min_ce(
			m_view.content_frame.pos.y + 1,
			m_view.frame.pos.y + m_view.frame.size.height
		);
		m_view.content_frame.size.height = max_ce(
			0,
			m_view.content_frame.size.height - 1
		);
	} else {
		m_view.header_frame = {{0, 0}, {0, 0}};
	}

	// We want to retain the row range at its beginning, so
	// instead of calculating the intersection with the previous
	// content frame, we're just queuing the entire range
	m_view.fit_count = m_view.content_frame.size.height;
	m_dirty.rows.resize(m_view.fit_count);
	update_view(
		m_view.row_range.x,
		m_view.row_range.x + m_view.fit_count,
		m_view.col_range.x,
		m_view.col_range.y,
		false
	);

	if (is_header_enabled()) {
		m_dirty.header = {-1, -1};
	}
	std::fill(
		m_dirty.rows.begin(),
		m_dirty.rows.end(),
		Vec2{-1, -1}
	);
}

void
ProtoGrid::render_view(
	ui::GridRenderData& grid_rd,
	bool all
) noexcept {
	Vec2 cr = m_view.col_range;
	if (is_header_enabled()) {
		if (!all) {
			cr = m_dirty.header;
			if (-1 == cr.x) {
				cr = m_view.col_range;
			} else {
				cr.x = value_clamp(cr.x, m_view.col_range);
				cr.y = value_clamp(cr.y, cr.x, m_view.col_range.y);
			}
		}
		if (cr.x < cr.y) {
			render_header(grid_rd, cr.x, cr.y, m_view.header_frame);
		}
	}

	Rect frame = m_view.content_frame;
	cr = m_view.col_range;
	if (m_view.row_count == 0 || range_length(m_view.col_range) <= 0) {
		// Do nothing
	} else if (all) {
		frame.size.height = m_view.row_count;
		render_content(
			grid_rd,
			m_view.row_range.x, m_view.row_range.y,
			cr.x, cr.y,
			frame
		);
	} else {
		signed row = 0;
		signed row_end = 0;
		Vec2 cr_queued;
		bool first = true;
		while (row < m_view.row_count) {
			if (row_end == m_view.row_count || m_dirty.rows[row_end].y == 0) {
				first = true;
				all = false;
				if (row == row_end) {
					row = ++row_end;
					continue;
				}
			} else {
				if (!all) {
					cr_queued = m_dirty.rows[row_end];
					if (cr_queued.x == -1) {
						cr = m_view.col_range;
						all = true;
					} else if (first) {
						cr = cr_queued;
						first = false;
					} else {
						cr.x = value_clamp(min_ce(cr.x, cr_queued.x), m_view.col_range);
						cr.y = value_clamp(max_ce(cr.y, cr_queued.y), cr.x, m_view.col_range.y);
						if (range_length(cr) == m_view.col_count) {
							all = true;
						}
					}
				}
				++row_end;
				continue;
			}
			frame.pos.y = m_view.content_frame.pos.y + row;
			frame.size.height = row_end - row;
			render_content(
				grid_rd,
				m_view.row_range.x + row,
				m_view.row_range.x + row_end,
				cr.x, cr.y,
				frame
			);
			std::fill(
				m_dirty.rows.begin() + row,
				m_dirty.rows.begin() + row_end,
				Vec2{0, 0}
			);
			row = ++row_end;
		}
	}
	if (m_view.fit_count > m_view.row_count) {
		// FIXME: Destructive clear
		frame.pos.y = m_view.content_frame.pos.y + m_view.row_count;
		frame.size.height = m_view.fit_count - m_view.row_count;
		grid_rd.rd.terminal.clear_back(frame);
	}
}

} // namespace ui
} // namespace Beard
<commit_msg>ui::ProtoGrid: tidy.<commit_after>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <Beard/ui/Defs.hpp>
#include <Beard/ui/ProtoGrid.hpp>

namespace Beard {
namespace ui {

// class ProtoGrid implementation

ProtoGrid::~ProtoGrid() noexcept = default;

// internals

namespace {
inline void
expand_range(
	Vec2& range,
	ui::index_type const begin,
	ui::index_type const end
) noexcept {
	if (-1 != range.x) {
		if (-1 == begin) {
			range.x = -1;
			range.y = -1;
		} else if (range.x == range.y) {
			range.x = begin;
			range.y = end;
		} else {
			range.x = min_ce(range.x, begin);
			range.y = max_ce(range.y, end);
		}
	}
}
} // anonymous namespace

void
ProtoGrid::update_view(
	ui::index_type row_begin,
	ui::index_type row_end,
	ui::index_type col_begin,
	ui::index_type col_end,
	bool const retain_intersection
) noexcept {
	row_begin = value_clamp(row_begin, 0, m_row_count);
	row_end = min_ce(
		value_clamp(row_end, row_begin, m_row_count),
		row_begin + m_view.fit_count
	);
	col_begin = value_clamp(col_begin, 0, m_col_count);
	col_end = value_clamp(col_end, col_begin, m_col_count);

	Vec2 const nrr{row_begin, row_end};
	auto const orc = m_view.row_count;
	Vec2 const orr = m_view.row_range;

	m_view.col_count = m_col_count - col_begin;
	m_view.row_count = row_end - row_begin;
	m_view.col_range = {col_begin, m_col_count};
	m_view.row_range = nrr;

	/*DUCT_DEBUGF(
		"update_view(): fit_count = %3d, row_count = %3d, col_count = %3d,\n"
		"  row_range = {%3d, %3d}, col_range = {%3d, %3d}"
		", orc = %3d"
		", dirty.rows.size = %zu",
		m_view.fit_count, m_view.row_count, m_view.col_count,
		m_view.row_range.x, m_view.row_range.y,
		m_view.col_range.x, m_view.col_range.y,
		orc, m_dirty.rows.size()
	);*/

	if (retain_intersection) {
		Vec2 const v_refresh{-1, -1};
		switch (range_rel(nrr, orr)) {
		case RangeRel::equal:
			// Nothing to do
			break;

		case RangeRel::disjoint_before:
		case RangeRel::disjoint_after:
			std::fill(
				m_dirty.rows.begin(),
				m_dirty.rows.end(),
				v_refresh
			);
			break;

		case RangeRel::subset:
		case RangeRel::intersection_after:
			// fall-through

		case RangeRel::superset:
		case RangeRel::intersection_before:
			auto const head = m_dirty.rows.begin();
			if (nrr.x > orr.x) {
				auto const idx = nrr.x - orr.x;
				auto const amt = min_ce(m_view.row_count, orc - idx);
				std::copy(head + idx, head + idx + amt, head);
				std::fill(head + idx + amt, m_dirty.rows.end(), v_refresh);
			} else if (nrr.x < orr.x) {
				auto const idx = orr.x - nrr.x;
				auto const amt = min_ce(orc, m_view.row_count - idx);
				std::copy_backward(head, head + amt, head + idx + amt);
				std::fill(head, head + amt, v_refresh);
				std::fill(head + idx + amt, m_dirty.rows.end(), v_refresh);
			} else {
				std::fill(
					m_dirty.rows.begin() + m_view.row_count,
					m_dirty.rows.end(),
					v_refresh
				);
			}
			break;
		}
	}
}

void
ProtoGrid::content_action_internal(
	ui::ProtoGrid::ContentAction const action,
	ui::index_type row_begin,
	ui::index_type count
) noexcept {
	if (0 >= count) {
		return;
	}

	row_begin = max_ce(0, row_begin);
	switch (action) {
	case ContentAction::insert_after:
		// Cast insert_after in terms of insert_before
		++row_begin;
		// fall-through

	case ContentAction::insert_before:
	case ContentAction::erase:
		// We only handle these three actions
		break;

	default:
		// Nothing to do for other actions
		return;
	}

	row_begin = min_ce(row_begin, m_row_count);
	auto const row_end = min_ce(row_begin + count, m_row_count);

	RangeRel const rel = range_rel(Vec2{row_begin, row_end}, m_view.row_range);
	bool const not_disjoint = RangeRel::disjoint_after != rel;

	// For both erasure and insertion, queue everything from
	// push_begin to the end of the view.
	// Bound-checked for a tiny bit of optimization (don't need to
	// mark anything outside the view itself)
	auto const push_begin = max_ce(row_begin, m_view.row_range.x);
	if (not_disjoint && push_begin < m_view.row_range.y) {
		std::fill(
			m_dirty.rows.begin() + (push_begin - m_view.row_range.x),
			m_dirty.rows.begin() + m_view.row_count,
			Vec2{-1, -1}
		);
	}

	if (ContentAction::erase == action) {
		// Erasure is bound (row_end is bound to m_row_count)
		set_row_count(m_row_count - (row_end - row_begin));
		// TODO: Shift view up if it contains no rows
	} else {
		// Insertion is unbound
		set_row_count(m_row_count + count);
	}
	if (not_disjoint) {
		update_view(
			m_view.row_range.x,
			m_view.row_range.x + m_view.fit_count,
			m_view.col_range.x,
			m_view.col_range.y,
			true
		);
	}
}

void
ProtoGrid::queue_header_render(
	ui::index_type col_begin,
	ui::index_type col_end
) noexcept {
	if (is_header_enabled()) {
		if (-1 == col_begin) {
			col_end = -1;
			m_dirty.header = {-1, -1};
		} else {
			col_begin = value_clamp(col_begin, m_view.col_range);
			col_end = value_clamp(col_end, col_begin, m_view.col_range.y);
			if (col_begin != col_end) {
				expand_range(m_dirty.header, col_begin, col_end);
			}
		}
	}
}

void
ProtoGrid::queue_cell_render(
	ui::index_type row_begin,
	ui::index_type row_end,
	ui::index_type col_begin,
	ui::index_type col_end
) noexcept {
	// NB: row_begin will be clamped to the view range, which is
	// already clamped to the number of rows. Also, row_begin needn't
	// be clamped to m_row_count because row_end is clamped to that,
	// and the bound comparison is row_end > row.
	if (-1 == col_begin) {
		col_end = -1;
	} else {
		col_begin = value_clamp(col_begin, m_view.col_range);
		col_end = value_clamp(col_end, col_begin, m_view.col_range.y);
		if (col_begin == col_end) {
			return;
		}
	}

	// Make row range relative to view
	row_begin = value_clamp(row_begin - m_view.row_range.x, 0, m_row_count);
	row_end = min_ce(
		max_ce(
			index_type{0},
			min_ce(row_end, m_row_count) - m_view.row_range.x
		),
		m_view.row_count
	);
	for (auto row = row_begin; row_end > row; ++row) {
		expand_range(m_dirty.rows[row], col_begin, col_end);
	}
}

void
ProtoGrid::reflow_view(
	Rect const& view_frame
) noexcept {
	if (
		m_header_enabled == m_header_enabled_next &&
		view_frame == m_view.frame
	) {
		return;
	}

	m_header_enabled = m_header_enabled_next;

	m_view.frame = view_frame;
	vec2_clamp_min(m_view.frame.size, Vec2{0, 0});
	m_view.content_frame = m_view.frame;
	if (is_header_enabled()) {
		// Clamps here are to avoid sneaking outside the view frame
		m_view.header_frame = m_view.frame;
		m_view.header_frame.size.height = min_ce(
			1,
			m_view.frame.size.height
		);

		m_view.content_frame.pos.y = min_ce(
			m_view.content_frame.pos.y + 1,
			m_view.frame.pos.y + m_view.frame.size.height
		);
		m_view.content_frame.size.height = max_ce(
			0,
			m_view.content_frame.size.height - 1
		);
	} else {
		m_view.header_frame = {{0, 0}, {0, 0}};
	}

	// We want to retain the row range at its beginning, so
	// instead of calculating the intersection with the previous
	// content frame, we're just queuing the entire range
	m_view.fit_count = m_view.content_frame.size.height;
	m_dirty.rows.resize(m_view.fit_count);
	update_view(
		m_view.row_range.x,
		m_view.row_range.x + m_view.fit_count,
		m_view.col_range.x,
		m_view.col_range.y,
		false
	);

	if (is_header_enabled()) {
		m_dirty.header = {-1, -1};
	}
	std::fill(
		m_dirty.rows.begin(),
		m_dirty.rows.end(),
		Vec2{-1, -1}
	);
}

void
ProtoGrid::render_view(
	ui::GridRenderData& grid_rd,
	bool all
) noexcept {
	Vec2 cr = m_view.col_range;
	if (is_header_enabled()) {
		if (!all) {
			cr = m_dirty.header;
			if (-1 == cr.x) {
				cr = m_view.col_range;
			} else {
				cr.x = value_clamp(cr.x, m_view.col_range);
				cr.y = value_clamp(cr.y, cr.x, m_view.col_range.y);
			}
		}
		if (cr.x < cr.y) {
			render_header(grid_rd, cr.x, cr.y, m_view.header_frame);
		}
	}

	Rect frame = m_view.content_frame;
	cr = m_view.col_range;
	if (m_view.row_count == 0 || range_length(m_view.col_range) <= 0) {
		// Do nothing
	} else if (all) {
		frame.size.height = m_view.row_count;
		render_content(
			grid_rd,
			m_view.row_range.x, m_view.row_range.y,
			cr.x, cr.y,
			frame
		);
	} else {
		signed row = 0;
		signed row_end = 0;
		Vec2 cr_queued;
		bool first = true;
		while (row < m_view.row_count) {
			if (row_end == m_view.row_count || m_dirty.rows[row_end].y == 0) {
				first = true;
				all = false;
				if (row == row_end) {
					row = ++row_end;
					continue;
				}
			} else {
				if (!all) {
					cr_queued = m_dirty.rows[row_end];
					if (cr_queued.x == -1) {
						cr = m_view.col_range;
						all = true;
					} else if (first) {
						cr = cr_queued;
						first = false;
					} else {
						cr.x = value_clamp(min_ce(cr.x, cr_queued.x), m_view.col_range);
						cr.y = value_clamp(max_ce(cr.y, cr_queued.y), cr.x, m_view.col_range.y);
						if (range_length(cr) == m_view.col_count) {
							all = true;
						}
					}
				}
				++row_end;
				continue;
			}
			frame.pos.y = m_view.content_frame.pos.y + row;
			frame.size.height = row_end - row;
			render_content(
				grid_rd,
				m_view.row_range.x + row,
				m_view.row_range.x + row_end,
				cr.x, cr.y,
				frame
			);
			std::fill(
				m_dirty.rows.begin() + row,
				m_dirty.rows.begin() + row_end,
				Vec2{0, 0}
			);
			row = ++row_end;
		}
	}
	if (m_view.fit_count > m_view.row_count) {
		// FIXME: Destructive clear
		frame.pos.y = m_view.content_frame.pos.y + m_view.row_count;
		frame.size.height = m_view.fit_count - m_view.row_count;
		grid_rd.rd.terminal.clear_back(frame);
	}
}

} // namespace ui
} // namespace Beard
<|endoftext|>