<commit_before>//..............................................................................
//
//  This file is part of the Doxyrest toolkit.
//
//  Doxyrest is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/doxyrest/license.txt
//
//..............................................................................

#include "pch.h"
#include "CmdLine.h"
#include "DoxyXmlParser.h"
#include "Module.h"
#include "Generator.h"
#include "version.h"

#define _PRINT_USAGE_IF_NO_ARGUMENTS 1
#define _PRINT_MODULE 0

//..............................................................................

void
printVersion ()
{
	printf (
		"doxyrest v%d.%d.%d (%s%s)\n",
		VERSION_MAJOR,
		VERSION_MINOR,
		VERSION_REVISION,
		AXL_CPU_STRING,
		AXL_DEBUG_SUFFIX
		);
}

void
printUsage ()
{
	printVersion ();

	sl::String helpString = CmdLineSwitchTable::getHelpString ();
	printf ("Usage: doxyrest <doxygen-index.xml> <options>...\n%s", helpString.sz ());
}

#if _PRINT_MODULE
inline
void
printIndent (size_t indent)
{
	for (size_t i = 0; i < indent; i++)
		printf ("  ");
}

void
printDocBlock (
	DocBlock const* block,
	size_t indent,
	size_t level
	)
{
	printIndent (indent);

	sl::Iterator <DocBlock> it;

	switch (block->m_blockKind)
	{
	case DocBlockKind_Paragraph:
		if (!block->m_title.isEmpty ())
		{
			printf ("\\paragraph %s\n", block->m_title.sz ());
			printIndent (indent);
		}
		else
		{
			printf ("\\paragraph\n");
			printIndent (indent);
		}

		printf ("%s\n", ((DocParagraphBlock*) block)->m_plainText.sz ());
		break;

	case DocBlockKind_Section:
		if (!block->m_title.isEmpty ())
			printf ("\\sect%d %s\n", level, block->m_title.sz ());
		else
			printf ("\\sect%d\n", level);

		it = ((DocSectionBlock*) block)->m_childBlockList.getHead ();
		for (; it; it++)
			printDocBlock (*it, indent + 1, level + 1);

		break;

	case DocBlockKind_Internal:
		printf ("\\internal\n");

		it = ((DocSectionBlock*) block)->m_childBlockList.getHead ();
		for (; it; it++)
			printDocBlock (*it, indent + 1, level + 1);

		break;
	}

}

void
printDescription (
	Description const* description,
	size_t indent
	)
{
	if (!description->m_title.isEmpty ())
	{
		printIndent (indent);
		printf ("\\title %s\n", description->m_title.sz ());
	}

	sl::Iterator <DocBlock> it = description->m_docBlockList.getHead ();
	for (; it; it++)
		printDocBlock (*it, indent, 1);
}

void
printEnumValue (EnumValue* enumValue)
{
	printf (
		"  enumValue\n"
		"    name:         %s\n"
		"    initializer:  %s\n",

		enumValue->m_name.sz (),
		enumValue->m_initializer.m_plainText.sz ()
		);

	if (!enumValue->m_briefDescription.isEmpty ())
	{
		printf ("    briefDescription\n");
		printDescription (&enumValue->m_briefDescription, 3);
	}

	if (!enumValue->m_detailedDescription.isEmpty ())
	{
		printf ("    detailedDescription\n");
		printDescription (&enumValue->m_detailedDescription, 3);
	}
}

void
printEnumValueList (const sl::ConstList <EnumValue>& list)
{
	sl::Iterator <EnumValue> it = list.getHead ();
	for (; it; it++)
		printEnumValue (*it);
}

void
printParam (Param* param)
{
	printf (
		"  param\n"
		"    declarationName: %s\n"
		"    definitionName:  %s\n"
		"    type:            %s\n"
		"    array:           %s\n"
		"    defaultValue:    %s\n"
		"    typeConstraint:  %s\n",

		param->m_declarationName.sz (),
		param->m_definitionName.sz (),
		param->m_type.m_plainText.sz (),
		param->m_array.sz (),
		param->m_defaultValue.m_plainText.sz (),
		param->m_typeConstraint.m_plainText.sz ()
		);

	if (!param->m_briefDescription.isEmpty ())
	{
		printf ("    briefDescription\n");
		printDescription (&param->m_briefDescription, 3);
	}
}

void
printParamList (const sl::ConstList <Param>& list)
{
	sl::Iterator <Param> it = list.getHead ();
	for (; it; it++)
		printParam (*it);
}

void
printMember(Member* member)
{
	printf (
		"%s %s\n"
		"  id:           %s\n"
		"  type:         %s\n"
		"  definition:   %s\n"
		"  argString:    %s\n"
		"  bitField:     %s\n"
		"  initializer:  %s\n"
		"  exceptions:   %s\n"
		"  flags:        %s\n",

		getMemberKindString (member->m_memberKind),
		member->m_name.sz (),
		member->m_id.sz (),
		member->m_type.m_plainText.sz (),
		member->m_definition.sz (),
		member->m_argString.sz (),
		member->m_bitField.sz (),
		member->m_initializer.m_plainText.sz (),
		member->m_exceptions.m_plainText.sz (),
		getProtectionKindString (member->m_protectionKind),
		getVirtualKindString (member->m_virtualKind),
		getMemberFlagString (member->m_flags).sz ()
		);

	if (!member->m_briefDescription.isEmpty ())
	{
		printf ("  briefDescription\n");
		printDescription (&member->m_briefDescription, 2);
	}

	if (!member->m_detailedDescription.isEmpty ())
	{
		printf ("  detailedDescription\n");
		printDescription (&member->m_detailedDescription, 2);
	}

	if (!member->m_detailedDescription.isEmpty ())
	{
		printf ("  inBodyDescription\n");
		printDescription (&member->m_inBodyDescription, 2);
	}

	if (member->m_memberKind == MemberKind_Enum)
	{
		printf ("  enumMembers {\n");

		sl::Iterator <EnumValue> it = member->m_enumValueList.getHead ();
		for (; it; it++)
			printEnumValue (*it);

		printf ("  }\n");
	}

	if (!member->m_templateParamList.isEmpty ())
	{
		printf ("  templateParamList <\n");
		printParamList (member->m_templateParamList);
		printf ("  >\n");
	}

	if (!member->m_paramList.isEmpty ())
	{
		printf ("  paramList (\n");
		printParamList (member->m_paramList);
		printf ("  )\n");
	}
}

void
printMemberList (const sl::ConstList <Member>& list)
{
	sl::Iterator <Member> it = list.getHead ();
	for (; it; it++)
		printMember (*it);
}

void
printMemberArray (const sl::Array <Member*>& array)
{
	size_t count = array.getCount ();
	for (size_t i = 0; i < count; i++)
		printMember (array [i]);
}

void
printCompound (Compound* compound)
{
	printf (
		"%s %s\n"
		"  id:         %s\n"
		"  title:      %s\n"
		"  language:   %s\n"
		"  protection: %s\n"
		"  isFinal:    %s\n"
		"  isSealed:   %s\n"
		"  isAbstract: %s\n",

		getCompoundKindString (compound->m_compoundKind),
		compound->m_name.sz (),
		compound->m_id.sz (),
		compound->m_title.sz (),
		getLanguageKindString (compound->m_languageKind),
		getProtectionKindString (compound->m_protectionKind),
		compound->m_isFinal ? "yes" : "no",
		compound->m_isSealed ? "yes" : "no",
		compound->m_isAbstract ? "yes" : "no"
		);

	if (!compound->m_briefDescription.isEmpty ())
	{
		printf ("  briefDescription\n");
		printDescription (&compound->m_briefDescription, 2);
	}

	if (!compound->m_detailedDescription.isEmpty ())
	{
		printf ("  detailedDescription\n");
		printDescription (&compound->m_detailedDescription, 2);
	}

	sl::Iterator <Member> it = compound->m_memberList.getHead ();
	for (; it; it++)
		printMember (*it);

	printf ("\n");
}

void
printNamespaceContents (NamespaceContents* nspace);

void
printNamespaceArray (const sl::Array <Namespace*>& array)
{
	size_t count = array.getCount ();
	for (size_t i = 0; i < count; i++)
	{
		Namespace* nspace = array [i];

		printf ("namespace %s {\n", nspace->m_compound->m_name.sz ());
		printNamespaceContents (nspace);
		printf ("} // namespace %s {\n", nspace->m_compound->m_name.sz ());
	}
}

void
printNamespaceContents (NamespaceContents* nspace)
{
	if (!nspace->m_namespaceArray.isEmpty ())
	{
		printf ("NAMESPACES\n");
		printNamespaceArray (nspace->m_namespaceArray);
	}

	if (!nspace->m_enumArray.isEmpty ())
	{
		printf ("ENUMS\n");
		printMemberArray (nspace->m_enumArray);
	}

	if (!nspace->m_structArray.isEmpty ())
	{
		printf ("STRUCTS\n");
		printNamespaceArray (nspace->m_structArray);
	}

	if (!nspace->m_unionArray.isEmpty ())
	{
		printf ("UNIONS\n");
		printNamespaceArray (nspace->m_unionArray);
	}

	if (!nspace->m_classArray.isEmpty ())
	{
		printf ("CLASSES\n");
		printNamespaceArray (nspace->m_classArray);
	}

	if (!nspace->m_typedefArray.isEmpty ())
	{
		printf ("TYPEDEFS\n");
		printMemberArray (nspace->m_typedefArray);
	}

	if (!nspace->m_variableArray.isEmpty ())
	{
		printf ("VARIABLES\n");
		printMemberArray (nspace->m_variableArray);
	}

	if (!nspace->m_functionArray.isEmpty ())
	{
		printf ("FUNCTIONS\n");
		printMemberArray (nspace->m_functionArray);
	}

	if (!nspace->m_propertyArray.isEmpty ())
	{
		printf ("PROPERTIES\n");
		printMemberArray (nspace->m_propertyArray);
	}

	if (!nspace->m_eventArray.isEmpty ())
	{
		printf ("EVENTS\n");
		printMemberArray (nspace->m_eventArray);
	}

	if (!nspace->m_aliasArray.isEmpty ())
	{
		printf ("ALIASES\n");
		printMemberArray (nspace->m_aliasArray);
	}
}
#endif

int
run (CmdLine* cmdLine)
{
	bool result;

	Module module;
	GlobalNamespace globalNamespace;
	DoxyXmlParser parser;
	Generator generator (cmdLine);

	printf ("parsing...\n");

	result =
		parser.parseFile (&module, cmdLine->m_inputFileName) &&
		globalNamespace.build (&module, cmdLine->m_protectionFilter);

	if (!result)
	{
		printf ("error: %s\n", err::getLastErrorDescription ().sz ());
		return -1;
	}

	printf ("generating...\n");

	result = generator.generate (
		&module,
		&globalNamespace,
		cmdLine->m_outputFileName,
		cmdLine->m_frameFileName
		);

	if (!result)
	{
		printf ("error: %s\n", err::getLastErrorDescription ().sz ());
		return -1;
	}

#if _PRINT_MODULE
	printf ("namespace :: {\n");
	printNamespaceContents (&globalNamespace);
	printf ("} // namespace :: {\n");
#endif

	return 0;
}

//..............................................................................

#if (_AXL_OS_WIN)
int
wmain (
	int argc,
	wchar_t* argv []
	)
#else
int
main (
	int argc,
	char* argv []
	)
#endif
{
	int result;

	xml::registerExpatErrorProvider ();
	lex::registerParseErrorProvider ();

	CmdLine cmdLine;
	CmdLineParser parser (&cmdLine);

#if _PRINT_USAGE_IF_NO_ARGUMENTS
	if (argc < 2)
	{
		printUsage ();
		return 0;
	}
#endif

	result = parser.parse (argc, argv);
	if (!result)
	{
		printf ("error parsing command line: %s\n", err::getLastErrorDescription ().sz ());
		return -1;
	}

	result = 0;

	if (cmdLine.m_flags & CmdLineFlag_Help)
		printUsage ();
	else if (cmdLine.m_flags & CmdLineFlag_Version)
		printVersion ();
	else
		result = run (&cmdLine);

	return result;
}

//..............................................................................
<commit_msg>[doxyrest] set axl tag<commit_after>//..............................................................................
//
//  This file is part of the Doxyrest toolkit.
//
//  Doxyrest is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/doxyrest/license.txt
//
//..............................................................................

#include "pch.h"
#include "CmdLine.h"
#include "DoxyXmlParser.h"
#include "Module.h"
#include "Generator.h"
#include "version.h"

#define _PRINT_USAGE_IF_NO_ARGUMENTS 1
#define _PRINT_MODULE 0

//..............................................................................

void
printVersion ()
{
	printf (
		"doxyrest v%d.%d.%d (%s%s)\n",
		VERSION_MAJOR,
		VERSION_MINOR,
		VERSION_REVISION,
		AXL_CPU_STRING,
		AXL_DEBUG_SUFFIX
		);
}

void
printUsage ()
{
	printVersion ();

	sl::String helpString = CmdLineSwitchTable::getHelpString ();
	printf ("Usage: doxyrest <doxygen-index.xml> <options>...\n%s", helpString.sz ());
}

#if _PRINT_MODULE
inline
void
printIndent (size_t indent)
{
	for (size_t i = 0; i < indent; i++)
		printf ("  ");
}

void
printDocBlock (
	DocBlock const* block,
	size_t indent,
	size_t level
	)
{
	printIndent (indent);

	sl::Iterator <DocBlock> it;

	switch (block->m_blockKind)
	{
	case DocBlockKind_Paragraph:
		if (!block->m_title.isEmpty ())
		{
			printf ("\\paragraph %s\n", block->m_title.sz ());
			printIndent (indent);
		}
		else
		{
			printf ("\\paragraph\n");
			printIndent (indent);
		}

		printf ("%s\n", ((DocParagraphBlock*) block)->m_plainText.sz ());
		break;

	case DocBlockKind_Section:
		if (!block->m_title.isEmpty ())
			printf ("\\sect%d %s\n", level, block->m_title.sz ());
		else
			printf ("\\sect%d\n", level);

		it = ((DocSectionBlock*) block)->m_childBlockList.getHead ();
		for (; it; it++)
			printDocBlock (*it, indent + 1, level + 1);

		break;

	case DocBlockKind_Internal:
		printf ("\\internal\n");

		it = ((DocSectionBlock*) block)->m_childBlockList.getHead ();
		for (; it; it++)
			printDocBlock (*it, indent + 1, level + 1);

		break;
	}

}

void
printDescription (
	Description const* description,
	size_t indent
	)
{
	if (!description->m_title.isEmpty ())
	{
		printIndent (indent);
		printf ("\\title %s\n", description->m_title.sz ());
	}

	sl::Iterator <DocBlock> it = description->m_docBlockList.getHead ();
	for (; it; it++)
		printDocBlock (*it, indent, 1);
}

void
printEnumValue (EnumValue* enumValue)
{
	printf (
		"  enumValue\n"
		"    name:         %s\n"
		"    initializer:  %s\n",

		enumValue->m_name.sz (),
		enumValue->m_initializer.m_plainText.sz ()
		);

	if (!enumValue->m_briefDescription.isEmpty ())
	{
		printf ("    briefDescription\n");
		printDescription (&enumValue->m_briefDescription, 3);
	}

	if (!enumValue->m_detailedDescription.isEmpty ())
	{
		printf ("    detailedDescription\n");
		printDescription (&enumValue->m_detailedDescription, 3);
	}
}

void
printEnumValueList (const sl::ConstList <EnumValue>& list)
{
	sl::Iterator <EnumValue> it = list.getHead ();
	for (; it; it++)
		printEnumValue (*it);
}

void
printParam (Param* param)
{
	printf (
		"  param\n"
		"    declarationName: %s\n"
		"    definitionName:  %s\n"
		"    type:            %s\n"
		"    array:           %s\n"
		"    defaultValue:    %s\n"
		"    typeConstraint:  %s\n",

		param->m_declarationName.sz (),
		param->m_definitionName.sz (),
		param->m_type.m_plainText.sz (),
		param->m_array.sz (),
		param->m_defaultValue.m_plainText.sz (),
		param->m_typeConstraint.m_plainText.sz ()
		);

	if (!param->m_briefDescription.isEmpty ())
	{
		printf ("    briefDescription\n");
		printDescription (&param->m_briefDescription, 3);
	}
}

void
printParamList (const sl::ConstList <Param>& list)
{
	sl::Iterator <Param> it = list.getHead ();
	for (; it; it++)
		printParam (*it);
}

void
printMember(Member* member)
{
	printf (
		"%s %s\n"
		"  id:           %s\n"
		"  type:         %s\n"
		"  definition:   %s\n"
		"  argString:    %s\n"
		"  bitField:     %s\n"
		"  initializer:  %s\n"
		"  exceptions:   %s\n"
		"  flags:        %s\n",

		getMemberKindString (member->m_memberKind),
		member->m_name.sz (),
		member->m_id.sz (),
		member->m_type.m_plainText.sz (),
		member->m_definition.sz (),
		member->m_argString.sz (),
		member->m_bitField.sz (),
		member->m_initializer.m_plainText.sz (),
		member->m_exceptions.m_plainText.sz (),
		getProtectionKindString (member->m_protectionKind),
		getVirtualKindString (member->m_virtualKind),
		getMemberFlagString (member->m_flags).sz ()
		);

	if (!member->m_briefDescription.isEmpty ())
	{
		printf ("  briefDescription\n");
		printDescription (&member->m_briefDescription, 2);
	}

	if (!member->m_detailedDescription.isEmpty ())
	{
		printf ("  detailedDescription\n");
		printDescription (&member->m_detailedDescription, 2);
	}

	if (!member->m_detailedDescription.isEmpty ())
	{
		printf ("  inBodyDescription\n");
		printDescription (&member->m_inBodyDescription, 2);
	}

	if (member->m_memberKind == MemberKind_Enum)
	{
		printf ("  enumMembers {\n");

		sl::Iterator <EnumValue> it = member->m_enumValueList.getHead ();
		for (; it; it++)
			printEnumValue (*it);

		printf ("  }\n");
	}

	if (!member->m_templateParamList.isEmpty ())
	{
		printf ("  templateParamList <\n");
		printParamList (member->m_templateParamList);
		printf ("  >\n");
	}

	if (!member->m_paramList.isEmpty ())
	{
		printf ("  paramList (\n");
		printParamList (member->m_paramList);
		printf ("  )\n");
	}
}

void
printMemberList (const sl::ConstList <Member>& list)
{
	sl::Iterator <Member> it = list.getHead ();
	for (; it; it++)
		printMember (*it);
}

void
printMemberArray (const sl::Array <Member*>& array)
{
	size_t count = array.getCount ();
	for (size_t i = 0; i < count; i++)
		printMember (array [i]);
}

void
printCompound (Compound* compound)
{
	printf (
		"%s %s\n"
		"  id:         %s\n"
		"  title:      %s\n"
		"  language:   %s\n"
		"  protection: %s\n"
		"  isFinal:    %s\n"
		"  isSealed:   %s\n"
		"  isAbstract: %s\n",

		getCompoundKindString (compound->m_compoundKind),
		compound->m_name.sz (),
		compound->m_id.sz (),
		compound->m_title.sz (),
		getLanguageKindString (compound->m_languageKind),
		getProtectionKindString (compound->m_protectionKind),
		compound->m_isFinal ? "yes" : "no",
		compound->m_isSealed ? "yes" : "no",
		compound->m_isAbstract ? "yes" : "no"
		);

	if (!compound->m_briefDescription.isEmpty ())
	{
		printf ("  briefDescription\n");
		printDescription (&compound->m_briefDescription, 2);
	}

	if (!compound->m_detailedDescription.isEmpty ())
	{
		printf ("  detailedDescription\n");
		printDescription (&compound->m_detailedDescription, 2);
	}

	sl::Iterator <Member> it = compound->m_memberList.getHead ();
	for (; it; it++)
		printMember (*it);

	printf ("\n");
}

void
printNamespaceContents (NamespaceContents* nspace);

void
printNamespaceArray (const sl::Array <Namespace*>& array)
{
	size_t count = array.getCount ();
	for (size_t i = 0; i < count; i++)
	{
		Namespace* nspace = array [i];

		printf ("namespace %s {\n", nspace->m_compound->m_name.sz ());
		printNamespaceContents (nspace);
		printf ("} // namespace %s {\n", nspace->m_compound->m_name.sz ());
	}
}

void
printNamespaceContents (NamespaceContents* nspace)
{
	if (!nspace->m_namespaceArray.isEmpty ())
	{
		printf ("NAMESPACES\n");
		printNamespaceArray (nspace->m_namespaceArray);
	}

	if (!nspace->m_enumArray.isEmpty ())
	{
		printf ("ENUMS\n");
		printMemberArray (nspace->m_enumArray);
	}

	if (!nspace->m_structArray.isEmpty ())
	{
		printf ("STRUCTS\n");
		printNamespaceArray (nspace->m_structArray);
	}

	if (!nspace->m_unionArray.isEmpty ())
	{
		printf ("UNIONS\n");
		printNamespaceArray (nspace->m_unionArray);
	}

	if (!nspace->m_classArray.isEmpty ())
	{
		printf ("CLASSES\n");
		printNamespaceArray (nspace->m_classArray);
	}

	if (!nspace->m_typedefArray.isEmpty ())
	{
		printf ("TYPEDEFS\n");
		printMemberArray (nspace->m_typedefArray);
	}

	if (!nspace->m_variableArray.isEmpty ())
	{
		printf ("VARIABLES\n");
		printMemberArray (nspace->m_variableArray);
	}

	if (!nspace->m_functionArray.isEmpty ())
	{
		printf ("FUNCTIONS\n");
		printMemberArray (nspace->m_functionArray);
	}

	if (!nspace->m_propertyArray.isEmpty ())
	{
		printf ("PROPERTIES\n");
		printMemberArray (nspace->m_propertyArray);
	}

	if (!nspace->m_eventArray.isEmpty ())
	{
		printf ("EVENTS\n");
		printMemberArray (nspace->m_eventArray);
	}

	if (!nspace->m_aliasArray.isEmpty ())
	{
		printf ("ALIASES\n");
		printMemberArray (nspace->m_aliasArray);
	}
}
#endif

int
run (CmdLine* cmdLine)
{
	bool result;

	Module module;
	GlobalNamespace globalNamespace;
	DoxyXmlParser parser;
	Generator generator (cmdLine);

	printf ("parsing...\n");

	result =
		parser.parseFile (&module, cmdLine->m_inputFileName) &&
		globalNamespace.build (&module, cmdLine->m_protectionFilter);

	if (!result)
	{
		printf ("error: %s\n", err::getLastErrorDescription ().sz ());
		return -1;
	}

	printf ("generating...\n");

	result = generator.generate (
		&module,
		&globalNamespace,
		cmdLine->m_outputFileName,
		cmdLine->m_frameFileName
		);

	if (!result)
	{
		printf ("error: %s\n", err::getLastErrorDescription ().sz ());
		return -1;
	}

#if _PRINT_MODULE
	printf ("namespace :: {\n");
	printNamespaceContents (&globalNamespace);
	printf ("} // namespace :: {\n");
#endif

	return 0;
}

//..............................................................................

#if (_AXL_OS_WIN)
int
wmain (
	int argc,
	wchar_t* argv []
	)
#else
int
main (
	int argc,
	char* argv []
	)
#endif
{
	int result;

	g::getModule ()->setTag ("doxyrest");
	xml::registerExpatErrorProvider ();
	lex::registerParseErrorProvider ();

	CmdLine cmdLine;
	CmdLineParser parser (&cmdLine);

#if _PRINT_USAGE_IF_NO_ARGUMENTS
	if (argc < 2)
	{
		printUsage ();
		return 0;
	}
#endif

	result = parser.parse (argc, argv);
	if (!result)
	{
		printf ("error parsing command line: %s\n", err::getLastErrorDescription ().sz ());
		return -1;
	}

	result = 0;

	if (cmdLine.m_flags & CmdLineFlag_Help)
		printUsage ();
	else if (cmdLine.m_flags & CmdLineFlag_Version)
		printVersion ();
	else
		result = run (&cmdLine);

	return result;
}

//..............................................................................
<|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <utility> // std::pair<T,U>
#include <pthread.h>
#include <algorithm>
#include <cmath>

#include "utils.hpp"

int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones);
void* does_work(void *ptr);

//////global
int problemSize =0;
//int threadCount = 24;
std::vector<std::vector<int> > results;
std::vector<int> wholeCost;
std::vector< std::vector<int> > Distance;
std::vector<std::vector<double> > Pher;
//std::vector

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		std::cerr << "I needs a file dammit!" << std::endl;
		return 1;
	}
	// well what now?
	// something about an algorithm...
	// oh yes! i think i need to build the distance and pheromones array
	// call shortest path with itthr_count
	// then print out the answer

	std::string fileName(argv[1]);

	std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector
	std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector
	problemSize = (dist.size() * dist[0].size())/2;
	for(int i =0; i < ANTCOUNT; i++)
	{
		std::vector<int> temp;
		results.push_back(temp);
		wholeCost.push_back(0);
	}

	// start time
	int answer = shortest_path_dist(dist, pheromones);
	// end time

	std::cout << answer << std::endl;
}

// this algorithm has a structure similar to floyds
// so look there for inspiration
// note: a thread pool is the sort of thing desired
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones)
{

  std::vector<pthread_t> cur;

	for(int i = 0; i < GENERATIONS; i++)
	{

		for(int i = 0;i < ANTCOUNT; i++)
		{
			int * ii = new int(i);
			pthread_t temp;
			pthread_create(&temp, NULL, does_work,(void*)ii);
			cur.push_back(temp);
		}

		while(!cur.empty())
		{
			pthread_join(cur.back(),NULL);
			cur.pop_back();
		}
		cur.clear();

		//global update

		for(int i =0; i < cur.size();i++)
		  cur[i] = 0;

	}
	// start all needed threads
	// for each iteration
		// for each ant : IN PARALLEL
			// initialize the ant
			// share distance and pheromone graph for the thread
			// while a tour is not finished
				// choose the next city (eq 1,2)
				// atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without
			// end while // end of ant's travel
			// atomic: global pheromone update (eq 4)
			// terminate the thread, release resources
		//}
		// barrier: all ants
	//} // end of iteration
}

void *does_work(void *ptr)
{
  int pos = 0;
  int antDist = 0;
  int id = *((int *)ptr);
  //std::vector<double> res;
  std::vector<int> history;

  while(history.size() < problemSize)
  {
    //res.clear();
    //for(int i =0;i < problemSize; i++)
    //{
    //	res.push_back(0.0);
    //}

    double choice = ((double) rand() / (RAND_MAX)) + 1;

    double max = 0;
    int maxIndex =0;

    if(choice < Q0){

      // expliait
      for(int i =0; i< problemSize; i++)
      {
	if(std::find(history.begin(), history.end(), i) != history.end())
	  continue;
	double temp = Pher[pos][i] / pow(Distance[pos][i],BETA) ;
	if( temp > max)
	{
	  max =temp;
	  maxIndex = i;
	}
      }

    }
    else //we expolore
    {

    }

    Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize);
    antDist += Distance[pos][maxIndex];
    pos = maxIndex;
    history.push_back(maxIndex);

  }

  results[id] = history;
  wholeCost[id] = antDist;

}

<commit_msg>I does work....<commit_after>#include <vector>
#include <iostream>
#include <utility> // std::pair<T,U>
#include <pthread.h>
#include <algorithm>
#include <cmath>

#include "utils.hpp"

int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones);
void* does_work(void *ptr);

//////global
int problemSize =0;
//int threadCount = 24;
std::vector<std::vector<int> > results;
std::vector<int> wholeCost;
std::vector< std::vector<int> > Distance;
std::vector<std::vector<double> > Pher;
std::vector<int> Locations;

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		std::cerr << "I needs a file dammit!" << std::endl;
		return 1;
	}
	// well what now?
	// something about an algorithm...
	// oh yes! i think i need to build the distance and pheromones array
	// call shortest path with itthr_count
	// then print out the answer

	std::string fileName(argv[1]);

	std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector
	std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector
	problemSize = (dist.size() * dist[0].size())/2;
	for(int i =0; i < ANTCOUNT; i++)
	{
		std::vector<int> temp;
		Locations.push_back(i);
		results.push_back(temp);
		wholeCost.push_back(0);
	}

	// start time
	int answer = shortest_path_dist(dist, pheromones);
	// end time

	std::cout << answer << std::endl;
}

// this algorithm has a structure similar to floyds
// so look there for inspiration
// note: a thread pool is the sort of thing desired
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones)
{

  std::vector<pthread_t> cur;

	for(int i = 0; i < GENERATIONS; i++)
	{

		for(int i = 0;i < ANTCOUNT; i++)
		{
			int * ii = new int(i);
			pthread_t temp;
			pthread_create(&temp, NULL, does_work,(void*)ii);
			cur.push_back(temp);
		}

		while(!cur.empty())
		{
			pthread_join(cur.back(),NULL);
			cur.pop_back();
		}
		cur.clear();

		//global update

		for(int i =0; i < cur.size();i++)
		  cur[i] = 0;

	}
	// start all needed threads
	// for each iteration
		// for each ant : IN PARALLEL
			// initialize the ant
			// share distance and pheromone graph for the thread
			// while a tour is not finished
				// choose the next city (eq 1,2)
				// atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without
			// end while // end of ant's travel
			// atomic: global pheromone update (eq 4)
			// terminate the thread, release resources
		//}
		// barrier: all ants
	//} // end of iteration
}

void *does_work(void *ptr)
{
  int pos = 0;
  int antDist = 0;
  int id = *((int *)ptr);
  //std::vector<double> res;
  std::vector<int> history;
  std::vector<int> unvisited = Locations;

  while(history.size() < problemSize)
  {
    //res.clear();
    //for(int i =0;i < problemSize; i++)
    //{
    //	res.push_back(0.0);
    //}

    double choice = ((double) rand() / (RAND_MAX)) + 1;

    double choice2 = ((double) rand() / (RAND_MAX)) + 1;

    double max = 0;
    int maxIndex =0;

    if(choice < Q0){

      // expliait
      for(int i =0; i< problemSize; i++)
      {
	if(std::find(history.begin(), history.end(), i) != history.end())
	  continue;

	double temp = Pher[pos][i] / pow(Distance[pos][i], BETA) ;

	if( temp > max)
	{
	  max =temp;
	  maxIndex = i;
	}
      }
    }
    else //we expolore
    {
	  std::vector cho = eq2(Distance, Pher, unvisited, pos);

	  maxIndex = eq2_helper(cho,choice2);
	  max = Pher[pos][maxIndex] / pow(Distance[pos][maxIndex], BETA);
    }

    Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize);
    antDist += Distance[pos][maxIndex];
    pos = maxIndex;
    history.push_back(maxIndex);
    int temp = std::find(unvisited.begin(),unvisited.end(),maxIndex);
    unvisited.erase(unvisited.begin() + temp);
  }

  results[id] = history;
  wholeCost[id] = antDist;

}

<|endoftext|>


<commit_before>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QStatusBar>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QIODevice>
#include <QtGui/QPalette>
#include <QtGui/QColor>
#include <QtGui/QGuiApplication>
#include <QtGui/QClipboard>

#include "dwr.h"
#include "main-window.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    this->mainWidget = new QWidget();
    this->setCentralWidget(this->mainWidget);

    this->initWidgets();
    this->initStatus();
    this->layout();
    this->initSlots();
    this->loadConfig();
}

void MainWindow::initStatus() {
    QStatusBar *status = this->statusBar();
    status->showMessage("Ready");
    QPalette palette = this->palette();
    palette.setColor(QPalette::Background, Qt::lightGray);
    palette.setColor(QPalette::Foreground, Qt::black);
    status->setPalette(palette);
    status->setAutoFillBackground(true);
}

void MainWindow::initWidgets()
{
    this->romFile = new FileEntry(this);
    this->outputDir = new DirEntry(this);
    this->seed = new SeedEntry(this);
    this->flags = new FlagEntry(this);

    chests =        new CheckBox('C', "Shuffle Chests && Search Items", this);
    shops =         new CheckBox('W', "Randomize Weapon Shops", this);
    deathNecklace = new CheckBox('D', "Enable Death Necklace", this);
    speedHacks =    new CheckBox('H', "Enable Speed Hacks", this);
    growth =        new CheckBox('G', "Randomize Growth", this);
    spells =        new CheckBox('M', "Randomize Spell Learning", this);
    attack =        new CheckBox('P', "Randomize Enemy Attacks", this);
    zones =         new CheckBox('Z', "Randomize Zones", this);
    musicShuffle =  new CheckBox('K', "Shuffle Music", this);
    musicDisable =  new CheckBox('Q', "Disable Music", this);
    copyChecksum =  new CheckBox(NO_FLAG, "Copy Checksum to Clipboard", this);

    this->levelSpeed = new LevelComboBox(this);

    this->goButton = new QPushButton("Randomize!", this);
}

void MainWindow::initSlots()
{
    connect(this->flags, SIGNAL(textEdited(QString)), this, SLOT(handleFlags()));

    connect(this->chests,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->shops,        SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->deathNecklace,SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->speedHacks,   SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->growth,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->spells,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->attack,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->zones,        SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->musicShuffle, SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->musicDisable, SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->copyChecksum, SIGNAL(clicked()), this, SLOT(handleCheckBox()));

    connect(this->levelSpeed, SIGNAL(activated(int)),
            this, SLOT(handleCheckBox()));

    connect(this->goButton,     SIGNAL(clicked()), this, SLOT(handleButton()));
}

void MainWindow::layout()
{
    QVBoxLayout *vbox;
    QGridLayout *grid;

    vbox = new QVBoxLayout();
    grid = new QGridLayout();

    grid->addWidget(this->romFile,   0, 0, 0);
    grid->addWidget(this->outputDir, 0, 1, 0);
    grid->addWidget(this->seed,      1, 0, 0);
    grid->addWidget(this->flags,     1, 1, 0);

    vbox->addLayout(grid);
    grid = new QGridLayout();
    vbox->addLayout(grid);

    grid->addWidget(this->chests,        0, 0, 0);
    grid->addWidget(this->shops,         1, 0, 0);
    grid->addWidget(this->zones,         2, 0, 0);

    grid->addWidget(this->growth,        0, 1, 0);
    grid->addWidget(this->spells,        1, 1, 0);
    grid->addWidget(this->attack,        2, 1, 0);
    grid->addWidget(this->copyChecksum,  3, 1, 0);

    grid->addWidget(this->deathNecklace, 0, 2, 0);
    grid->addWidget(this->speedHacks,    1, 2, 0);
    grid->addWidget(this->musicShuffle,  2, 2, 0);
    grid->addWidget(this->musicDisable,  3, 2, 0);

    grid->addWidget(new QLabel("Leveling Speed", this), 6, 0, 0);
    grid->addWidget(this->levelSpeed,    7, 0, 0);

    grid->addWidget(this->goButton,      8, 2, 0);

    this->mainWidget->setLayout(vbox);

    this->copyChecksum->hide();
}

QString MainWindow::getOptions()
{
    std::string flags = std::string() +
                        this->chests->getFlag() +
                        this->shops->getFlag() +
                        this->deathNecklace->getFlag() +
                        this->speedHacks->getFlag() +
                        this->growth->getFlag() +
                        this->spells->getFlag() +
                        this->attack->getFlag() +
                        this->zones->getFlag() +
                        this->musicShuffle->getFlag() +
                        this->musicDisable->getFlag() +
                        this->copyChecksum->getFlag() +

                        this->levelSpeed->getFlag();

    std::sort(flags.begin(), flags.end());
    std::replace(flags.begin(), flags.end(), NO_FLAG, '\0');
    return QString(flags.c_str());
}

void MainWindow::setOptions(QString flags)
{
    this->chests->updateState(flags);
    this->shops->updateState(flags);
    this->deathNecklace->updateState(flags);
    this->speedHacks->updateState(flags);
    this->growth->updateState(flags);
    this->spells->updateState(flags);
    this->attack->updateState(flags);
    this->zones->updateState(flags);
    this->musicShuffle->updateState(flags);
    this->musicDisable->updateState(flags);
    this->copyChecksum->updateState(flags);

    this->levelSpeed->updateState(flags);
}

QString MainWindow::getFlags()
{
    std::string flags = this->flags->text().toStdString();
    std::sort(flags.begin(), flags.end());
    return QString::fromStdString(flags);
}

void MainWindow::setFlags(QString flags)
{
    this->flags->setText(flags);
}

void MainWindow::handleCheckBox()
{
    QString flags = this->getOptions();
    this->setFlags(flags);
}

void MainWindow::handleComboBox(int index)
{
    this->handleCheckBox();
}

void MainWindow::handleFlags()
{
    QString flags = this->getFlags();
    this->setOptions(flags);
}

void MainWindow::handleButton()
{
    char flags[64], checksum[64];
    QString flagStr = this->getFlags();
    strncpy(flags, flagStr.toLatin1().constData(), 64);

    uint64_t seed = this->seed->getSeed();
    std::string inputFile = this->romFile->text().toLatin1().constData();
    std::string outputDir = this->outputDir->text().toLatin1().constData();
    uint64_t crc = dwr_randomize(inputFile.c_str(), seed,
                                 flags, outputDir.c_str());
    if (crc) {
        sprintf(checksum, "Checksum: %016" PRIx64, crc);
        QGuiApplication::clipboard()->setText(checksum);
        this->statusBar()->showMessage("Checksum copied to clipboard", 3000);
        QMessageBox::information(this, "Success!",
                                 "The new ROM has been created.");
    } else {
        QMessageBox::critical(this, "Failed", "An error occurred and"
                "the ROM could not be created.");
    }
    this->saveConfig();
}

bool MainWindow::saveConfig()
{
    QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf");
    if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        printf("Failed to save configuration.\n");
        return false;
    }
    QTextStream out(&configFile);

    out << this->romFile->text() << endl;
    out << this->outputDir->text() << endl;
    out << this->getFlags() << endl;

    return true;
}

bool MainWindow::loadConfig()
{
    char tmp[1024];
    qint64 read;
    QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf");
    if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        printf("Failed to load configuration.\n");
        return false;
    }
    read = configFile.readLine(tmp, 1024);
    tmp[read - 1] = '\0';
    this->romFile->setText(tmp);
    if (configFile.atEnd()) {
        return false;
    }

    read = configFile.readLine(tmp, 1024);
    tmp[read - 1] = '\0';
    this->outputDir->setText(tmp);
    if (configFile.atEnd()) {
        return false;
    }

    read = configFile.readLine(tmp, 1024);
    tmp[read - 1] = '\0';
    this->setFlags(tmp);
    this->setOptions(tmp);

    return true;
}
<commit_msg>Config directory is now created if missing<commit_after>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QStatusBar>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QIODevice>
#include <QtGui/QPalette>
#include <QtGui/QColor>
#include <QtGui/QGuiApplication>
#include <QtGui/QClipboard>

#include "dwr.h"
#include "main-window.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    this->mainWidget = new QWidget();
    this->setCentralWidget(this->mainWidget);

    this->initWidgets();
    this->initStatus();
    this->layout();
    this->initSlots();
    this->loadConfig();
}

void MainWindow::initStatus() {
    QStatusBar *status = this->statusBar();
    status->showMessage("Ready");
    QPalette palette = this->palette();
    palette.setColor(QPalette::Background, Qt::lightGray);
    palette.setColor(QPalette::Foreground, Qt::black);
    status->setPalette(palette);
    status->setAutoFillBackground(true);
}

void MainWindow::initWidgets()
{
    this->romFile = new FileEntry(this);
    this->outputDir = new DirEntry(this);
    this->seed = new SeedEntry(this);
    this->flags = new FlagEntry(this);

    chests =        new CheckBox('C', "Shuffle Chests && Search Items", this);
    shops =         new CheckBox('W', "Randomize Weapon Shops", this);
    deathNecklace = new CheckBox('D', "Enable Death Necklace", this);
    speedHacks =    new CheckBox('H', "Enable Speed Hacks", this);
    growth =        new CheckBox('G', "Randomize Growth", this);
    spells =        new CheckBox('M', "Randomize Spell Learning", this);
    attack =        new CheckBox('P', "Randomize Enemy Attacks", this);
    zones =         new CheckBox('Z', "Randomize Zones", this);
    musicShuffle =  new CheckBox('K', "Shuffle Music", this);
    musicDisable =  new CheckBox('Q', "Disable Music", this);
    copyChecksum =  new CheckBox(NO_FLAG, "Copy Checksum to Clipboard", this);

    this->levelSpeed = new LevelComboBox(this);

    this->goButton = new QPushButton("Randomize!", this);
}

void MainWindow::initSlots()
{
    connect(this->flags, SIGNAL(textEdited(QString)), this, SLOT(handleFlags()));

    connect(this->chests,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->shops,        SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->deathNecklace,SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->speedHacks,   SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->growth,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->spells,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->attack,       SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->zones,        SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->musicShuffle, SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->musicDisable, SIGNAL(clicked()), this, SLOT(handleCheckBox()));
    connect(this->copyChecksum, SIGNAL(clicked()), this, SLOT(handleCheckBox()));

    connect(this->levelSpeed, SIGNAL(activated(int)),
            this, SLOT(handleCheckBox()));

    connect(this->goButton,     SIGNAL(clicked()), this, SLOT(handleButton()));
}

void MainWindow::layout()
{
    QVBoxLayout *vbox;
    QGridLayout *grid;

    vbox = new QVBoxLayout();
    grid = new QGridLayout();

    grid->addWidget(this->romFile,   0, 0, 0);
    grid->addWidget(this->outputDir, 0, 1, 0);
    grid->addWidget(this->seed,      1, 0, 0);
    grid->addWidget(this->flags,     1, 1, 0);

    vbox->addLayout(grid);
    grid = new QGridLayout();
    vbox->addLayout(grid);

    grid->addWidget(this->chests,        0, 0, 0);
    grid->addWidget(this->shops,         1, 0, 0);
    grid->addWidget(this->zones,         2, 0, 0);

    grid->addWidget(this->growth,        0, 1, 0);
    grid->addWidget(this->spells,        1, 1, 0);
    grid->addWidget(this->attack,        2, 1, 0);
    grid->addWidget(this->copyChecksum,  3, 1, 0);

    grid->addWidget(this->deathNecklace, 0, 2, 0);
    grid->addWidget(this->speedHacks,    1, 2, 0);
    grid->addWidget(this->musicShuffle,  2, 2, 0);
    grid->addWidget(this->musicDisable,  3, 2, 0);

    grid->addWidget(new QLabel("Leveling Speed", this), 6, 0, 0);
    grid->addWidget(this->levelSpeed,    7, 0, 0);

    grid->addWidget(this->goButton,      8, 2, 0);

    this->mainWidget->setLayout(vbox);

    this->copyChecksum->hide();
}

QString MainWindow::getOptions()
{
    std::string flags = std::string() +
                        this->chests->getFlag() +
                        this->shops->getFlag() +
                        this->deathNecklace->getFlag() +
                        this->speedHacks->getFlag() +
                        this->growth->getFlag() +
                        this->spells->getFlag() +
                        this->attack->getFlag() +
                        this->zones->getFlag() +
                        this->musicShuffle->getFlag() +
                        this->musicDisable->getFlag() +
                        this->copyChecksum->getFlag() +

                        this->levelSpeed->getFlag();

    std::sort(flags.begin(), flags.end());
    std::replace(flags.begin(), flags.end(), NO_FLAG, '\0');
    return QString(flags.c_str());
}

void MainWindow::setOptions(QString flags)
{
    this->chests->updateState(flags);
    this->shops->updateState(flags);
    this->deathNecklace->updateState(flags);
    this->speedHacks->updateState(flags);
    this->growth->updateState(flags);
    this->spells->updateState(flags);
    this->attack->updateState(flags);
    this->zones->updateState(flags);
    this->musicShuffle->updateState(flags);
    this->musicDisable->updateState(flags);
    this->copyChecksum->updateState(flags);

    this->levelSpeed->updateState(flags);
}

QString MainWindow::getFlags()
{
    std::string flags = this->flags->text().toStdString();
    std::sort(flags.begin(), flags.end());
    return QString::fromStdString(flags);
}

void MainWindow::setFlags(QString flags)
{
    this->flags->setText(flags);
}

void MainWindow::handleCheckBox()
{
    QString flags = this->getOptions();
    this->setFlags(flags);
}

void MainWindow::handleComboBox(int index)
{
    this->handleCheckBox();
}

void MainWindow::handleFlags()
{
    QString flags = this->getFlags();
    this->setOptions(flags);
}

void MainWindow::handleButton()
{
    char flags[64], checksum[64];
    QString flagStr = this->getFlags();
    strncpy(flags, flagStr.toLatin1().constData(), 64);

    uint64_t seed = this->seed->getSeed();
    std::string inputFile = this->romFile->text().toLatin1().constData();
    std::string outputDir = this->outputDir->text().toLatin1().constData();
    uint64_t crc = dwr_randomize(inputFile.c_str(), seed,
                                 flags, outputDir.c_str());
    if (crc) {
        sprintf(checksum, "Checksum: %016" PRIx64, crc);
        QGuiApplication::clipboard()->setText(checksum);
        this->statusBar()->showMessage("Checksum copied to clipboard", 3000);
        QMessageBox::information(this, "Success!",
                                 "The new ROM has been created.");
    } else {
        QMessageBox::critical(this, "Failed", "An error occurred and"
                "the ROM could not be created.");
    }
    this->saveConfig();
}

bool MainWindow::saveConfig()
{
    QDir configDir("");
    if (!configDir.exists(QDir::homePath() + "/.config/")){
        configDir.mkdir(QDir::homePath() + "/.config/");
    }

    QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf");
    if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        printf("Failed to save configuration.\n");
        return false;
    }
    QTextStream out(&configFile);

    out << this->romFile->text() << endl;
    out << this->outputDir->text() << endl;
    out << this->getFlags() << endl;

    return true;
}

bool MainWindow::loadConfig()
{
    char tmp[1024];
    qint64 read;
    QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf");
    if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        printf("Failed to load configuration.\n");
        return false;
    }
    read = configFile.readLine(tmp, 1024);
    tmp[read - 1] = '\0';
    this->romFile->setText(tmp);
    if (configFile.atEnd()) {
        return false;
    }

    read = configFile.readLine(tmp, 1024);
    tmp[read - 1] = '\0';
    this->outputDir->setText(tmp);
    if (configFile.atEnd()) {
        return false;
    }

    read = configFile.readLine(tmp, 1024);
    tmp[read - 1] = '\0';
    this->setFlags(tmp);
    this->setOptions(tmp);

    return true;
}
<|endoftext|>


<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "paintwidgets.hh"
#include "factory.hh"
#include "painter.hh"

#define CHECK_CAIRO_STATUS(status)      do {    \
  cairo_status_t ___s = (status);               \
  if (___s != CAIRO_STATUS_SUCCESS)             \
    RAPICORN_DIAG ("%s: %s", cairo_status_to_string (___s), #status);   \
  } while (0)

namespace Rapicorn {

// == ArrowImpl ==
ArrowImpl::ArrowImpl() :
  dir_ (Direction::RIGHT)
{}

ArrowImpl::~ArrowImpl()
{}

Direction
ArrowImpl::arrow_dir () const
{
  return dir_;
}

void
ArrowImpl::arrow_dir (Direction dir)
{
  dir_ = dir;
  expose();
  changed ("arrow_dir");
}

static DataKey<SizePolicy> size_policy_key;

SizePolicy
ArrowImpl::size_policy () const
{
  SizePolicy spol = get_data (&size_policy_key);
  return spol;
}

void
ArrowImpl::size_policy (SizePolicy spol)
{
  if (spol == 0)
    delete_data (&size_policy_key);
  else
    set_data (&size_policy_key, spol);
  invalidate_size();
  changed ("size_policy");
}

void
ArrowImpl::size_request (Requisition &requisition)
{
  requisition.width = 3;
  requisition.height = 3;
}

void
ArrowImpl::size_allocate (Allocation area, bool changed)
{
  SizePolicy spol = size_policy();
  if (spol == SizePolicy::WIDTH_FROM_HEIGHT)
    tune_requisition (area.height, -1);
  else if (spol == SizePolicy::HEIGHT_FROM_WIDTH)
    tune_requisition (-1, area.width);
}

void
ArrowImpl::render (RenderContext &rcontext)
{
  IRect ia = allocation();
  int x = ia.x, y = ia.y, width = ia.width, height = ia.height;
  if (width >= 2 && height >= 2)
    {
      cairo_t *cr = cairo_context (rcontext);
      CPainter painter (cr);
      painter.draw_dir_arrow (x, y, width, height, foreground(), dir_);
    }
}

static const WidgetFactory<ArrowImpl> arrow_factory ("Rapicorn::Arrow");

// == DotGrid ==
DotGridImpl::DotGridImpl() :
  normal_dot_ (DrawFrame::IN),
  active_dot_ (DrawFrame::IN),
  n_hdots_ (1), n_vdots_ (1),
  right_padding_dots_ (0), top_padding_dots_ (0),
  left_padding_dots_ (0), bottom_padding_dots_ (0)
{}

DotGridImpl::~DotGridImpl()
{}

DrawFrame
DotGridImpl::dot_type () const
{
  RAPICORN_ASSERT_UNREACHED();
}

void
DotGridImpl::dot_type (DrawFrame ft)
{
  normal_dot (ft);
  active_dot (ft);
}

DrawFrame
DotGridImpl::current_dot ()
{
  return ancestry_active() ? active_dot() : normal_dot();
}

static inline int
u31 (int v)
{
  return CLAMP (v, 0, INT_MAX);
}

void
DotGridImpl::active_dot (DrawFrame ft)
{
  active_dot_ = ft;
  expose();
  changed ("active_dot");
}

DrawFrame
DotGridImpl::active_dot () const
{
  return active_dot_;
}

void
DotGridImpl::normal_dot (DrawFrame ft)
{
  normal_dot_ = ft;
  expose();
  changed ("normal_dot");
}

DrawFrame
DotGridImpl::normal_dot () const
{
  return normal_dot_;
}

void
DotGridImpl::n_hdots (int num)
{
  n_hdots_ = u31 (num);
  expose();
  changed ("n_hdots");
}

int
DotGridImpl::n_hdots () const
{
  return n_hdots_;
}

void
DotGridImpl::n_vdots (int num)
{
  n_vdots_ = u31 (num);
  expose();
  changed ("n_vdots");
}

int
DotGridImpl::n_vdots () const
{
  return n_vdots_;
}

int
DotGridImpl::right_padding_dots () const
{
  return right_padding_dots_;
}

void
DotGridImpl::right_padding_dots (int c)
{
  right_padding_dots_ = u31 (c);
  expose();
  changed ("right_padding_dots");
}

int
DotGridImpl::top_padding_dots () const
{
  return top_padding_dots_;
}

void
DotGridImpl::top_padding_dots (int c)
{
  top_padding_dots_ = u31 (c);
  expose();
  changed ("top_padding_dots");
}

int
DotGridImpl::left_padding_dots () const
{
  return left_padding_dots_;
}

void
DotGridImpl::left_padding_dots (int c)
{
  left_padding_dots_ = u31 (c);
  expose();
  changed ("left_padding_dots");
}

int
DotGridImpl::bottom_padding_dots () const
{
  return bottom_padding_dots_;
}

void
DotGridImpl::bottom_padding_dots (int c)
{
  bottom_padding_dots_ = u31 (c);
  expose();
  changed ("bottom_padding_dots");
}

void
DotGridImpl::size_request (Requisition &requisition)
{
  const uint ythick = 1, xthick = 1;
  requisition.width = n_hdots_ * (xthick + xthick) + MAX (n_hdots_ - 1, 0) * xthick;
  requisition.height = n_vdots_ * (ythick + ythick) + MAX (n_vdots_ - 1, 0) * ythick;
  requisition.width += (right_padding_dots_ + left_padding_dots_) * 3 * xthick;
  requisition.height += (top_padding_dots_ + bottom_padding_dots_) * 3 * ythick;
}

void
DotGridImpl::size_allocate (Allocation area, bool changed)
{}

void
DotGridImpl::render (RenderContext &rcontext)
{
  const int ythick = 1, xthick = 1;
  int n_hdots = n_hdots_, n_vdots = n_vdots_;
  const IRect ia = allocation();
  int x = ia.x, y = ia.y, width = ia.width, height = ia.height;
  const int rq_width = n_hdots_ * (xthick + xthick) + MAX (n_hdots - 1, 0) * xthick;
  const int rq_height = n_vdots_ * (ythick + ythick) + MAX (n_vdots - 1, 0) * ythick;
  /* split up extra width */
  const uint hpadding = right_padding_dots_ + left_padding_dots_;
  const double halign = hpadding ? left_padding_dots_ * 1.0 / hpadding : 0.5;
  if (rq_width < width)
    x += ifloor ((width - rq_width) * halign);
  /* split up extra height */
  const uint vpadding = top_padding_dots_ + bottom_padding_dots_;
  const double valign = vpadding ? bottom_padding_dots_ * 1.0 / vpadding : 0.5;
  if (rq_height < height)
    y += ifloor ((height - rq_height) * valign);
  /* draw dots */
  if (width >= 2 * xthick && height >= 2 * ythick && n_hdots && n_vdots)
    {
      /* limit n_hdots */
      if (rq_width > width)
        {
          const int w = width - 2 * xthick;     // dot1
          n_hdots = 1 + w / (3 * xthick);
        }
      /* limit n_vdots */
      if (rq_height > height)
        {
          const int h = height - 2 * ythick;    // dot1
          n_vdots = 1 + h / (3 * ythick);
        }
      cairo_t *cr = cairo_context (rcontext);
      CPainter rp (cr);
      for (int j = 0; j < n_vdots; j++)
        {
          int xtmp = 0;
          for (int i = 0; i < n_hdots; i++)
            {
              rp.draw_shaded_rect (x + xtmp, y + 2 * ythick - 1, dark_shadow(),
                                   x + xtmp + 2 * xthick - 1, y, light_glint());
              xtmp += 3 * xthick;
            }
          y += 3 * ythick;
        }
    }
}

static const WidgetFactory<DotGridImpl> dot_grid_factory ("Rapicorn::DotGrid");

// == DrawableImpl ==
DrawableImpl::DrawableImpl() :
  x_ (0), y_ (0)
{}

void
DrawableImpl::size_request (Requisition &requisition)
{
  requisition.width = 320;
  requisition.height = 200;
}

void
DrawableImpl::size_allocate (Allocation area, bool changed)
{
  if (false) // clear out, can lead to flicker
    {
      pixbuf_ = Pixbuf();
      x_ = 0;
      y_ = 0;
    }
  sig_redraw.emit (area.x, area.y, area.width, area.height);
}

void
DrawableImpl::draw_rect (int x, int y, const Pixbuf &pixbuf)
{
  const Allocation &area = allocation();
  const size_t rowstride = pixbuf.width();
  if (x >= area.x && y >= area.y &&
      x + pixbuf.width() <= area.x + area.width &&
      y + pixbuf.height() <= area.y + area.height &&
      rowstride * pixbuf.height() <= pixbuf.pixels.size())
    {
      x_ = x;
      y_ = y;
      pixbuf_ = pixbuf;
    }
  else if (pixbuf_.width() > 0)
    {
      pixbuf_ = Pixbuf();
      x_ = 0;
      y_ = 0;
    }
  invalidate_content();
}

void
DrawableImpl::render (RenderContext &rcontext)
{
  const uint size = 10;
  const Allocation &area = allocation();
  cairo_t *cr = cairo_context (rcontext);
  // checkerboard pattern
  if (true)
    {
      cairo_save (cr);
      cairo_surface_t *ps = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, 2 * size, 2 * size);
      cairo_t *pc = cairo_create (ps);
      cairo_set_source_rgb (pc, 1.0, 1.0, 1.0);
      cairo_rectangle (pc,    0,    0, size, size);
      cairo_rectangle (pc, size, size, size, size);
      cairo_fill (pc);
      cairo_set_source_rgb (pc, 0.9, 0.9, 0.9);
      cairo_rectangle (pc,    0, size, size, size);
      cairo_rectangle (pc, size,    0, size, size);
      cairo_fill (pc);
      cairo_destroy (pc);
      cairo_pattern_t *pat = cairo_pattern_create_for_surface (ps);
      cairo_surface_destroy (ps);
      cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT);
      // render pattern
      cairo_rectangle (cr, area.x, area.y, area.width, area.height);
      cairo_clip (cr);
      cairo_translate (cr, area.x, area.y + area.height);
      cairo_set_source (cr, pat);
      cairo_paint (cr);
      cairo_pattern_destroy (pat);
      cairo_restore (cr);
    }
  // handle user draw
  if (pixbuf_.width() > 0 && pixbuf_.height() > 0)
    {
      const int rowstride = pixbuf_.width();
      cairo_surface_t *surface = cairo_image_surface_create_for_data ((uint8*) pixbuf_.pixels.data(), CAIRO_FORMAT_ARGB32,
                                                                      pixbuf_.width(), pixbuf_.height(), rowstride * 4);
      CHECK_CAIRO_STATUS (cairo_surface_status (surface));
      cairo_set_source_surface (cr, surface, x_, y_);
      cairo_paint (cr);
      cairo_surface_destroy (surface);
    }
}

static const WidgetFactory<DrawableImpl> drawable_factory ("Rapicorn::Drawable");

} // Rapicorn
<commit_msg>UI: paintwidgets.cc: use CAIRO_CHECK_STATUS()<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "paintwidgets.hh"
#include "factory.hh"
#include "painter.hh"
#include "rcore/cairoutils.hh"

namespace Rapicorn {

// == ArrowImpl ==
ArrowImpl::ArrowImpl() :
  dir_ (Direction::RIGHT)
{}

ArrowImpl::~ArrowImpl()
{}

Direction
ArrowImpl::arrow_dir () const
{
  return dir_;
}

void
ArrowImpl::arrow_dir (Direction dir)
{
  dir_ = dir;
  expose();
  changed ("arrow_dir");
}

static DataKey<SizePolicy> size_policy_key;

SizePolicy
ArrowImpl::size_policy () const
{
  SizePolicy spol = get_data (&size_policy_key);
  return spol;
}

void
ArrowImpl::size_policy (SizePolicy spol)
{
  if (spol == 0)
    delete_data (&size_policy_key);
  else
    set_data (&size_policy_key, spol);
  invalidate_size();
  changed ("size_policy");
}

void
ArrowImpl::size_request (Requisition &requisition)
{
  requisition.width = 3;
  requisition.height = 3;
}

void
ArrowImpl::size_allocate (Allocation area, bool changed)
{
  SizePolicy spol = size_policy();
  if (spol == SizePolicy::WIDTH_FROM_HEIGHT)
    tune_requisition (area.height, -1);
  else if (spol == SizePolicy::HEIGHT_FROM_WIDTH)
    tune_requisition (-1, area.width);
}

void
ArrowImpl::render (RenderContext &rcontext)
{
  IRect ia = allocation();
  int x = ia.x, y = ia.y, width = ia.width, height = ia.height;
  if (width >= 2 && height >= 2)
    {
      cairo_t *cr = cairo_context (rcontext);
      CPainter painter (cr);
      painter.draw_dir_arrow (x, y, width, height, foreground(), dir_);
    }
}

static const WidgetFactory<ArrowImpl> arrow_factory ("Rapicorn::Arrow");

// == DotGrid ==
DotGridImpl::DotGridImpl() :
  normal_dot_ (DrawFrame::IN),
  active_dot_ (DrawFrame::IN),
  n_hdots_ (1), n_vdots_ (1),
  right_padding_dots_ (0), top_padding_dots_ (0),
  left_padding_dots_ (0), bottom_padding_dots_ (0)
{}

DotGridImpl::~DotGridImpl()
{}

DrawFrame
DotGridImpl::dot_type () const
{
  RAPICORN_ASSERT_UNREACHED();
}

void
DotGridImpl::dot_type (DrawFrame ft)
{
  normal_dot (ft);
  active_dot (ft);
}

DrawFrame
DotGridImpl::current_dot ()
{
  return ancestry_active() ? active_dot() : normal_dot();
}

static inline int
u31 (int v)
{
  return CLAMP (v, 0, INT_MAX);
}

void
DotGridImpl::active_dot (DrawFrame ft)
{
  active_dot_ = ft;
  expose();
  changed ("active_dot");
}

DrawFrame
DotGridImpl::active_dot () const
{
  return active_dot_;
}

void
DotGridImpl::normal_dot (DrawFrame ft)
{
  normal_dot_ = ft;
  expose();
  changed ("normal_dot");
}

DrawFrame
DotGridImpl::normal_dot () const
{
  return normal_dot_;
}

void
DotGridImpl::n_hdots (int num)
{
  n_hdots_ = u31 (num);
  expose();
  changed ("n_hdots");
}

int
DotGridImpl::n_hdots () const
{
  return n_hdots_;
}

void
DotGridImpl::n_vdots (int num)
{
  n_vdots_ = u31 (num);
  expose();
  changed ("n_vdots");
}

int
DotGridImpl::n_vdots () const
{
  return n_vdots_;
}

int
DotGridImpl::right_padding_dots () const
{
  return right_padding_dots_;
}

void
DotGridImpl::right_padding_dots (int c)
{
  right_padding_dots_ = u31 (c);
  expose();
  changed ("right_padding_dots");
}

int
DotGridImpl::top_padding_dots () const
{
  return top_padding_dots_;
}

void
DotGridImpl::top_padding_dots (int c)
{
  top_padding_dots_ = u31 (c);
  expose();
  changed ("top_padding_dots");
}

int
DotGridImpl::left_padding_dots () const
{
  return left_padding_dots_;
}

void
DotGridImpl::left_padding_dots (int c)
{
  left_padding_dots_ = u31 (c);
  expose();
  changed ("left_padding_dots");
}

int
DotGridImpl::bottom_padding_dots () const
{
  return bottom_padding_dots_;
}

void
DotGridImpl::bottom_padding_dots (int c)
{
  bottom_padding_dots_ = u31 (c);
  expose();
  changed ("bottom_padding_dots");
}

void
DotGridImpl::size_request (Requisition &requisition)
{
  const uint ythick = 1, xthick = 1;
  requisition.width = n_hdots_ * (xthick + xthick) + MAX (n_hdots_ - 1, 0) * xthick;
  requisition.height = n_vdots_ * (ythick + ythick) + MAX (n_vdots_ - 1, 0) * ythick;
  requisition.width += (right_padding_dots_ + left_padding_dots_) * 3 * xthick;
  requisition.height += (top_padding_dots_ + bottom_padding_dots_) * 3 * ythick;
}

void
DotGridImpl::size_allocate (Allocation area, bool changed)
{}

void
DotGridImpl::render (RenderContext &rcontext)
{
  const int ythick = 1, xthick = 1;
  int n_hdots = n_hdots_, n_vdots = n_vdots_;
  const IRect ia = allocation();
  int x = ia.x, y = ia.y, width = ia.width, height = ia.height;
  const int rq_width = n_hdots_ * (xthick + xthick) + MAX (n_hdots - 1, 0) * xthick;
  const int rq_height = n_vdots_ * (ythick + ythick) + MAX (n_vdots - 1, 0) * ythick;
  /* split up extra width */
  const uint hpadding = right_padding_dots_ + left_padding_dots_;
  const double halign = hpadding ? left_padding_dots_ * 1.0 / hpadding : 0.5;
  if (rq_width < width)
    x += ifloor ((width - rq_width) * halign);
  /* split up extra height */
  const uint vpadding = top_padding_dots_ + bottom_padding_dots_;
  const double valign = vpadding ? bottom_padding_dots_ * 1.0 / vpadding : 0.5;
  if (rq_height < height)
    y += ifloor ((height - rq_height) * valign);
  /* draw dots */
  if (width >= 2 * xthick && height >= 2 * ythick && n_hdots && n_vdots)
    {
      /* limit n_hdots */
      if (rq_width > width)
        {
          const int w = width - 2 * xthick;     // dot1
          n_hdots = 1 + w / (3 * xthick);
        }
      /* limit n_vdots */
      if (rq_height > height)
        {
          const int h = height - 2 * ythick;    // dot1
          n_vdots = 1 + h / (3 * ythick);
        }
      cairo_t *cr = cairo_context (rcontext);
      CPainter rp (cr);
      for (int j = 0; j < n_vdots; j++)
        {
          int xtmp = 0;
          for (int i = 0; i < n_hdots; i++)
            {
              rp.draw_shaded_rect (x + xtmp, y + 2 * ythick - 1, dark_shadow(),
                                   x + xtmp + 2 * xthick - 1, y, light_glint());
              xtmp += 3 * xthick;
            }
          y += 3 * ythick;
        }
    }
}

static const WidgetFactory<DotGridImpl> dot_grid_factory ("Rapicorn::DotGrid");

// == DrawableImpl ==
DrawableImpl::DrawableImpl() :
  x_ (0), y_ (0)
{}

void
DrawableImpl::size_request (Requisition &requisition)
{
  requisition.width = 320;
  requisition.height = 200;
}

void
DrawableImpl::size_allocate (Allocation area, bool changed)
{
  if (false) // clear out, can lead to flicker
    {
      pixbuf_ = Pixbuf();
      x_ = 0;
      y_ = 0;
    }
  sig_redraw.emit (area.x, area.y, area.width, area.height);
}

void
DrawableImpl::draw_rect (int x, int y, const Pixbuf &pixbuf)
{
  const Allocation &area = allocation();
  const size_t rowstride = pixbuf.width();
  if (x >= area.x && y >= area.y &&
      x + pixbuf.width() <= area.x + area.width &&
      y + pixbuf.height() <= area.y + area.height &&
      rowstride * pixbuf.height() <= pixbuf.pixels.size())
    {
      x_ = x;
      y_ = y;
      pixbuf_ = pixbuf;
    }
  else if (pixbuf_.width() > 0)
    {
      pixbuf_ = Pixbuf();
      x_ = 0;
      y_ = 0;
    }
  invalidate_content();
}

void
DrawableImpl::render (RenderContext &rcontext)
{
  const uint size = 10;
  const Allocation &area = allocation();
  cairo_t *cr = cairo_context (rcontext);
  // checkerboard pattern
  if (true)
    {
      cairo_save (cr);
      cairo_surface_t *ps = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, 2 * size, 2 * size);
      cairo_t *pc = cairo_create (ps);
      cairo_set_source_rgb (pc, 1.0, 1.0, 1.0);
      cairo_rectangle (pc,    0,    0, size, size);
      cairo_rectangle (pc, size, size, size, size);
      cairo_fill (pc);
      cairo_set_source_rgb (pc, 0.9, 0.9, 0.9);
      cairo_rectangle (pc,    0, size, size, size);
      cairo_rectangle (pc, size,    0, size, size);
      cairo_fill (pc);
      cairo_destroy (pc);
      cairo_pattern_t *pat = cairo_pattern_create_for_surface (ps);
      cairo_surface_destroy (ps);
      cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT);
      // render pattern
      cairo_rectangle (cr, area.x, area.y, area.width, area.height);
      cairo_clip (cr);
      cairo_translate (cr, area.x, area.y + area.height);
      cairo_set_source (cr, pat);
      cairo_paint (cr);
      cairo_pattern_destroy (pat);
      cairo_restore (cr);
    }
  // handle user draw
  if (pixbuf_.width() > 0 && pixbuf_.height() > 0)
    {
      const int rowstride = pixbuf_.width();
      cairo_surface_t *surface = cairo_image_surface_create_for_data ((uint8*) pixbuf_.pixels.data(), CAIRO_FORMAT_ARGB32,
                                                                      pixbuf_.width(), pixbuf_.height(), rowstride * 4);
      CAIRO_CHECK_STATUS (cairo_surface_status (surface));
      cairo_set_source_surface (cr, surface, x_, y_);
      cairo_paint (cr);
      cairo_surface_destroy (surface);
    }
}

static const WidgetFactory<DrawableImpl> drawable_factory ("Rapicorn::Drawable");

} // Rapicorn
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <QtCore>
#include <QFile>
#include <QString>
#include "server/websocketserver.h"
#include "prepare_tmp_deb_package.h"

int main(int argc, char** argv) {
	QCoreApplication a(argc, argv);

    QCommandLineParser parser;
    parser.setApplicationDescription("freehackquest-backend");
    parser.addHelpOption();

    QCommandLineOption versionOption(QStringList() << "v" << "version", QCoreApplication::translate("main", "Version"));
    parser.addOption(versionOption);

    QCommandLineOption prepareDebOption(QStringList() << "pd" << "prepare-deb", QCoreApplication::translate("main", "Prepare Deb Package"));
    parser.addOption(prepareDebOption);

    parser.process(a);

    bool version = parser.isSet(versionOption);
    if(version){
		std::cout << PrepareTmpDebPackage::version().toStdString() << "\n";
		return 0;
	}

	bool prepare_deb = parser.isSet(prepareDebOption);
    if(prepare_deb){
		PrepareTmpDebPackage::prepare("","tmpdeb");
		return 0;
	}

	if(!QFile::exists("/etc/freehackquest-backend/conf.ini")){
		qDebug() << "Not found /etc/freehackquest-backend/conf.ini";
		return 0;
	}

	QThreadPool::globalInstance()->setMaxThreadCount(5);
    WebSocketServer *pServer = new WebSocketServer();
    QObject::connect(pServer, &WebSocketServer::closed, &a, &QCoreApplication::quit);

    // TODO redesign to check config
    QSqlDatabase *db = pServer->database();
    if (!db->open()){
		return -1;
	}

	return a.exec();
}
<commit_msg>Fixed compile error<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <QtCore>
#include <QFile>
#include <QString>
#include <websocketserver.h>
#include "prepare_tmp_deb_package.h"

int main(int argc, char** argv) {
	QCoreApplication a(argc, argv);

    QCommandLineParser parser;
    parser.setApplicationDescription("freehackquest-backend");
    parser.addHelpOption();

    QCommandLineOption versionOption(QStringList() << "v" << "version", QCoreApplication::translate("main", "Version"));
    parser.addOption(versionOption);

    QCommandLineOption prepareDebOption(QStringList() << "pd" << "prepare-deb", QCoreApplication::translate("main", "Prepare Deb Package"));
    parser.addOption(prepareDebOption);

    parser.process(a);

    bool version = parser.isSet(versionOption);
    if(version){
		std::cout << PrepareTmpDebPackage::version().toStdString() << "\n";
		return 0;
	}

	bool prepare_deb = parser.isSet(prepareDebOption);
    if(prepare_deb){
		PrepareTmpDebPackage::prepare("","tmpdeb");
		return 0;
	}

	if(!QFile::exists("/etc/freehackquest-backend/conf.ini")){
		qDebug() << "Not found /etc/freehackquest-backend/conf.ini";
		return 0;
	}

	QThreadPool::globalInstance()->setMaxThreadCount(5);
    WebSocketServer *pServer = new WebSocketServer();
    QObject::connect(pServer, &WebSocketServer::closed, &a, &QCoreApplication::quit);

    // TODO redesign to check config
    QSqlDatabase *db = pServer->database();
    if (!db->open()){
		return -1;
	}

	return a.exec();
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QApplication>
#include <QSplashScreen>
#include <QTimer>

#define SPLASH

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

#ifdef SPLASH
    QImage img(":/icons/splashscreen.png");
    QPixmap pixmap = QPixmap::fromImage(img);
    QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint);
    splash.show();
    a.processEvents();
#endif

    MainWindow w;

#ifdef SPLASH
    w.hide();

    QTimer::singleShot(2500, &splash, SLOT(close()));
    QTimer::singleShot(1500, &w, SLOT(unhide()));
#else
    w.show();
#endif

    return a.exec();
}
<commit_msg>Splashscreen: Faster unhidding of main window.<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QSplashScreen>
#include <QTimer>

#define SPLASH

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

#ifdef SPLASH
    QImage img(":/icons/splashscreen.png");
    QPixmap pixmap = QPixmap::fromImage(img);
    QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint);
    splash.show();
    a.processEvents();
#endif

    MainWindow w;

#ifdef SPLASH
    w.hide();

    QTimer::singleShot(2500, &splash, SLOT(close()));
    QTimer::singleShot(500, &w, SLOT(unhide()));
#else
    w.show();
#endif

    return a.exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
 * Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
 * Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
 *
 * This file is part of SuperKaramba.
 *
 *  SuperKaramba is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  SuperKaramba 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SuperKaramba; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#include "karambaapp.h"
#include "karambasessionmanaged.h"
#include "python/karamba.h"

#include "config-superkaramba.h"

#include <stdlib.h>

#include <KLocale>
#include <KConfig>
#include <KDebug>
#include <KStandardDirs>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KWindowSystem>

#include <X11/extensions/Xrender.h>

static const char *description =
    I18N_NOOP("A KDE Eye-candy Application");

static const char *version = "0.50";

int main(int argc, char **argv)
{
    Display *dpy = XOpenDisplay(0); // open default display
    if (!dpy) {
        kWarning() << "Cannot connect to the X server";
        exit(1);
    }

    Colormap colormap = 0;
    Visual *visual = 0;

    if (KWindowSystem::compositingActive()) {
        int screen = DefaultScreen(dpy);
        int eventBase, errorBase;

        if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) {
            int nvi;
            XVisualInfo templ;
            templ.screen  = screen;
            templ.depth   = 32;
            templ.c_class = TrueColor;
            XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask |
                                              VisualDepthMask |
                                              VisualClassMask,
                                              &templ, &nvi);
            for (int i = 0; i < nvi; ++i) {
                XRenderPictFormat *format = XRenderFindVisualFormat(dpy,
                                            xvi[i].visual);
                if (format->type == PictTypeDirect && format->direct.alphaMask) {
                    visual = xvi[i].visual;
                    colormap = XCreateColormap(dpy, RootWindow(dpy, screen),
                                               visual, AllocNone);
                    break;
                }
            }
        }
    }

    KAboutData about("superkaramba", 0, ki18n("SuperKaramba"),
                     version, ki18n(description),
                     KAboutData::License_GPL,
                     ki18n("(c) 2003-2007 The SuperKaramba developers"));
    about.addAuthor(ki18n("Adam Geitgey"), KLocalizedString(), "adam@rootnode.org");
    about.addAuthor(ki18n("Hans Karlsson"), KLocalizedString(), "karlsson.h@home.se");
    about.addAuthor(ki18n("Ryan Nickell"), KLocalizedString(), "p0z3r@earthlink.net");
    about.addAuthor(ki18n("Petri Damstén"), KLocalizedString(), "petri.damsten@iki.fi");
    about.addAuthor(ki18n("Alexander Wiedenbruch"), KLocalizedString(), "mail@wiedenbruch.de");
    about.addAuthor(ki18n("Luke Kenneth Casson Leighton"), KLocalizedString(), "lkcl@lkcl.net");
    about.addCredit(ki18n("Sebastian Sauer"), ki18n("Work on Kross, tutorials and examples"), "mail@dipe.org");
    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    // { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
// { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
#ifdef PYTHON_INCLUDE_PATH
   options.add("usefallback", ki18n("Use the original python bindings as scripting backend. Off by default."));
#endif
    options.add("+file", ki18n("A required argument 'file'"));
    KCmdLineArgs::addCmdLineOptions(options);
    KarambaApplication::addCmdLineOptions();
    KarambaSessionManaged ksm;

    if (!KarambaApplication::start()) {
        fprintf(stderr, "SuperKaramba is already running!\n");
        exit(0);
    }

#ifdef PYTHON_INCLUDE_PATH
    bool noUseKross = false;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->isSet("usefallback")) {
        noUseKross = true;
        kDebug() << "Using fallback python scripting backend!" ;
    }
#endif

    KarambaApplication app(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap));

    app.setupSysTray(&about);
    int ret = 0;

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::initPython();
    }
#endif

    ret = app.exec();

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::shutdownPython();
    }
#endif

    return ret;
}
<commit_msg>Updating the version number and adding link to homepage on utils.kde.org<commit_after>/*
 * Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
 * Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
 * Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
 *
 * This file is part of SuperKaramba.
 *
 *  SuperKaramba is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  SuperKaramba 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SuperKaramba; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#include "karambaapp.h"
#include "karambasessionmanaged.h"
#include "python/karamba.h"

#include "config-superkaramba.h"

#include <stdlib.h>

#include <KLocale>
#include <KConfig>
#include <KDebug>
#include <KStandardDirs>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KWindowSystem>

#include <X11/extensions/Xrender.h>

static const char *description =
    I18N_NOOP("A KDE Eye-candy Application");

static const char *version = "0.52";

int main(int argc, char **argv)
{
    Display *dpy = XOpenDisplay(0); // open default display
    if (!dpy) {
        kWarning() << "Cannot connect to the X server";
        exit(1);
    }

    Colormap colormap = 0;
    Visual *visual = 0;

    if (KWindowSystem::compositingActive()) {
        int screen = DefaultScreen(dpy);
        int eventBase, errorBase;

        if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) {
            int nvi;
            XVisualInfo templ;
            templ.screen  = screen;
            templ.depth   = 32;
            templ.c_class = TrueColor;
            XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask |
                                              VisualDepthMask |
                                              VisualClassMask,
                                              &templ, &nvi);
            for (int i = 0; i < nvi; ++i) {
                XRenderPictFormat *format = XRenderFindVisualFormat(dpy,
                                            xvi[i].visual);
                if (format->type == PictTypeDirect && format->direct.alphaMask) {
                    visual = xvi[i].visual;
                    colormap = XCreateColormap(dpy, RootWindow(dpy, screen),
                                               visual, AllocNone);
                    break;
                }
            }
        }
    }

    KAboutData about("superkaramba", 0, ki18n("SuperKaramba"),
                     version, ki18n(description),
                     KAboutData::License_GPL,
                     ki18n("(c) 2003-2007 The SuperKaramba developers"), KLocalizedString(),
                     "http://utils.kde.org/projects/superkaramba");
    about.addAuthor(ki18n("Adam Geitgey"), KLocalizedString(), "adam@rootnode.org");
    about.addAuthor(ki18n("Hans Karlsson"), KLocalizedString(), "karlsson.h@home.se");
    about.addAuthor(ki18n("Ryan Nickell"), KLocalizedString(), "p0z3r@earthlink.net");
    about.addAuthor(ki18n("Petri Damstén"), KLocalizedString(), "petri.damsten@iki.fi");
    about.addAuthor(ki18n("Alexander Wiedenbruch"), KLocalizedString(), "mail@wiedenbruch.de");
    about.addAuthor(ki18n("Luke Kenneth Casson Leighton"), KLocalizedString(), "lkcl@lkcl.net");
    about.addCredit(ki18n("Sebastian Sauer"), ki18n("Work on Kross, tutorials and examples"), "mail@dipe.org");
    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    // { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
// { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
#ifdef PYTHON_INCLUDE_PATH
   options.add("usefallback", ki18n("Use the original python bindings as scripting backend. Off by default."));
#endif
    options.add("+file", ki18n("A required argument 'file'"));
    KCmdLineArgs::addCmdLineOptions(options);
    KarambaApplication::addCmdLineOptions();
    KarambaSessionManaged ksm;

    if (!KarambaApplication::start()) {
        fprintf(stderr, "SuperKaramba is already running!\n");
        exit(0);
    }

#ifdef PYTHON_INCLUDE_PATH
    bool noUseKross = false;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->isSet("usefallback")) {
        noUseKross = true;
        kDebug() << "Using fallback python scripting backend!" ;
    }
#endif

    KarambaApplication app(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap));

    app.setupSysTray(&about);
    int ret = 0;

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::initPython();
    }
#endif

    ret = app.exec();

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::shutdownPython();
    }
#endif

    return ret;
}
<|endoftext|>


<commit_before>#include <AppConfig.h>
// #include <modules/juce_audio_basics/juce_audio_basics.h>
// #include <modules/juce_audio_devices/juce_audio_devices.h>
// #include <modules/juce_audio_formats/juce_audio_formats.h>
// #include <modules/juce_audio_processors/juce_audio_processors.h>
#include <modules/juce_core/juce_core.h>
// #include <modules/juce_cryptography/juce_cryptography.h>
// #include <modules/juce_data_structures/juce_data_structures.h>
// #include <modules/juce_events/juce_events.h>
// #include <modules/juce_graphics/juce_graphics.h>
#include <modules/juce_gui_basics/juce_gui_basics.h>
// #include <modules/juce_gui_extra/juce_gui_extra.h>
// #include <modules/juce_opengl/juce_opengl.h>
// #include <modules/juce_video/juce_video.h>
#include <base/base.hpp>

using namespace juce;
using namespace granite;

namespace ProjectInfo
{
    const char* const  projectName    = "Kiwano";
    const char* const  versionString  = "0.1";
    const int          versionNumber  = 0x10000;
}

class playlist : public Component, public FileDragAndDropTarget {
    struct playlistModel : public ListBoxModel {
		StringArray entries;
        int getNumRows() override {
            return entries.size();
        }

        void paintListBoxItem(int rowNumber, Graphics& g,
							  int width, int height, bool rowIsSelected) override {
            if (rowIsSelected)
                g.fillAll(Colours::lightblue);

            g.setColour(Colours::black);
            g.setFont(height * 0.7f);
			g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true);
        }
    };

    ListBox box;
    playlistModel model;
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist);

public:
    playlist() : box("playlist-box", nullptr) {
		setName("playlist");
		box.setModel(&model);
		box.setMultipleSelectionEnabled(true);
		addAndMakeVisible(box);
	}

    void resized() override {
		box.setBounds(getLocalBounds().reduced(0));
	}

	bool isInterestedInFileDrag(const StringArray& /*files*/) override {
		return true;
	}

	void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override {
		repaint();
	}

	void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {}

	void fileDragExit (const StringArray& /*files*/) override {
		repaint();
	}

	void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override {
		model.entries.addArray(files);
		box.updateContent();
		repaint();
	}
};

class tabs : public TabbedComponent {
public:
    tabs() : TabbedComponent(TabbedButtonBar::TabsAtTop) {
        addTab("Menus", getRandomTabBackgroundColour(), new playlist(), true);
        addTab("Buttons", getRandomTabBackgroundColour(), new playlist(), true);
    }

    static Colour getRandomTabBackgroundColour() {
        return Colour(Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f);
    }
};

class layout : public Component {
	StretchableLayoutManager l;
	StretchableLayoutResizerBar rb;
	std::vector<Component *> components;

public:
	layout(Component *c1, Component *c2) : rb(&l, 1, false) {
		setOpaque(true);
		addAndMakeVisible(rb);
		addAndMakeVisible(c1);
		addAndMakeVisible(c2);
		components.push_back(c1);
		components.push_back(&rb);
		components.push_back(c2);
		components.push_back(nullptr);
		l.setItemLayout(0, -0.1, -0.9, -0.5);
		l.setItemLayout(1, 5, 5, 5);
		l.setItemLayout(2, -0.1, -0.9, -0.5);
	}

	void paint(Graphics &g) override {
		g.setColour(Colour::greyLevel(0.2f));
		g.fillAll();
	}

	void resized() {
        Rectangle<int> r(getLocalBounds().reduced(4));
		l.layOutComponents(components.data(), 3, r.getX(), r.getY(), r.getWidth(), r.getHeight(), true, true);
	}
};

class KiwanoApplication : public JUCEApplication {
    class MainWindow : public DocumentWindow {
		layout l;
        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow)

    public:
        MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons),
			l(new tabs(), new tabs()) {
			setContentOwned(&l, false);
			setSize(800, 600);
            setVisible(true);
			setUsingNativeTitleBar(true);
			setResizable(true, true);
        }

        void closeButtonPressed() override {
            JUCEApplication::getInstance()->systemRequestedQuit();
        }
    };

    ScopedPointer<MainWindow> mainWindow;

public:
    KiwanoApplication() {}

    const String getApplicationName() override { return ProjectInfo::projectName; }
    const String getApplicationVersion() override { return ProjectInfo::versionString; }
    bool moreThanOneInstanceAllowed() override { return false; }

    void initialise(const String& commandLine) override {
        mainWindow = new MainWindow(getApplicationName());
    }

    void shutdown() override {
        mainWindow = nullptr;
    }

    void systemRequestedQuit() override {
        quit();
    }

    void anotherInstanceStarted (const String& commandLine) override {
    }
};

START_JUCE_APPLICATION(KiwanoApplication)
<commit_msg>+ GLISP integration<commit_after>#include <AppConfig.h>
// #include <modules/juce_audio_basics/juce_audio_basics.h>
// #include <modules/juce_audio_devices/juce_audio_devices.h>
// #include <modules/juce_audio_formats/juce_audio_formats.h>
// #include <modules/juce_audio_processors/juce_audio_processors.h>
#include <modules/juce_core/juce_core.h>
// #include <modules/juce_cryptography/juce_cryptography.h>
// #include <modules/juce_data_structures/juce_data_structures.h>
// #include <modules/juce_events/juce_events.h>
// #include <modules/juce_graphics/juce_graphics.h>
#include <modules/juce_gui_basics/juce_gui_basics.h>
// #include <modules/juce_gui_extra/juce_gui_extra.h>
// #include <modules/juce_opengl/juce_opengl.h>
// #include <modules/juce_video/juce_video.h>
#include <base/base.hpp>
#include <memory>

using namespace juce;
using namespace granite;

namespace ProjectInfo
{
    const char* const  projectName    = "Kiwano";
    const char* const  versionString  = "0.1";
    const int          versionNumber  = 0x10000;
}

class playlist : public Component, public FileDragAndDropTarget {
    struct playlistModel : public ListBoxModel {
		StringArray entries;
        int getNumRows() override {
            return entries.size();
        }

        void paintListBoxItem(int rowNumber, Graphics& g,
							  int width, int height, bool rowIsSelected) override {
            if (rowIsSelected)
                g.fillAll(Colours::lightblue);

            g.setColour(Colours::black);
            g.setFont(height * 0.7f);
			g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true);
        }
    };

    ListBox box;
    playlistModel model;
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist);

public:
    playlist() : box("playlist-box", nullptr) {
		setName("playlist");
		box.setModel(&model);
		box.setMultipleSelectionEnabled(true);
		addAndMakeVisible(box);
	}

    void resized() override {
		box.setBounds(getLocalBounds().reduced(0));
	}

	bool isInterestedInFileDrag(const StringArray& /*files*/) override {
		return true;
	}

	void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override {
		repaint();
	}

	void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {}

	void fileDragExit (const StringArray& /*files*/) override {
		repaint();
	}

	void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override {
		model.entries.addArray(files);
		box.updateContent();
		repaint();
	}
};

class tabs : public TabbedComponent {
public:
    tabs() : TabbedComponent(TabbedButtonBar::TabsAtTop) {
        addTab("Menus", getRandomTabBackgroundColour(), new playlist(), true);
        addTab("Buttons", getRandomTabBackgroundColour(), new playlist(), true);
    }

    static Colour getRandomTabBackgroundColour() {
        return Colour(Random::getSystemRandom().nextFloat(), 0.1f, 0.97f, 1.0f);
    }
};

class layout : public Component {
	StretchableLayoutManager l;
	std::vector<std::unique_ptr<Component>> components;
	std::vector<Component*> lc;
	bool horizontal;

public:
	layout(bool _horizontal) : horizontal(_horizontal){
		setOpaque(true);
	}

	void paint(Graphics &g) override {
		g.setColour(Colour::greyLevel(0.2f));
		g.fillAll();
	}

	void resized() override {
		juce::Rectangle<int> r(getLocalBounds());
		l.layOutComponents(lc.data(), lc.size(), r.getX(), r.getY(), r.getWidth(), r.getHeight(), !horizontal, true);
	}

	void addSplitter() {
		if (lc.size() > 0) {
			l.setItemLayout(lc.size(), 5, 5, 5);
			components.push_back(std::make_unique<StretchableLayoutResizerBar>(&l, lc.size(), horizontal));
			lc.push_back(components.back().get());
			addAndMakeVisible(components.back().get());
		}
	}

	void addComponent(Component *c, double minimum, double maximum, double preferred) {
		l.setItemLayout(lc.size(), minimum, maximum, preferred);
		lc.push_back(c);
		addAndMakeVisible(c);
	}
};

class interpreter : public Component,
					public TextEditor::Listener {
	base::lisp ≷
	TextEditor te;

public:
	interpreter(base::lisp &glisp) : gl(glisp) {
		te.setMultiLine(true);
		te.setReturnKeyStartsNewLine(false);
		te.setTabKeyUsedAsCharacter(false);
		te.setReadOnly(false);
		te.setCaretVisible(true);
		te.addListener(this);
		addAndMakeVisible(te);
	}
	~interpreter() {}

	void resized() override {
		te.setBounds(getLocalBounds());
	}

    void textEditorTextChanged(TextEditor&) override {}
    void textEditorEscapeKeyPressed(TextEditor&) override {}
    void textEditorFocusLost(TextEditor&) override {}

    void textEditorReturnKeyPressed(TextEditor&) override {
		// get line
		te.moveCaretToStartOfLine(false);
		int begin = te.getCaretPosition();
		te.moveCaretToEndOfLine(false);
		String t = te.getTextInRange(Range<int>(begin, te.getCaretPosition()));

		// execute code and print result
		std::string r = gl.eval(t.toStdString());
		te.insertTextAtCaret("\n > ");
		te.insertTextAtCaret(r);
		te.insertTextAtCaret("\n");
    }
};

class user_interface : public Component {
	std::map<std::string, std::unique_ptr<Component>> components;
	Component *mainComponent;
	base::lisp ≷

public:
	user_interface(base::lisp &glisp) : mainComponent(nullptr), gl(glisp) {}
	~user_interface() {}

	void resized() override {
		if (mainComponent)
			mainComponent->setBounds(getLocalBounds());
	}

	// (set-main-component name)
	base::cell_t set_main_component(base::cell_t c, base::cells_t &ret) {
		const auto &name = c + 1;
		auto cc = components.find(name->s);
		if (cc != components.end()) {
			mainComponent = cc->second.get();
			addAndMakeVisible(mainComponent);
			mainComponent->setBounds(getLocalBounds());
		}
		return c;
	}

	// (refresh-interface)
	base::cell_t refresh_interface(base::cell_t c, base::cells_t &ret) {
		if (mainComponent)
			mainComponent->resized();
		return c;
	}

	// (create-playlist name)
	base::cell_t create_playlist(base::cell_t c, base::cells_t &ret) {
		// TODO: error reporting
		const auto &name = c + 1;
		if (components.find(name->s) == components.end()) {
			components.insert(std::make_pair(name->s, std::make_unique<playlist>()));
		}
		return c;
	}

	// (create-layout name (bool)horizontal (bool)splitter)
	base::cell_t create_layout(base::cell_t c, base::cells_t &ret) {
		const auto &name = c + 1;
		const auto &horizontal = c + 2;
		if (components.find(name->s) == components.end()) {
			components.insert(std::make_pair(name->s, std::make_unique<layout>(horizontal->s != "nil")));
		}
		return c;
		// TODO: returning quoted ID
	}

	// (create-interpreter name)
	base::cell_t create_interpreter(base::cell_t c, base::cells_t &ret) {
		const auto &name = c + 1;
		if (components.find(name->s) == components.end()) {
			components.insert(std::make_pair(name->s, std::make_unique<interpreter>(gl)));
		}
		return c;
	}

	// (layout-add-component layout-id component-id (float)min (float)max (float)preffered)
	base::cell_t layout_add_component(base::cell_t c, base::cells_t &ret) {
		// TODO: expected format: list of 5, id, id, float, float, float
		const auto &lname = c + 1;
		const auto &cname = c + 2;
		auto l = components.find(lname->s);
		auto com = components.find(cname->s);
		if (l != components.end() && com != components.end()) {
			const auto &minimum = c + 3;
			const auto &maximum = c + 4;
			const auto &preferred = c + 5;
			layout *lay = reinterpret_cast<layout*>(l->second.get());
			lay->addComponent(com->second.get(), (double)minimum->f, (double)maximum->f, (double)preferred->f);
		}
		return c;
	}

	// (layout-add-splitter layout-id)
	base::cell_t layout_add_splitter(base::cell_t c, base::cells_t &ret) {
		const auto &lname = c + 1;
		auto l = components.find(lname->s);
		if (l != components.end()) {
			layout *lay = reinterpret_cast<layout*>(l->second.get());
			lay->addSplitter();
		}
		return c;
	}
};

class KiwanoApplication : public JUCEApplication {
    class MainWindow : public DocumentWindow {
		user_interface itf;
		base::lisp gl;
        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow)

		public:
		MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons),
			itf(gl) {
			setContentOwned(&itf, false);
			setSize(800, 600);
			setTopLeftPosition(200, 200);
            setVisible(true);
			setUsingNativeTitleBar(true);
			setResizable(true, true);

			// initialize GLISP
			using namespace std::placeholders;
			gl.init();
			gl.addProcedure("create-playlist", std::bind(&user_interface::create_playlist, &itf, _1, _2));
			gl.addProcedure("create-layout", std::bind(&user_interface::create_layout, &itf, _1, _2));
			gl.addProcedure("layout-add-component", std::bind(&user_interface::layout_add_component, &itf, _1, _2));
			gl.addProcedure("layout-add-splitter", std::bind(&user_interface::layout_add_splitter, &itf, _1, _2));
			gl.addProcedure("set-main-component", std::bind(&user_interface::set_main_component, &itf, _1, _2));
			gl.addProcedure("create-interpreter", std::bind(&user_interface::create_interpreter, &itf, _1, _2));
			gl.addProcedure("refresh-interface", std::bind(&user_interface::refresh_interface, &itf, _1, _2));
			gl.eval("(create-playlist 'p1)");
			gl.eval("(create-playlist 'p2)");
			gl.eval("(create-layout 'l1 t)");
			gl.eval("(layout-add-component 'l1 'p1 -0.1 -0.9 -0.5)");
			gl.eval("(layout-add-splitter 'l1)");
			gl.eval("(layout-add-component 'l1 'p2 -0.1 -0.9 -0.5)");
			gl.eval("(create-layout 'l2 nil)");
			gl.eval("(create-interpreter 'int1)");
			gl.eval("(layout-add-component 'l2 'int1 50.0 100.0 50.0)");
			gl.eval("(layout-add-splitter 'l2)");
			gl.eval("(layout-add-component 'l2 'l1 -0.1 -1.0 -0.9)");
			gl.eval("(set-main-component 'l2)");
        }

        void closeButtonPressed() override {
			gl.close();
            JUCEApplication::getInstance()->systemRequestedQuit();
        }
    };

    ScopedPointer<MainWindow> mainWindow;

public:
    KiwanoApplication() {}

    const String getApplicationName() override { return ProjectInfo::projectName; }
    const String getApplicationVersion() override { return ProjectInfo::versionString; }
    bool moreThanOneInstanceAllowed() override { return false; }

    void initialise(const String& commandLine) override {
        mainWindow = new MainWindow(getApplicationName());
    }

    void shutdown() override {
        mainWindow = nullptr;
    }

    void systemRequestedQuit() override {
        quit();
    }

    void anotherInstanceStarted (const String& commandLine) override {
    }
};

START_JUCE_APPLICATION(KiwanoApplication)
<|endoftext|>