<commit_before>/*-
 *   Copyright (C) 2008-2009 by Maxim Ignatenko
 *   gelraen.ua@gmail.com
 *
 *   All rights reserved.                                                  *
 *                                                                         *
 *   Redistribution and use in source and binary forms, with or without    *
 *    modification, are permitted provided that the following conditions   *
 *    are met:                                                             *
 *     * Redistributions of source code must retain the above copyright    *
 *       notice, this list of conditions and the following disclaimer.     *
 *     * Redistributions in binary form must reproduce the above copyright *
 *       notice, this list of conditions and the following disclaimer in   *
 *       the documentation and/or other materials provided with the        *
 *       distribution.                                                     *
 *                                                                         *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   *
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     *
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  *
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      *
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
 *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   *
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  *
 *
 *  $Id$
 */

#include "defs.h"

#include <iostream>
#include <translator.h>
#include <config.h>
#include <dcclient.h>
#include <ircclient.h>
#include <sys/select.h>
#include <unistd.h>
#include <fcntl.h>
#include "../config.h"
#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <sys/stat.h>

using namespace std;

void usage();
void version();
bool writepid(const string& pidfile);

int main(int argc,char *argv[])
{
	Config conf;
	Translator trans;
	IRCClient irc;
	DCClient dc;

	string conffile=CONFFILE;
	string pidfile;
	bool daemonize=true;
	string logfile;
	int loglevel;
	bool bloglevel=false; // specified in command line?

	if (argc==1)
	{
		usage();
		return 0;
	}

	char ch;
	while((ch = getopt(argc, argv, "dc:l:L:p:h")) != -1) {
		switch (ch) {
			case 'd':
				daemonize=false;
				break;
			case 'c':
				conffile=optarg;
				break;
			case 'l':
				logfile=optarg;
				break;
			case 'L':
				bloglevel=true;
				loglevel=(int)strtol(optarg, (char **)NULL, 10);
				break;
			case 'p':
				pidfile=optarg;
				break;
			case 'h':
			case '?':
			default:
				usage();
				return(0);
		}
	}

	if (!conf.ReadFromFile(conffile))
	{
		LOG(log::error, "Failed to load config. Exiting", true);
		return 1;
	}

	LogLevel= bloglevel ? loglevel : conf.m_loglevel;

	if(!logfile.empty())
	if(dup2(open(logfile.c_str(), O_APPEND | O_CREAT, S_IRWXU | S_IRWXG),2)==-1)
		LOG(log::warning, "Failed to open log file. Continue logging to old stderr", true);

	if (!logfile.empty())
	{
		conf.m_sLogFile=logfile;
	}

	if (!pidfile.empty())
	{
		conf.m_pidfile=pidfile;
	}

	if (daemonize)
	{
		if (daemon(0,0)==-1) // chdir to '/' and close fd's 0-2
		{
			LOG(log::error, "daemon() failed, exiting", true);
			return 1;
		}
	}

	if (!conf.m_pidfile.empty()&&!writepid(conf.m_pidfile))
	{
		LOG(log::error,"Unable to write pidfile", true);
	}

	if (!irc.setConfig(conf))
	{
		LOG(log::error,"Incorrect config for IRC", true);
		return 1;
	}
	if (!dc.setConfig(conf))
	{
		LOG(log::error,"Incorrect config for DC++", true);
		return 1;
	}

	string str;

	LOG(log::notice,"Connecting to IRC... ");
	if (!irc.Connect())
	{
		LOG(log::error,"ERROR");
		return 2;
	} else LOG(log::notice,"OK");

	LOG(log::notice,"Connecting to DC++... ");
	if (!dc.Connect())
	{
		LOG(log::error,"ERROR");
		return 2;
	} else LOG(log::notice,"OK");

	// now recreate config, cause DC hub may change our nickname
	conf=Config(irc.getConfig(),dc.getConfig());

	if (!trans.setConfig(conf))
	{
		LOG(log::error,"Incorrect config for Translator");
		return 1;
	}

	fd_set rset;
	int max=0,t;

	for(;;)
	{
		// recreate rset
		FD_ZERO(&rset);

		t=irc.FdSet(rset);
		max=(t>max)?t:max;

		t=dc.FdSet(rset);
		max=(t>max)?t:max;

		select(max+1,&rset,NULL,NULL,NULL);

		while(irc.readCommand(str))
		{
			if (trans.IRCtoDC(str,str))
			{
				dc.writeCommand(str);
			}
		}
		if (!dc.isLoggedIn())
		{
			LOG(log::warning, "DC++ connection closed. Trying to reconnect...");
			dc.Connect();
		}

		while(dc.readCommand(str))
		{
			if (trans.DCtoIRC(str,str))
			{
				irc.writeCommand(str);
			}
		}
		if (!irc.isLoggedIn())
		{
			LOG(log::warning,"IRC connection closed. Trying to reconnect...");
			irc.Connect();
		}
	}

	return 0;
}

void usage()
{
	version();
	cout << endl;
	cout << "Options:" << endl;
	cout << "   -h      - show this help message" << endl;
	cout << "   -c file - specify path to config file" << endl;
	cout << "   -l file - override path to logfile specified in config" << endl;
	cout << "   -L num  - override loglevel" << endl;
	cout << "   -p file - override path to pidfile specified in config" << endl;
	cout << "   -d      - do not go in background, all logging goes to stderr" << endl;
	cout << endl;
}

void version()
{
	cout << PACKAGE << " " << VERSION << endl;
}

bool writepid(const string& pidfile)
{
	ofstream pid(pidfile.c_str());
	if (pid.bad()) return false;
	pid << getpid() << endl;
	return true;
}
<commit_msg>Reopen file at stderr only after successful daemon(3) call<commit_after>/*-
 *   Copyright (C) 2008-2009 by Maxim Ignatenko
 *   gelraen.ua@gmail.com
 *
 *   All rights reserved.                                                  *
 *                                                                         *
 *   Redistribution and use in source and binary forms, with or without    *
 *    modification, are permitted provided that the following conditions   *
 *    are met:                                                             *
 *     * Redistributions of source code must retain the above copyright    *
 *       notice, this list of conditions and the following disclaimer.     *
 *     * Redistributions in binary form must reproduce the above copyright *
 *       notice, this list of conditions and the following disclaimer in   *
 *       the documentation and/or other materials provided with the        *
 *       distribution.                                                     *
 *                                                                         *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   *
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     *
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  *
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      *
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
 *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   *
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  *
 *
 *  $Id$
 */

#include "defs.h"

#include <iostream>
#include <translator.h>
#include <config.h>
#include <dcclient.h>
#include <ircclient.h>
#include <sys/select.h>
#include <unistd.h>
#include <fcntl.h>
#include "../config.h"
#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <sys/stat.h>

using namespace std;

void usage();
void version();
bool writepid(const string& pidfile);

int main(int argc,char *argv[])
{
	Config conf;
	Translator trans;
	IRCClient irc;
	DCClient dc;

	string conffile=CONFFILE;
	string pidfile;
	bool daemonize=true;
	string logfile;
	int loglevel;
	bool bloglevel=false; // specified in command line?

	if (argc==1)
	{
		usage();
		return 0;
	}

	char ch;
	while((ch = getopt(argc, argv, "dc:l:L:p:h")) != -1) {
		switch (ch) {
			case 'd':
				daemonize=false;
				break;
			case 'c':
				conffile=optarg;
				break;
			case 'l':
				logfile=optarg;
				break;
			case 'L':
				bloglevel=true;
				loglevel=(int)strtol(optarg, (char **)NULL, 10);
				break;
			case 'p':
				pidfile=optarg;
				break;
			case 'h':
			case '?':
			default:
				usage();
				return(0);
		}
	}

	if (!conf.ReadFromFile(conffile))
	{
		LOG(log::error, "Failed to load config. Exiting", true);
		return 1;
	}

	LogLevel= bloglevel ? loglevel : conf.m_loglevel;

	if (!logfile.empty())
	{
		conf.m_sLogFile=logfile;
	}

	if (!pidfile.empty())
	{
		conf.m_pidfile=pidfile;
	}

	if (daemonize)
	{
		if (daemon(0,0)==-1) // chdir to '/' and close fd's 0-2
		{
			LOG(log::error, "daemon() failed, exiting", true);
			return 1;
		}

		if (dup2(open(conf.m_sLogFile.c_str(),
					  O_APPEND | O_CREAT,
	    			  S_IRWXU | S_IRWXG),2)==-1)
		{
			LOG(log::warning, "Failed to open log file. Continue logging to stderr", true);
		}
	}

	if (!conf.m_pidfile.empty()&&!writepid(conf.m_pidfile))
	{
		LOG(log::error,"Unable to write pidfile", true);
	}

	if (!irc.setConfig(conf))
	{
		LOG(log::error,"Incorrect config for IRC", true);
		return 1;
	}
	if (!dc.setConfig(conf))
	{
		LOG(log::error,"Incorrect config for DC++", true);
		return 1;
	}

	string str;

	LOG(log::notice,"Connecting to IRC... ");
	if (!irc.Connect())
	{
		LOG(log::error,"ERROR");
		return 2;
	} else LOG(log::notice,"OK");

	LOG(log::notice,"Connecting to DC++... ");
	if (!dc.Connect())
	{
		LOG(log::error,"ERROR");
		return 2;
	} else LOG(log::notice,"OK");

	// now recreate config, cause DC hub may change our nickname
	conf=Config(irc.getConfig(),dc.getConfig());

	if (!trans.setConfig(conf))
	{
		LOG(log::error,"Incorrect config for Translator");
		return 1;
	}

	fd_set rset;
	int max=0,t;

	for(;;)
	{
		// recreate rset
		FD_ZERO(&rset);

		t=irc.FdSet(rset);
		max=(t>max)?t:max;

		t=dc.FdSet(rset);
		max=(t>max)?t:max;

		select(max+1,&rset,NULL,NULL,NULL);

		while(irc.readCommand(str))
		{
			if (trans.IRCtoDC(str,str))
			{
				dc.writeCommand(str);
			}
		}
		if (!dc.isLoggedIn())
		{
			LOG(log::warning, "DC++ connection closed. Trying to reconnect...");
			dc.Connect();
		}

		while(dc.readCommand(str))
		{
			if (trans.DCtoIRC(str,str))
			{
				irc.writeCommand(str);
			}
		}
		if (!irc.isLoggedIn())
		{
			LOG(log::warning,"IRC connection closed. Trying to reconnect...");
			irc.Connect();
		}
	}

	return 0;
}

void usage()
{
	version();
	cout << endl;
	cout << "Options:" << endl;
	cout << "   -h      - show this help message" << endl;
	cout << "   -c file - specify path to config file" << endl;
	cout << "   -l file - override path to logfile specified in config" << endl;
	cout << "   -L num  - override loglevel" << endl;
	cout << "   -p file - override path to pidfile specified in config" << endl;
	cout << "   -d      - do not go in background, all logging goes to stderr" << endl;
	cout << endl;
}

void version()
{
	cout << PACKAGE << " " << VERSION << endl;
}

bool writepid(const string& pidfile)
{
	ofstream pid(pidfile.c_str());
	if (pid.bad()) return false;
	pid << getpid() << endl;
	return true;
}
<|endoftext|>


<commit_before>#include <Refal2.h>

using namespace Refal2;

typedef std::vector<std::string> CFileNames;

class CSourceFilesProcessor : private IErrorHandler {
public:
	static CProgramPtr Compile( const CFileNames& fileNames );
	static bool Check( const CFileNames& fileNames );

private:
	CScanner scanner;
	std::ifstream file;

	CSourceFilesProcessor( const CFileNames& fileNames );
	CSourceFilesProcessor( const CSourceFilesProcessor& );
	CSourceFilesProcessor& operator=( const CSourceFilesProcessor& );

	void processFile( const std::string& fileName );

	virtual void Error( const CError& error );
};

CProgramPtr CSourceFilesProcessor::Compile( const CFileNames& fileNames )
{
	CSourceFilesProcessor sourceFilesProcessor( fileNames );
	return sourceFilesProcessor.scanner.BuildProgram();
}

bool CSourceFilesProcessor::Check( const CFileNames& fileNames )
{
	CSourceFilesProcessor sourceFilesProcessor( fileNames );
	return sourceFilesProcessor.scanner.CheckProgram();
}

CSourceFilesProcessor::CSourceFilesProcessor( const CFileNames& fileNames )
{
	scanner.SetErrorHandler( this );
	if( fileNames.empty() ) {
		for( char c; std::cin.get( c ); ) {
			scanner.AddChar( c );
		}
		if( scanner.ErrorSeverity() != ES_FatalError ) {
			scanner.AddEndOfFile();
		}
	} else {
		for( CFileNames::const_iterator fileName = fileNames.begin();
			fileName != fileNames.end(); ++fileName )
		{
			processFile( *fileName );
			if( scanner.ErrorSeverity() == ES_FatalError ) {
				break;
			}
		}
	}
}

void CSourceFilesProcessor::processFile( const std::string& fileName )
{
	file.open( fileName );
	if( file.good() ) {
		scanner.SetFileName( fileName );
		for( char c; file.get( c ); ) {
			scanner.AddChar( c );
		}
		if( scanner.ErrorSeverity() != ES_FatalError ) {
			scanner.AddEndOfFile();
		}
	} else {
		std::cerr << UtilityName << ": " << fileName
			<< ": No such file" << std::endl;
	}
}

void CSourceFilesProcessor::Error( const CError& error )
{
	std::cerr << error.UserMessage() << std::endl;
	if( error.Severity() == ES_FatalError ) {
		file.clear( std::ios_base::eofbit );
		std::cin.clear( std::ios_base::eofbit );
	}
}

const char* const ExecutionResultStrings[] = {
	"ok",
	"recognition impossible",
	"call empty function",
	"lost function label",
	"wrong argument of embedded function"
};

const std::string SeparatorLine( 80, '-' );

int main( int argc, const char* argv[] )
{
	std::ios::sync_with_stdio( false );

	CFileNames fileNames;
	for( int i = 1; i < argc; i++ ) {
		fileNames.push_back( argv[i] );
	}

	CProgramPtr program = CSourceFilesProcessor::Compile( fileNames );
	if( !static_cast<bool>( program ) ) {
		return 1;
	}

	CReceptaclePtr receptacle( new CReceptacle );
	CUnitList fieldOfView;
	CUnitNode* errorNode;
	TExecutionResult result =
		COperationsExecuter::Run( program, receptacle, fieldOfView, errorNode );

	std::cout << SeparatorLine << std::endl;
	std::cout << "Execution result: "
		<< ExecutionResultStrings[result] << "." << std::endl;
	if( !fieldOfView.IsEmpty() ) {
		std::cout << "Field of view: " << std::endl;
		CProgramPrintHelper programPrintHelper( program );
		//programPrintHelper.SetPrintLabelWithModule();
		fieldOfView.HandyPrint( std::cout, programPrintHelper );
	}
	if( !receptacle->IsEmpty() ) {
		if( !fieldOfView.IsEmpty() ) {
			std::cout << SeparatorLine << std::endl;
		}
		std::cout << "Receptacle: " << std::endl;
		CUnitList receptacleUnitList;
		receptacle->DigOutAll( receptacleUnitList );
		CProgramPrintHelper programPrintHelper( program );
		receptacleUnitList.HandyPrint( std::cout, programPrintHelper );
		std::cout << std::endl;
	}
	return 0;
}
<commit_msg>add command line options<commit_after>#include <Refal2.h>

using namespace Refal2;

//-----------------------------------------------------------------------------
// Constants

const char* const UtilityName = "refal2";

//-----------------------------------------------------------------------------
// CCommandLineOptions

typedef std::vector<std::string> CFileNames;

class CCommandLineOptions {
public:
	CCommandLineOptions() { ResetDefaults(); }

	void ResetDefaults();
	bool SetByCommandLineArguments( int numberOfArguments,
		const char* const arguments[] );

	bool IsCheckOnly() const { return isCheckOnly; }
	void SetCheckOnly( bool _isCheckOnly = true )
		{ isCheckOnly = _isCheckOnly; }

	bool IsInfoOnly() const { return isInfoOnly; }
	void SetInfoOnly( bool _isInfoOnly = true ) { isInfoOnly = _isInfoOnly; }

	void ResetSourceFiles() { sourceFiles.clear(); }
	bool HasSourceFiles() const { return !sourceFiles.empty(); }
	CFileNames SourceFiles() const { return sourceFiles; }
	void AddSourceFile( const std::string& fileName )
		{ sourceFiles.push_back( fileName ); }

private:
	bool isInfoOnly;
	bool optionsEnd;
	// if true program only parse and print found errors
	bool isCheckOnly;
	// *.ref files
	CFileNames sourceFiles;

	static bool isOption( const std::string& argument );
	bool parseArgument( const std::string& argument );

	static void printInvalidOption( const std::string& argument );
	static void printHelp();
	static void printVersion();
};

//-----------------------------------------------------------------------------

void CCommandLineOptions::ResetDefaults()
{
	SetInfoOnly( false );
	SetCheckOnly( false );
	ResetSourceFiles();
}

bool CCommandLineOptions::SetByCommandLineArguments( int numberOfArguments,
	const char* const arguments[] )
{
	ResetDefaults();
	optionsEnd = false;
	for( int i = 0; i < numberOfArguments; i++ ) {
		if( !parseArgument( arguments[i] ) ) {
			ResetDefaults();
			return false;
		}
		if( IsInfoOnly() ) {
			break;
		}
	}
	return true;
}

bool CCommandLineOptions::isOption( const std::string& argument )
{
	return ( argument.length() >= 2 && argument.front() == '-' );
}

bool CCommandLineOptions::parseArgument( const std::string& argument )
{
	if( !optionsEnd && isOption( argument ) ) {
		if( argument == "-c" || argument == "--check" ) {
			SetCheckOnly();
		} else if( argument == "--help" ) {
			SetInfoOnly();
			printHelp();
		} else if( argument == "--version" ) {
			SetInfoOnly();
			printVersion();
		} else if( argument == "--" ) {
			optionsEnd = true;
		} else {
			printInvalidOption( argument );
			return false;
		}
	} else if( !argument.empty() ) {
		AddSourceFile( argument );
	}
	return true;
}

void CCommandLineOptions::printInvalidOption( const std::string& argument )
{
	std::cerr
		<< UtilityName << ": invalid option `" << argument << "`" << std::endl
		<< "Try `" << UtilityName << " --help` for more information."
		<< std::endl;
}

void CCommandLineOptions::printHelp()
{
	std::cout
		<< "Usage: " << UtilityName << " [OPTION]... [FILE]..."
		<< std::endl << std::endl
		<< "  -c, --check      check source FILE(s) for errors and exit"
		<< std::endl
		<< "      --help       display this help and exit" << std::endl
		<< "      --version    output version information and exit"
		<< std::endl << std::endl << "Report bugs to <refal2@yandex.ru>."
		<< std::endl;
}

void CCommandLineOptions::printVersion()
{
	std::cout
		<< "Written by Anton Todua." << std::endl
		<< "Report bugs to <refal2@yandex.ru>" << std::endl;
}

//-----------------------------------------------------------------------------
// CSourceFilesProcessor

class CSourceFilesProcessor : private IErrorHandler {
public:
	static CProgramPtr Compile( const CFileNames& fileNames );
	static bool Check( const CFileNames& fileNames );

private:
	CScanner scanner;
	std::ifstream file;

	CSourceFilesProcessor( const CFileNames& fileNames );
	CSourceFilesProcessor( const CSourceFilesProcessor& );
	CSourceFilesProcessor& operator=( const CSourceFilesProcessor& );

	void processFile( const std::string& fileName );

	virtual void Error( const CError& error );
};

//-----------------------------------------------------------------------------

CProgramPtr CSourceFilesProcessor::Compile( const CFileNames& fileNames )
{
	CSourceFilesProcessor sourceFilesProcessor( fileNames );
	return sourceFilesProcessor.scanner.BuildProgram();
}

bool CSourceFilesProcessor::Check( const CFileNames& fileNames )
{
	CSourceFilesProcessor sourceFilesProcessor( fileNames );
	return sourceFilesProcessor.scanner.CheckProgram();
}

CSourceFilesProcessor::CSourceFilesProcessor( const CFileNames& fileNames )
{
	scanner.SetErrorHandler( this );
	if( fileNames.empty() ) {
		for( char c; std::cin.get( c ); ) {
			scanner.AddChar( c );
		}
		if( scanner.ErrorSeverity() != ES_FatalError ) {
			scanner.AddEndOfFile();
		}
	} else {
		for( CFileNames::const_iterator fileName = fileNames.begin();
			fileName != fileNames.end(); ++fileName )
		{
			processFile( *fileName );
			if( scanner.ErrorSeverity() == ES_FatalError ) {
				break;
			}
		}
	}
}

void CSourceFilesProcessor::processFile( const std::string& fileName )
{
	file.open( fileName );
	if( file.good() ) {
		scanner.SetFileName( fileName );
		for( char c; file.get( c ); ) {
			scanner.AddChar( c );
		}
		if( scanner.ErrorSeverity() != ES_FatalError ) {
			scanner.AddEndOfFile();
		}
	} else {
		scanner.SetFileName( UtilityName );
		scanner.RaiseError( ES_FatalError, "no such file" );
		scanner.ResetFileName();
	}
}

void CSourceFilesProcessor::Error( const CError& error )
{
	std::cerr << error.UserMessage() << std::endl;
	if( error.Severity() == ES_FatalError ) {
		file.clear( std::ios_base::eofbit );
		std::cin.clear( std::ios_base::eofbit );
	}
}

//-----------------------------------------------------------------------------

const char* const ExecutionResultStrings[] = {
	"ok",
	"recognition impossible",
	"call empty function",
	"lost function label",
	"wrong argument of embedded function"
};

const std::string SeparatorLine( 80, '-' );

int main( int argc, const char* argv[] )
{
	std::ios::sync_with_stdio( false );

	CCommandLineOptions commandLineOptions;
	if( !commandLineOptions.SetByCommandLineArguments( argc - 1, argv + 1 ) ) {
		return 1;
	}

	if( commandLineOptions.IsInfoOnly() ) {
		return 0;
	}

	if( commandLineOptions.IsCheckOnly() ) {
		return ( CSourceFilesProcessor::Check(
			commandLineOptions.SourceFiles() ) ? 0 : 1 );
	}

	CProgramPtr program = CSourceFilesProcessor::Compile(
		commandLineOptions.SourceFiles() );
	if( !static_cast<bool>( program ) ) {
		return 1;
	}

	CReceptaclePtr receptacle( new CReceptacle );
	CUnitList fieldOfView;
	CUnitNode* errorNode;
	TExecutionResult result =
		COperationsExecuter::Run( program, receptacle, fieldOfView, errorNode );

	std::cout << SeparatorLine << std::endl;
	std::cout << "Execution result: "
		<< ExecutionResultStrings[result] << "." << std::endl;
	if( !fieldOfView.IsEmpty() ) {
		std::cout << "Field of view: " << std::endl;
		CProgramPrintHelper programPrintHelper( program );
		//programPrintHelper.SetPrintLabelWithModule();
		fieldOfView.HandyPrint( std::cout, programPrintHelper );
	}
	if( !receptacle->IsEmpty() ) {
		if( !fieldOfView.IsEmpty() ) {
			std::cout << SeparatorLine << std::endl;
		}
		std::cout << "Receptacle: " << std::endl;
		CUnitList receptacleUnitList;
		receptacle->DigOutAll( receptacleUnitList );
		CProgramPrintHelper programPrintHelper( program );
		receptacleUnitList.HandyPrint( std::cout, programPrintHelper );
		std::cout << std::endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include <logging/Logger.h>
#include <graphics/GlfwContext.h>
#include <graphics/GlfwWindow.h>
#include <graphics/Renderer.h>
#include <gamemodel/GameState.h>
#include <input/Input.h>

int main(int argc, char ** argv) {
	Logger::initSystem(argc, argv);

	GlfwContext glfwContext(Logger::glfwErrorCallback);
	GlfwWindow glfwWindow(1200, 800);

	GameState gameState;
	Input input(gameState);
	Renderer renderer(glfwWindow, gameState);

	glfwWindow.makeCurrent();
	glfwWindow.setKeyCallback(input.handleKeyboardFcnPtr);
	glfwWindow.enterMainLoop([&] {

		const double t = glfwGetTime();

		input.update(t);
		gameState.update(t);
		renderer.draw(t);

		return t < 5.0;
	});

	return 0;
}
<commit_msg>empty commit to see if git email is linked properly<commit_after>#include <logging/Logger.h>
#include <graphics/GlfwContext.h>
#include <graphics/GlfwWindow.h>
#include <graphics/Renderer.h>
#include <gamemodel/GameState.h>
#include <input/Input.h>

int main(int argc, char ** argv) {
	Logger::initSystem(argc, argv);

	GlfwContext glfwContext(Logger::glfwErrorCallback);
	GlfwWindow glfwWindow(1200, 800);

	GameState gameState;
	Input input(gameState);
	Renderer renderer(glfwWindow, gameState);

	glfwWindow.makeCurrent();
	glfwWindow.setKeyCallback(input.handleKeyboardFcnPtr);
	glfwWindow.enterMainLoop([&] {

		const double t = glfwGetTime();

		input.update(t);
		gameState.update(t);
		renderer.draw(t);

		return t < 5.0;
	});

	return 0;
}
<|endoftext|>


<commit_before>#include "global.hpp"

using namespace std;

static char* exe;
static void usagemode() {
  printf(
    "Usage mode: %s <option>\n"
    "\n"
    "Options:\n"
    "  install <new directory name without trailing slash>\n"
    "  start\n"
    "  stop\n"
    "  restart (just a stop followed by a start)\n"
    "  reload (reload all settings except webserver)\n"
    "  rerun-id <attempt id>\n"
    "  rerun-atts <list of problem names>\n"
    "  rerun-all-atts [list of problem names to skip]\n",
    exe
  );
}

int main(int argc, char** argv) {
  exe = argv[0];
  if (argc == 1) { usagemode(); return 0; }
  string mode = argv[1];
  if (mode == "install") {
    if (argc == 2) { usagemode(); return 0; }
    Global::install(argv[2]);
  }
  else if (mode == "start") {
    Global::start();
  }
  else if (mode == "stop") {
    Global::stop();
  }
  else if (mode == "restart") {
    Global::stop();
    Global::start();
  }
  else if (mode == "reload") {
    Global::reload();
  }
  else usagemode();
  return 0;
}
<commit_msg>Update usage mode<commit_after>#include "global.hpp"

using namespace std;

static char* exe;
static void usagemode() {
  printf(
    "Usage mode: %s <option>\n"
    "\n"
    "Installation option:\n"
    "  install <non-existing directory path>\n"
    "\n"
    "The following options must be executed inside a directory created with\n"
    "the 'install' option.\n"
    "\n"
    "Offline options:\n"
    "  start\n"
    "\n"
    "Online options:\n"
    "  stop\n"
    "  restart (stop followed by start)\n"
    "  reload (just reload all settings except webserver's)\n"
    "  rerun-att <attempt id>\n"
    "  rerun-probs <list of problem id ranges> (* reruns ALL attempts)\n"
    "    Example to rerun problems 1, 3, 4 and 5: %s rerun-probs 1 3-5\n",
    exe,exe
  );
}

int main(int argc, char** argv) {
  exe = argv[0];
  if (argc == 1) { usagemode(); return 0; }
  string mode = argv[1];
  if (mode == "install") {
    if (argc == 2) { usagemode(); return 0; }
    Global::install(argv[2]);
  }
  else if (mode == "start") {
    Global::start();
  }
  else if (mode == "stop") {
    Global::stop();
  }
  else if (mode == "restart") {
    Global::stop();
    Global::start();
  }
  else if (mode == "reload") {
    Global::reload();
  }
  else usagemode();
  return 0;
}
<|endoftext|>


<commit_before>#include <gst/gst.h>
#include <glib.h>

// Message handler callback
static gboolean
bus_call (GstBus     *bus,
          GstMessage *msg,
          gpointer    data)
{
  GMainLoop *loop = (GMainLoop *) data;

  switch (GST_MESSAGE_TYPE (msg)) {

    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;

    case GST_MESSAGE_ERROR: {
      gchar  *debug;
      GError *error;

      gst_message_parse_error (msg, &error, &debug);
      g_free (debug);

      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}

int
main (int   argc,
      char *argv[])
{
  GMainLoop *loop;

  GstElement *pipeline, *source, *parser, *decoder, *conv, *sink;
  GstBus *bus;
  guint bus_watch_id;

  /* Initialisation */
  gst_init (&argc, &argv);

  loop = g_main_loop_new (NULL, FALSE);

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new("mp3_player");
  source   = gst_element_factory_make ("filesrc",       "file-source");
  parser   = gst_element_factory_make ("mpegaudioparse", "parser");
  decoder  = gst_element_factory_make ("mpg123audiodec",     "auto-decoder");
  conv     = gst_element_factory_make ("audioconvert",  "converter");
  sink     = gst_element_factory_make ("pulsesink", "audio-output");

  if (!pipeline || !source || !parser || !decoder || !conv ||!sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Set up the pipeline */

  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (source), "location",
		"../../media/music/Tours_-_01_-_Enthusiast.mp3", NULL);

  // Message handler
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  // Add elements to pipeline
  gst_bin_add_many (GST_BIN(pipeline), source, parser, decoder, conv, sink, NULL);

  // Link the elements together
  gst_element_link_many(source, parser, decoder, conv, sink, NULL);

  // Set pipeline to playing
  g_print ("Now playing: %s\n", "default");
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  // Loop
  g_print ("Running...\n");
  g_main_loop_run (loop);

  // Deinitialization
  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipeline));
  g_source_remove (bus_watch_id);
  g_main_loop_unref (loop);

  return 0;
}
<commit_msg>Use custom main loop<commit_after>#include <gst/gst.h>
#include <glib.h>

int
main (int   argc,
      char *argv[])
{
  //GMainLoop *loop;
  bool terminate=false;
  GstMessage *msg;

  GstElement *pipeline, *source, *parser, *decoder, *conv, *sink;
  GstBus *bus;
  //guint bus_watch_id;

  /* Initialisation */
  gst_init (&argc, &argv);

  //loop = g_main_loop_new (NULL, FALSE);

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new("mp3_player");
  source   = gst_element_factory_make ("filesrc",       "file-source");
  parser   = gst_element_factory_make ("mpegaudioparse", "parser");
  decoder  = gst_element_factory_make ("mpg123audiodec",     "auto-decoder");
  conv     = gst_element_factory_make ("audioconvert",  "converter");
  sink     = gst_element_factory_make ("pulsesink", "audio-output");

  if (!pipeline || !source || !parser || !decoder || !conv ||!sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Set up the pipeline */

  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (source), "location",
		"../../media/music/Tours_-_01_-_Enthusiast.mp3", NULL);

  // Add elements to pipeline
  gst_bin_add_many (GST_BIN(pipeline), source, parser, decoder, conv, sink, NULL);

  // Link the elements together
  gst_element_link_many(source, parser, decoder, conv, sink, NULL);

  // Set pipeline to playing
  g_print ("Now playing: %s\n", "default");
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  // Loop---------------------------------------------
  g_print ("Running...\n");
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  do {
    // Pop one by one
    msg = gst_bus_timed_pop (bus, GST_CLOCK_TIME_NONE);

    /* Parse message */
    if (msg != NULL) {
      GError *err;
      gchar *debug_info;

      switch (GST_MESSAGE_TYPE (msg)) {
      case GST_MESSAGE_ERROR:
	gst_message_parse_error (msg, &err, &debug_info);
	g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
	g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
	g_clear_error (&err);
	g_free (debug_info);
	terminate = true;
	break;
      case GST_MESSAGE_EOS:
	g_print ("End-Of-Stream reached.\n");
	terminate = true;
	break;
      case GST_MESSAGE_STATE_CHANGED:
	/* We are only interested in state-changed messages from the pipeline */
	if (GST_MESSAGE_SRC (msg) == GST_OBJECT (pipeline)) {
	  GstState old_state, new_state, pending_state;
	  gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
	  g_print ("Pipeline state changed from %s to %s:\n",
		   gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
	}
	break;
      default:
	// Do not handle any other message
	g_printerr ("INFO: unhandled message\n");
	break;
      }
      gst_message_unref (msg);
    }
  } while (!terminate);

  // Deinitialization
  g_print ("Returned, stopping playback\n");
  gst_object_unref (bus);
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipeline));

  return 0;
}
<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>
#include <ctime>

#include "qpp.h"
#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping

using namespace std;

using namespace qpp;
using namespace qpp::types;

int myfunc(const cplx &z)
{
	return std::abs(z);
}

//int main(int argc, char **argv)
int main()
{
	_init();

//	std::cout << std::fixed; // use fixed format for nice formatting
////	std::cout << std::scientific;
//	std::cout << std::setprecision(4); // only for fixed or scientific modes
//
//	cout << "Starting qpp..." << endl;
//
//	// MATLAB interface testing
//	cmat randu = rand_unitary(3);
//	cout << endl;
//	displn(randu);
//
//	saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w");
//	cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu");
//	cout << endl;
//	displn(randu - res);
//
//	// functor testing
//	auto lambda = [](const cplx& z)->int
//	{	return abs(z);};
//
//	cmat mat1(3, 3);
//	mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii;
//
//	cout << endl;
//	displn(mat1);
//
//	cout << endl;
//	displn(fun<cmat, int>(mat1 * mat1, lambda));
//
//	cout << endl;
//	displn(fun(mat1 * mat1, myfunc));
//
//	// other functions
//	cout << endl;
//	cmat mat11 = mat1 * mat1;
//	displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1)));
//
//	mat11 = cmat::Random(3, 3);
//	mat11 = mat11 + adjoint(mat11);
//	cmat mat2(2, 2);
//	mat2 << 1, ct::ii, -ct::ii, 1;
//	// eigenvalue test
//	cout << endl << hevals<cmat>(mat11) << endl;
//	displn(
//			mat11 * hevects(mat11).col(0)
//					- (hevals(mat11)(0)) * hevects(mat11).col(0));
//
//	cout << endl << mat11 << endl << endl;
//
//	cout << endl;
//	displn(transpose(mat11));
//	cout << typeid(transpose(mat11)).name() << endl<<endl;
//
//	displn(transpose(mat11 * mat11));
//	cout << typeid(transpose(mat11*mat11)).name() << endl;
//
//	cout<<endl;
//	displn(kron_list<cmat>({gt::X*gt::X,gt::X+gt::X}));
//
//	cout<<endl;
//	displn(kron_pow(gt::X*gt::X,2));
//
//	cout<<endl;
//	displn(kron(gt::X*gt::X,gt::X+gt::X));

	size_t N = 5000;
	cmat test = cmat::Random(N, N);

	// measure time taken

	clock_t start, end;
	double time;
	start = clock();

	/* process starts here */

	norm(reshape(test, 1, N * N));

	/* process ends here */
	end = clock();

	time = (double) (end - start);
	cout << "It took me " << time << " clicks ("
			<< ((float) time) / CLOCKS_PER_SEC << " seconds).";
	cout << endl << "Exiting qpp..." << endl;
}
<commit_msg>commit<commit_after>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>
#include <ctime>

#include "qpp.h"
//#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping

using namespace std;

using namespace qpp;
using namespace qpp::types;

int myfunc(const cplx &z)
{
	return std::abs(z);
}

//int main(int argc, char **argv)
int main()
{
	_init();

	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	// MATLAB interface testing
	cmat randu = rand_unitary(3);
	cout << endl;
	displn(randu);

	//saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w");
	//cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu");
	cout << endl;
	//displn(randu - res);

	// functor testing
	auto lambda = [](const cplx& z)->int
	{	return abs(z);};

	cmat mat1(3, 3);
	mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii;

	cout << endl;
	displn(mat1);

	cout << endl;
	displn(fun<cmat, int>(mat1 * mat1, lambda));

	cout << endl;
	displn(fun(mat1 * mat1, myfunc));

	// other functions
	cout << endl;
	cmat mat11 = mat1 * mat1;
	displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1)));

	mat11 = cmat::Random(3, 3);
	mat11 = mat11 + adjoint(mat11);
	cmat mat2(2, 2);
	mat2 << 1, ct::ii, -ct::ii, 1;
	// eigenvalue test
	cout << endl << hevals<cmat>(mat11) << endl;
	displn(
			mat11 * hevects(mat11).col(0)
					- (hevals(mat11)(0)) * hevects(mat11).col(0));

	cout << endl << mat11 << endl << endl;

	cout << endl;
	displn(transpose(mat11));
	cout << typeid(transpose(mat11)).name() << endl << endl;

	displn(transpose(mat11 * mat11));
	cout << typeid(transpose(mat11 * mat11)).name() << endl;

	cout << endl;
	displn(kron_list<cmat>( { gt::X * gt::X, gt::X + gt::X }));

	cout << endl;
	displn(kron_pow(gt::X * gt::X, 2));

	cout << endl;
	displn(kron(gt::X * gt::X, gt::X + gt::X));

	size_t N = 5000;
	cmat test = cmat::Random(N, N);

	// measure time taken

	clock_t start, end;
	double time;
	start = clock();

	/* process starts here */

	norm(reshape(test, 1, N * N));

	/* process ends here */
	end = clock();

	time = (double) (end - start);
	cout << "It took me " << time << " clicks ("
			<< ((float) time) / CLOCKS_PER_SEC << " seconds).";
	cout << endl << "Exiting qpp..." << endl;
}
<|endoftext|>


<commit_before>#include "System.h"
#include "Display.h"

#include "interface.h"
#include "ecg.h"
#include "nibp.h"

#define DISPLAY_CS PC4
#define DISPLAY_RESET PC5
#define DISPLAY_SPI spi_c1

#define SCREEN_ROWS 10
#define SCREEN_COLUMNS 10

SPI_Interface display_spi(DISPLAY_SPI);
Display tft(DISPLAY_CS, DISPLAY_RESET, &display_spi, SCREEN_ROWS, SCREEN_COLUMNS);

int currentMode = 0; // Change mode

Console c(USART2, 115200);

/* Build UI Buttons */
Button settings = Button(9,9,2,2,RA8875_RED,"Alarm Settings",true,&tft);
Button record = Button(5,9,2,2,RA8875_BLUE,"Data to Serial",true,&tft);
Button confirm_button = Button(9,1,2,2,RA8875_GREEN,"Confirm",true,&tft);
Button cancel_button = Button(9,9,2,2,RA8875_RED,"Cancel",true,&tft);
Button default_button = Button(6,7,2,2,RA8875_LIGHTGREY,"Default Settings",true,&tft);
ECGReadout ecg = ECGReadout(2,1,3,7,PB0,RA8875_BLUE,RA8875_LIGHTGREY,1000,tim3,&tft);
TextBox title = TextBox(1,3,1,3,RA8875_BLACK,RA8875_WHITE,3,true,false,"FreePulse Patient Monitor v0.9", &tft);
TextBox hr_label = TextBox(2,8,3,3,RA8875_BLACK,RA8875_BLUE,2,true,true,"BPM", &tft);
LargeNumberView heartrate = LargeNumberView(3,8,2,3,RA8875_BLACK,RA8875_BLUE,true,60,&tft);

Console c(USART2, 115200);

extern "C" void TIM3_IRQHandler(void) {
	if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) {
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
		int val = ecg.read();
		c.print(val);
		c.print("\n");
	}
}

void MainScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  title.draw();
  settings.draw();
  ecg.draw();
  heartrate.draw();
  hr_label.draw();
}

void SettingsScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  confirm_button.draw();
  default_button.draw();
  cancel_button.draw();
}

enum layout{
	home, alarms
};

void systemInit() {
	adcInit();
  	tft.startup();
	ecg.enable();
}

int main(void)
{
	c.configure();
	c.print("\n");
	c.print("Starting FreePulse...\n");
  	layout currentMode = home;
	systemInit();
	c.print("Welcome!\n");
	while (1) {
		MainScreenInit();
		delay(1000);
		tft.read_touch();
		tft.reset_touch();
		while (currentMode == home) {
			while (digitalRead(tft.interrupt)){
				ecg.display_signal();
				delay(100);
			}
			tft.read_touch();
			if (settings.isTapped()){
				tft.fillScreen(RA8875_BLACK);
				currentMode = alarms;
			}
			tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
		}
		if (currentMode == alarms) {
			SettingsScreenInit();
			delay(1000);
			tft.read_touch();
			tft.reset_touch();
			while (currentMode == alarms) {
				while (digitalRead(tft.interrupt)){}
				tft.read_touch();
				tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
				if (cancel_button.isTapped()) {
					tft.fillScreen(RA8875_BLACK);
					currentMode = home;
				}
			}
		}
    }
    return 0;
}
<commit_msg>Remove stray code from NIBP<commit_after>#include "System.h"
#include "Display.h"

#include "interface.h"
#include "ecg.h"

#define DISPLAY_CS PC4
#define DISPLAY_RESET PC5
#define DISPLAY_SPI spi_c1

#define SCREEN_ROWS 10
#define SCREEN_COLUMNS 10

SPI_Interface display_spi(DISPLAY_SPI);
Display tft(DISPLAY_CS, DISPLAY_RESET, &display_spi, SCREEN_ROWS, SCREEN_COLUMNS);

int currentMode = 0; // Change mode

Console c(USART2, 115200);

/* Build UI Buttons */
Button settings = Button(9,9,2,2,RA8875_RED,"Alarm Settings",true,&tft);
Button record = Button(5,9,2,2,RA8875_BLUE,"Data to Serial",true,&tft);
Button confirm_button = Button(9,1,2,2,RA8875_GREEN,"Confirm",true,&tft);
Button cancel_button = Button(9,9,2,2,RA8875_RED,"Cancel",true,&tft);
Button default_button = Button(6,7,2,2,RA8875_LIGHTGREY,"Default Settings",true,&tft);
ECGReadout ecg = ECGReadout(2,1,3,7,PB0,RA8875_BLUE,RA8875_LIGHTGREY,1000,tim3,&tft);
TextBox title = TextBox(1,3,1,3,RA8875_BLACK,RA8875_WHITE,3,true,false,"FreePulse Patient Monitor v0.9", &tft);
TextBox hr_label = TextBox(2,8,3,3,RA8875_BLACK,RA8875_BLUE,2,true,true,"BPM", &tft);
LargeNumberView heartrate = LargeNumberView(3,8,2,3,RA8875_BLACK,RA8875_BLUE,true,60,&tft);

extern "C" void TIM3_IRQHandler(void) {
	if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) {
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
		int val = ecg.read();
		c.print(val);
		c.print("\n");
	}
}

void MainScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  title.draw();
  settings.draw();
  ecg.draw();
  heartrate.draw();
  hr_label.draw();
}

void SettingsScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  confirm_button.draw();
  default_button.draw();
  cancel_button.draw();
}

enum layout{
	home, alarms
};

void systemInit() {
	adcInit();
  	tft.startup();
	ecg.enable();
}

int main(void)
{
	c.configure();
	c.print("\n");
	c.print("Starting FreePulse...\n");
  	layout currentMode = home;
	systemInit();
	c.print("Welcome!\n");
	while (1) {
		MainScreenInit();
		delay(1000);
		tft.read_touch();
		tft.reset_touch();
		while (currentMode == home) {
			while (digitalRead(tft.interrupt)){
				ecg.display_signal();
				delay(100);
			}
			tft.read_touch();
			if (settings.isTapped()){
				tft.fillScreen(RA8875_BLACK);
				currentMode = alarms;
			}
			tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
		}
		if (currentMode == alarms) {
			SettingsScreenInit();
			delay(1000);
			tft.read_touch();
			tft.reset_touch();
			while (currentMode == alarms) {
				while (digitalRead(tft.interrupt)){}
				tft.read_touch();
				tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
				if (cancel_button.isTapped()) {
					tft.fillScreen(RA8875_BLACK);
					currentMode = home;
				}
			}
		}
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <tuple>
#include <condition_variable>

#include "input_file_reader.hpp"
#include "minimize.hpp"
#include "comparator.hpp"
#include "result.hpp"

// mutex for shared resources
static std::mutex g_tasks_mutex;

// conditonal variable for shared resources
static std::condition_variable g_cv;

// global queue with two pointers to the sequences
// they are compared directly if the both sequence lengths are small enough
static std::queue<std::tuple<OLC::Sequence*, OLC::Sequence*>> g_sequence_pairs;

// global queue with two pointers to vectors of minimizers
// we use this instead if the sequences are too long
static std::queue<std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*>> g_minimizer_pairs;

static void worker()
{
  // Get the task and remove it from the pool
  g_tasks_mutex.lock();

  const std::tuple<OLC::Sequence*, OLC::Sequence*> sequence_pair = g_sequence_pairs.front();
  g_sequence_pairs.pop();
  const std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*> minimizer_pair = g_minimizer_pairs.front();
  g_minimizer_pairs.pop();

  g_tasks_mutex.unlock();

  // Get the task sequences
  const OLC::Sequence* sequence1 = std::get<0>(sequence_pair);
  const OLC::Sequence* sequence2 = std::get<1>(sequence_pair);

  // Pull out the wrapped nucleotide vectors
  const std::vector<OLC::Nucleotide> nucleotides1 = sequence1->getNucleotides()->getSequence();
  const std::vector<OLC::Nucleotide> nucleotides2 = sequence2->getNucleotides()->getSequence();

  // If small enough, no need to use minimizers
  if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000)
  {
    const OLC::Overlap overlap = compare(nucleotides1, nucleotides2);
    const uint32_t overlapFirstEnd = overlap.getEndFirst();
    const uint32_t overlapSecondEnd = overlap.getEndSecond();
    const uint32_t overlapFirstStart = overlap.getStartFirst();
    const uint32_t overlapSecondStart = overlap.getStartSecond();
    const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;

    const std::string sequence1_ident = sequence1->getIdentifier();
    const std::string sequence2_ident = sequence2->getIdentifier();

    int32_t ahang = overlapFirstStart;
    int32_t bhang = nucleotides2.size() - overlapSecondEnd;

    if (overlapSecondStart > overlapFirstStart) {
      ahang *= -1;
    }

    if (nucleotides1.size() > overlapSecondEnd) {
      bhang *= -1;
    }

    //TODO: Add into result queue
    const OLC::Result result(sequence1_ident, sequence2_ident, overlapLength, ahang, bhang);
  }
  else
  {

  }

  return;
}

int main(int argc, char** argv)
{
  std::ios_base::sync_with_stdio(false);

  if (argc != 3)
  {
    std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n";
    return 1;
  }

  // file with the data
  const std::string file = std::string(argv[2]);

  // L is the minimum overlap length
  const uint32_t L = std::stoi(argv[1]);

  // window size
  const uint32_t w = (L + 1) / 2;

  // size of the k-mer
  const uint32_t k = (L + 1) / 2;

  // read phase
  OLC::InputFileReader reader(file);
  const std::vector<OLC::Sequence*> sequences = reader.readSequences();
  std::vector<std::vector<OLC::Minimizer>> minimizers;

  for (size_t i = 0; i < sequences.size(); ++i)
  {
    const auto sequence = sequences[i]->getNucleotides()->getSequence();

    // calculate minimizers - both interior and end minimizers
    minimizers.push_back(minimize(sequence, w, k));
  }

  // generate tasks so we can do this in parallel if possible
  std::queue<std::tuple<uint32_t, uint32_t>> tasks;

  for (uint32_t i = 0; i < sequences.size(); ++i)
  {
    for (uint32_t j = i + 1; j < sequences.size(); ++j)
    {
      g_sequence_pairs.emplace(sequences[i], sequences[j]);
      g_minimizer_pairs.emplace(&minimizers[i], &minimizers[j]);
    }
  }

  // use concurrent minimizer matching
  std::vector<std::thread> threads(std::thread::hardware_concurrency());

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i] = std::thread(worker);

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i].join();

  // cleanup
  for (size_t i = 0; i < sequences.size(); ++i)
    delete sequences[i];

  return 0;
}
<commit_msg>main: do the simple case<commit_after>#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <tuple>
#include <condition_variable>

#include "input_file_reader.hpp"
#include "minimize.hpp"
#include "comparator.hpp"
#include "result.hpp"

// mutex for shared resources
static std::mutex g_resource_mutex;

// mutex for result vector
static std::mutex g_result_mutex;

// conditonal variable for shared resources
static std::condition_variable g_resource_cv;

// conditonal variable for result vector
static std::condition_variable g_result_cv;

// global queue with two pointers to the sequences
// they are compared directly if the both sequence lengths are small enough
static std::queue<std::tuple<OLC::Sequence*, OLC::Sequence*>> g_sequence_pairs;

// global queue with two pointers to vectors of minimizers
// we use this instead if the sequences are too long
static std::queue<std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*>> g_minimizer_pairs;

static std::vector<OLC::Result> g_results;

static void worker()
{
  while(true)
  {
    // Get the task and remove it from the pool
    std::unique_lock<std::mutex> resource_lock(g_resource_mutex);
    g_resource_cv.wait(resource_lock);

    if (g_sequence_pairs.empty())
      return;

    const std::tuple<OLC::Sequence*, OLC::Sequence*> sequence_pair = g_sequence_pairs.front();
    g_sequence_pairs.pop();
    const std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*> minimizer_pair = g_minimizer_pairs.front();
    g_minimizer_pairs.pop();

    resource_lock.unlock();
    g_resource_cv.notify_one();

    // Get the task sequences
    const OLC::Sequence* sequence1 = std::get<0>(sequence_pair);
    const OLC::Sequence* sequence2 = std::get<1>(sequence_pair);

    // Pull out the wrapped nucleotide vectors
    const std::vector<OLC::Nucleotide> nucleotides1 = sequence1->getNucleotides()->getSequence();
    const std::vector<OLC::Nucleotide> nucleotides2 = sequence2->getNucleotides()->getSequence();

    // If small enough, no need to use minimizers
    if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000)
    {
      const OLC::Overlap overlap = compare(nucleotides1, nucleotides2);
      const uint32_t overlapFirstEnd = overlap.getEndFirst();
      const uint32_t overlapSecondEnd = overlap.getEndSecond();
      const uint32_t overlapFirstStart = overlap.getStartFirst();
      const uint32_t overlapSecondStart = overlap.getStartSecond();
      const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;

      const std::string sequence1_ident = sequence1->getIdentifier();
      const std::string sequence2_ident = sequence2->getIdentifier();

      int32_t ahang = overlapFirstStart;
      int32_t bhang = nucleotides2.size() - overlapSecondEnd;

      if (overlapSecondStart > overlapFirstStart)
        ahang *= -1;

      if (nucleotides1.size() > overlapSecondEnd)
        bhang *= -1;

      const OLC::Result result(sequence1_ident, sequence2_ident, overlapLength, ahang, bhang);

      std::unique_lock<std::mutex> result_lock(g_result_mutex);
      g_result_cv.wait(result_lock);

      g_results.push_back(result);

      result_lock.unlock();
      g_result_cv.notify_one();
    }
    else
    {

    }
  }
}

int main(int argc, char** argv)
{
  std::ios_base::sync_with_stdio(false);

  if (argc != 3)
  {
    std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n";
    return 1;
  }

  // file with the data
  const std::string file = std::string(argv[2]);

  // L is the minimum overlap length
  const uint32_t L = std::stoi(argv[1]);

  // window size
  const uint32_t w = (L + 1) / 2;

  // size of the k-mer
  const uint32_t k = (L + 1) / 2;

  // read phase
  OLC::InputFileReader reader(file);
  const std::vector<OLC::Sequence*> sequences = reader.readSequences();
  std::vector<std::vector<OLC::Minimizer>> minimizers;

  for (size_t i = 0; i < sequences.size(); ++i)
  {
    const auto sequence = sequences[i]->getNucleotides()->getSequence();

    // calculate minimizers - both interior and end minimizers
    minimizers.push_back(minimize(sequence, w, k));
  }

  // generate tasks so we can do this in parallel if possible
  std::queue<std::tuple<uint32_t, uint32_t>> tasks;

  for (uint32_t i = 0; i < sequences.size(); ++i)
  {
    for (uint32_t j = i + 1; j < sequences.size(); ++j)
    {
      g_sequence_pairs.emplace(sequences[i], sequences[j]);
      g_minimizer_pairs.emplace(&minimizers[i], &minimizers[j]);
    }
  }

  // use concurrent minimizer matching
  std::vector<std::thread> threads(std::thread::hardware_concurrency());

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i] = std::thread(worker);

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i].join();

  // cleanup
  for (size_t i = 0; i < sequences.size(); ++i)
    delete sequences[i];

  return 0;
}
<|endoftext|>


<commit_before>/*
 *
<<<<<<< HEAD
 *  Copyright 2013 Mario Alviano, Carmine Dodaro and Francesco Ricca.
=======
 *  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
>>>>>>> 5fc82930c51bc47fa41e640f5f2e1612ac22a801
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#include <cstdlib>

#include "WaspFacade.h"
#include "Options.h"
using namespace std;

int EXIT_CODE = 0;

/*
 *
 */
int main( int argc, char** argv )
{
    wasp::Options::parse( argc, argv );
    WaspFacade waspFacade;
    wasp::Options::setOptions( waspFacade );
    waspFacade.readInput();
    waspFacade.solve();

    return EXIT_CODE;
}

<commit_msg>Removed a conflict in a comment.<commit_after>/*
 *
 *  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#include <cstdlib>

#include "WaspFacade.h"
#include "Options.h"
using namespace std;

int EXIT_CODE = 0;

/*
 *
 */
int main( int argc, char** argv )
{
    wasp::Options::parse( argc, argv );
    WaspFacade waspFacade;
    wasp::Options::setOptions( waspFacade );
    waspFacade.readInput();
    waspFacade.solve();

    return EXIT_CODE;
}

<|endoftext|>


<commit_before>// ImGui - standalone example application for DirectX 9
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.

#include "BoardView.h"

#include "imgui_impl_dx9.h"
#include <d3d9.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
#include "crtdbg.h"
#include "platform.h"

// Data
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS g_d3dpp;

extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam))
		return true;

	switch (msg) {
	case WM_SIZE:
		if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) {
			ImGui_ImplDX9_InvalidateDeviceObjects();
			g_d3dpp.BackBufferWidth = LOWORD(lParam);
			g_d3dpp.BackBufferHeight = HIWORD(lParam);
			HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
			if (hr == D3DERR_INVALIDCALL)
				IM_ASSERT(0);
			ImGui_ImplDX9_CreateDeviceObjects();
		}
		return 0;
	case WM_SYSCOMMAND:
		if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
			return 0;
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hWnd, msg, wParam, lParam);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	// Initialize comctl
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	static const wchar_t *class_name = L"ImGui Example";

	// Create application window
	HINSTANCE instance = GetModuleHandle(NULL);
	HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));
	WNDCLASSEX wc = {sizeof(WNDCLASSEX),
	                 CS_CLASSDC,
	                 WndProc,
	                 0L,
	                 0L,
	                 instance,
	                 icon,
	                 NULL,
	                 NULL,
	                 NULL,
	                 class_name,
	                 NULL};
	RegisterClassEx(&wc);
	HWND hwnd =
	    CreateWindow(class_name, _T("Open Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
	                 CW_USEDEFAULT, 1280, 800, NULL, NULL, wc.hInstance, NULL);

	// Initialize Direct3D
	LPDIRECT3D9 pD3D;
	if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) {
		UnregisterClass(class_name, wc.hInstance);
		MessageBox(hwnd, L"Failed to initialise Direct3D", NULL, 0);
		return 0;
	}
	ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
	g_d3dpp.Windowed = TRUE;
	g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	g_d3dpp.EnableAutoDepthStencil = TRUE;
	g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

	// Create the D3DDevice
	if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
	                       D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) {
		pD3D->Release();
		UnregisterClass(class_name, wc.hInstance);
		MessageBox(hwnd, L"Failed to create Direct3D device", NULL, 0);
		return 0;
	}

	// Setup ImGui binding
	ImGui_ImplDX9_Init(hwnd, g_pd3dDevice);

	// Load Fonts
	// (there is a default font, this is only if you want to change it. see extra_fonts/README.txt
	// for more details)
	ImGuiIO &io = ImGui::GetIO();
	int ttf_size;
	unsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS);
	ImFontConfig font_cfg{};
	font_cfg.FontDataOwnedByAtlas = false;
	io.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, 20.0f, &font_cfg);
// io.Fonts->AddFontDefault();
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
// io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL,
// io.Fonts->GetGlyphRangesJapanese());
#if 0
	// Get current flag
	int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

	// Turn on leak-checking bit.
	tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;

	// Set flag to the new value.
	_CrtSetDbgFlag(tmpFlag);
#endif
	BoardView app{};

	bool show_test_window = true;
	bool show_another_window = false;
	ImVec4 clear_col = ImColor(20, 20, 30);

	// Main loop
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	ShowWindow(hwnd, SW_SHOWDEFAULT);
	UpdateWindow(hwnd);
	while (msg.message != WM_QUIT) {
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			continue;
		}
		ImGui_ImplDX9_NewFrame();
#if 0
		// 1. Show a simple window
		// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window
		// automatically called "Debug"
		{
			static float f = 0.0f;
			ImGui::Text("Hello, world!");
			ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
			ImGui::ColorEdit3("clear color", (float *)&clear_col);
			if (ImGui::Button("Test Window"))
				show_test_window ^= 1;
			if (ImGui::Button("Another Window"))
				show_another_window ^= 1;
			ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
			            1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
		}

		// 2. Show another simple window, this time using an explicit Begin/End pair
		if (show_another_window) {
			ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
			ImGui::Begin("Another Window", &show_another_window);
			ImGui::Text("Hello");
			ImGui::End();
		}

#endif
#if 0
		// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
		if (show_test_window) {
			ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
			ImGui::ShowTestWindow(&show_test_window);
		}
#endif
		app.Update();
		if (app.m_wantsQuit) {
			PostMessage(hwnd, WM_QUIT, 0, 0);
		}

		// Rendering
		g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
		g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
		g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
		D3DCOLOR clear_col_dx =
		    D3DCOLOR_RGBA((int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f),
		                  (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f));
		g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
		if (g_pd3dDevice->BeginScene() >= 0) {
			ImGui::Render();
			g_pd3dDevice->EndScene();
		}
		g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
	}

	ImGui_ImplDX9_Shutdown();
	if (g_pd3dDevice)
		g_pd3dDevice->Release();
	if (pD3D)
		pD3D->Release();
	UnregisterClass(class_name, wc.hInstance);

	return 0;
}
<commit_msg>Revert "Display an error when DirectX can't be initialised"<commit_after>// ImGui - standalone example application for DirectX 9
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.

#include "BoardView.h"

#include "imgui_impl_dx9.h"
#include <d3d9.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
#include "crtdbg.h"
#include "platform.h"

// Data
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS g_d3dpp;

extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam))
		return true;

	switch (msg) {
	case WM_SIZE:
		if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) {
			ImGui_ImplDX9_InvalidateDeviceObjects();
			g_d3dpp.BackBufferWidth = LOWORD(lParam);
			g_d3dpp.BackBufferHeight = HIWORD(lParam);
			HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
			if (hr == D3DERR_INVALIDCALL)
				IM_ASSERT(0);
			ImGui_ImplDX9_CreateDeviceObjects();
		}
		return 0;
	case WM_SYSCOMMAND:
		if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
			return 0;
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hWnd, msg, wParam, lParam);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	// Initialize comctl
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	static const wchar_t *class_name = L"ImGui Example";

	// Create application window
	HINSTANCE instance = GetModuleHandle(NULL);
	HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));
	WNDCLASSEX wc = {sizeof(WNDCLASSEX),
	                 CS_CLASSDC,
	                 WndProc,
	                 0L,
	                 0L,
	                 instance,
	                 icon,
	                 NULL,
	                 NULL,
	                 NULL,
	                 class_name,
	                 NULL};
	RegisterClassEx(&wc);
	HWND hwnd =
	    CreateWindow(class_name, _T("Open Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
	                 CW_USEDEFAULT, 1280, 800, NULL, NULL, wc.hInstance, NULL);

	// Initialize Direct3D
	LPDIRECT3D9 pD3D;
	if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) {
		UnregisterClass(class_name, wc.hInstance);
		return 0;
	}
	ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
	g_d3dpp.Windowed = TRUE;
	g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	g_d3dpp.EnableAutoDepthStencil = TRUE;
	g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

	// Create the D3DDevice
	if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
	                       D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) {
		pD3D->Release();
		UnregisterClass(class_name, wc.hInstance);
		return 0;
	}

	// Setup ImGui binding
	ImGui_ImplDX9_Init(hwnd, g_pd3dDevice);

	// Load Fonts
	// (there is a default font, this is only if you want to change it. see extra_fonts/README.txt
	// for more details)
	ImGuiIO &io = ImGui::GetIO();
	int ttf_size;
	unsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS);
	ImFontConfig font_cfg{};
	font_cfg.FontDataOwnedByAtlas = false;
	io.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, 20.0f, &font_cfg);
// io.Fonts->AddFontDefault();
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
// io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
// io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL,
// io.Fonts->GetGlyphRangesJapanese());
#if 0
	// Get current flag
	int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

	// Turn on leak-checking bit.
	tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;

	// Set flag to the new value.
	_CrtSetDbgFlag(tmpFlag);
#endif
	BoardView app{};

	bool show_test_window = true;
	bool show_another_window = false;
	ImVec4 clear_col = ImColor(20, 20, 30);

	// Main loop
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	ShowWindow(hwnd, SW_SHOWDEFAULT);
	UpdateWindow(hwnd);
	while (msg.message != WM_QUIT) {
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			continue;
		}
		ImGui_ImplDX9_NewFrame();
#if 0
		// 1. Show a simple window
		// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window
		// automatically called "Debug"
		{
			static float f = 0.0f;
			ImGui::Text("Hello, world!");
			ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
			ImGui::ColorEdit3("clear color", (float *)&clear_col);
			if (ImGui::Button("Test Window"))
				show_test_window ^= 1;
			if (ImGui::Button("Another Window"))
				show_another_window ^= 1;
			ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
			            1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
		}

		// 2. Show another simple window, this time using an explicit Begin/End pair
		if (show_another_window) {
			ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
			ImGui::Begin("Another Window", &show_another_window);
			ImGui::Text("Hello");
			ImGui::End();
		}

#endif
#if 0
		// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
		if (show_test_window) {
			ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
			ImGui::ShowTestWindow(&show_test_window);
		}
#endif
		app.Update();
		if (app.m_wantsQuit) {
			PostMessage(hwnd, WM_QUIT, 0, 0);
		}

		// Rendering
		g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
		g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
		g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
		D3DCOLOR clear_col_dx =
		    D3DCOLOR_RGBA((int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f),
		                  (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f));
		g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
		if (g_pd3dDevice->BeginScene() >= 0) {
			ImGui::Render();
			g_pd3dDevice->EndScene();
		}
		g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
	}

	ImGui_ImplDX9_Shutdown();
	if (g_pd3dDevice)
		g_pd3dDevice->Release();
	if (pD3D)
		pD3D->Release();
	UnregisterClass(class_name, wc.hInstance);

	return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QDebug>
#include <QScrollBar>
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>

// CTK includes
#include "ctkFittedTextBrowser.h"
#include "ctkFittedTextBrowser_p.h"

static const char moreAnchor[] = "show_details";
static const char lessAnchor[] = "hide_details";

//-----------------------------------------------------------------------------
ctkFittedTextBrowserPrivate::ctkFittedTextBrowserPrivate(ctkFittedTextBrowser& object)
  :q_ptr(&object)
{
  this->Collapsed = true;
  this->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text;
  this->ShowDetailsText = object.tr("Show details...");
  this->HideDetailsText = object.tr("Hide details.");
  QString HideDetailsText;
}

//-----------------------------------------------------------------------------
ctkFittedTextBrowserPrivate::~ctkFittedTextBrowserPrivate()
{
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowserPrivate::updateCollapsedText()
{
  Q_Q(ctkFittedTextBrowser);
  bool html = (this->CollapsibleTextSetter == ctkFittedTextBrowserPrivate::Html || this->CollapsibleText.indexOf("") >= 0);
  if (html)
  {
    q->setHtml(this->collapsedTextFromHtml());
  }
  else
  {
    q->setHtml(this->collapsedTextFromPlainText());
  }
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowserPrivate::collapsedTextFromPlainText() const
{
  Q_Q(const ctkFittedTextBrowser);
  int teaserEndPosition = this->CollapsibleText.indexOf("\n");
  if (teaserEndPosition < 0)
  {
    return this->CollapsibleText;
  }
  QString finalText;
  finalText.append("");
  finalText.append(this->Collapsed ? this->CollapsibleText.left(teaserEndPosition) : this->CollapsibleText);
  finalText.append(this->collapseLinkText());
  finalText.append("");
  // Remove line break to allow continuation of line.
  finalText.replace(finalText.indexOf('\n'), 1, "");
  // In plain text line breaks were indicated by newline, but we now use html,
  // so line breaks must use

  finalText.replace("\n", "
");
  return finalText;
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowserPrivate::collapsedTextFromHtml() const
{
  Q_Q(const ctkFittedTextBrowser);
  const QString lineBreak("
");
  int teaserEndPosition = this->CollapsibleText.indexOf(lineBreak);
  if (teaserEndPosition < 0)
  {
    return this->CollapsibleText;
  }

  QString finalText = this->CollapsibleText;
  if (this->Collapsed)
  {
    finalText = finalText.left(teaserEndPosition) + this->collapseLinkText();
    // By truncating the full text we might have deleted the closing  tag
    // restore it now.
    if (finalText.contains("<html") && !finalText.contains("</html"))
    {
      finalText.append("");
    }
  }
  else
  {
    // Remove
 to allow continuation of line and avoid extra space
    // when
 element is used as well.
    finalText.replace(finalText.indexOf(lineBreak), lineBreak.size(), "");
    // Add link text before closing  or  tag
    if (finalText.contains(""))
    {
      finalText.replace("", this->collapseLinkText() + "");
    }
    else if (finalText.contains(""))
    {
      finalText.replace("", this->collapseLinkText() + "");
    }
    else
    {
      finalText.append(this->collapseLinkText());
    }
  }
  return finalText;
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowserPrivate::collapseLinkText() const
{
  Q_Q(const ctkFittedTextBrowser);
  if (this->Collapsed)
  {
    return QString("… " + this->ShowDetailsText + "";
  }
  else
  {
    return QString(" " + this->HideDetailsText + "";
  }
}

//-----------------------------------------------------------------------------
ctkFittedTextBrowser::ctkFittedTextBrowser(QWidget* _parent)
  : QTextBrowser(_parent)
  , d_ptr(new ctkFittedTextBrowserPrivate(*this))
{
  this->connect(this, SIGNAL(textChanged()), SLOT(heightForWidthMayHaveChanged()));
  QSizePolicy newSizePolicy = QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
  this->setSizePolicy(newSizePolicy);
  this->connect(this, SIGNAL(anchorClicked(QUrl)), SLOT(anchorClicked(QUrl)));
}

//-----------------------------------------------------------------------------
ctkFittedTextBrowser::~ctkFittedTextBrowser()
{

}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::heightForWidthMayHaveChanged()
{
  this->updateGeometry();
}

//-----------------------------------------------------------------------------
int ctkFittedTextBrowser::heightForWidth(int _width) const
{
  QTextDocument* doc = this->document();
  qreal savedWidth = doc->textWidth();

  // Fudge factor. This is the difference between the frame and the
  // viewport.
  int fudge = 2 * this->frameWidth();

  int horizontalScrollbarHeight = 0;
  if (this->horizontalScrollBar()->isVisible())
  {
    horizontalScrollbarHeight = this->horizontalScrollBar()->height() + fudge;
  }

  // Do the calculation assuming no scrollbars
  doc->setTextWidth(_width - fudge);
  int noScrollbarHeight =
    doc->documentLayout()->documentSize().height() + fudge;

  // (If noScrollbarHeight is greater than the maximum height we'll be
  // allowed, then there will be scrollbars, and the actual required
  // height will be even higher. But since in this case we've already
  // hit the maximum height, it doesn't matter that we underestimate.)

  // Get minimum height (even if string is empty): one line of text
  int _minimumHeight = QFontMetrics(doc->defaultFont()).lineSpacing() + fudge;
  int ret = qMax(noScrollbarHeight, _minimumHeight) + horizontalScrollbarHeight;

  doc->setTextWidth(savedWidth);
  return ret;
}

//-----------------------------------------------------------------------------
QSize ctkFittedTextBrowser::minimumSizeHint() const {
  QSize s(this->size().width(), 0);
  if (s.width() == 0)
    {
    //s.setWidth(400); // arbitrary value
    return QTextBrowser::minimumSizeHint();
    }
  s.setHeight(this->heightForWidth(s.width()));
  return s;
}

//-----------------------------------------------------------------------------
QSize ctkFittedTextBrowser::sizeHint() const {
  return this->minimumSizeHint();
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::resizeEvent(QResizeEvent* e)
{
  this->QTextBrowser::resizeEvent(e);
  if (e->size().height() != this->heightForWidth(e->size().width()))
    {
    this->heightForWidthMayHaveChanged();
    }
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsibleText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text;
  d->CollapsibleText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowser::collapsibleText() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->CollapsibleText;
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsiblePlainText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::PlainText;
  d->CollapsibleText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsibleHtml(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Html;
  d->CollapsibleText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::anchorClicked(const QUrl &url)
{
  Q_D(ctkFittedTextBrowser);
  if (url.path().isEmpty())
  {
    if (url.fragment() == moreAnchor)
    {
      this->setCollapsed(false);
    }
    else if (url.fragment() == lessAnchor)
    {
      this->setCollapsed(true);
    }
  }
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsed(bool collapsed)
{
  Q_D(ctkFittedTextBrowser);
  if (d->Collapsed == collapsed)
  {
    // no change
    return;
  }
  d->Collapsed = collapsed;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
bool ctkFittedTextBrowser::collapsed() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->Collapsed;
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setShowDetailsText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  if (d->ShowDetailsText == text)
  {
    // no change
    return;
  }
  d->ShowDetailsText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowser::showDetailsText() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->ShowDetailsText;
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setHideDetailsText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  if (d->HideDetailsText == text)
  {
    // no change
    return;
  }
  d->HideDetailsText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowser::hideDetailsText() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->HideDetailsText;
}
<commit_msg>COMP: Fix -Wunused-variable warnings in ctkFittedTextBrowserPrivate<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QDebug>
#include <QScrollBar>
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>

// CTK includes
#include "ctkFittedTextBrowser.h"
#include "ctkFittedTextBrowser_p.h"

static const char moreAnchor[] = "show_details";
static const char lessAnchor[] = "hide_details";

//-----------------------------------------------------------------------------
ctkFittedTextBrowserPrivate::ctkFittedTextBrowserPrivate(ctkFittedTextBrowser& object)
  :q_ptr(&object)
{
  this->Collapsed = true;
  this->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text;
  this->ShowDetailsText = object.tr("Show details...");
  this->HideDetailsText = object.tr("Hide details.");
  QString HideDetailsText;
}

//-----------------------------------------------------------------------------
ctkFittedTextBrowserPrivate::~ctkFittedTextBrowserPrivate()
{
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowserPrivate::updateCollapsedText()
{
  Q_Q(ctkFittedTextBrowser);
  bool html = (this->CollapsibleTextSetter == ctkFittedTextBrowserPrivate::Html || this->CollapsibleText.indexOf("") >= 0);
  if (html)
  {
    q->setHtml(this->collapsedTextFromHtml());
  }
  else
  {
    q->setHtml(this->collapsedTextFromPlainText());
  }
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowserPrivate::collapsedTextFromPlainText() const
{
  int teaserEndPosition = this->CollapsibleText.indexOf("\n");
  if (teaserEndPosition < 0)
  {
    return this->CollapsibleText;
  }
  QString finalText;
  finalText.append("");
  finalText.append(this->Collapsed ? this->CollapsibleText.left(teaserEndPosition) : this->CollapsibleText);
  finalText.append(this->collapseLinkText());
  finalText.append("");
  // Remove line break to allow continuation of line.
  finalText.replace(finalText.indexOf('\n'), 1, "");
  // In plain text line breaks were indicated by newline, but we now use html,
  // so line breaks must use

  finalText.replace("\n", "
");
  return finalText;
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowserPrivate::collapsedTextFromHtml() const
{
  const QString lineBreak("
");
  int teaserEndPosition = this->CollapsibleText.indexOf(lineBreak);
  if (teaserEndPosition < 0)
  {
    return this->CollapsibleText;
  }

  QString finalText = this->CollapsibleText;
  if (this->Collapsed)
  {
    finalText = finalText.left(teaserEndPosition) + this->collapseLinkText();
    // By truncating the full text we might have deleted the closing  tag
    // restore it now.
    if (finalText.contains("<html") && !finalText.contains("</html"))
    {
      finalText.append("");
    }
  }
  else
  {
    // Remove
 to allow continuation of line and avoid extra space
    // when
 element is used as well.
    finalText.replace(finalText.indexOf(lineBreak), lineBreak.size(), "");
    // Add link text before closing  or  tag
    if (finalText.contains(""))
    {
      finalText.replace("", this->collapseLinkText() + "");
    }
    else if (finalText.contains(""))
    {
      finalText.replace("", this->collapseLinkText() + "");
    }
    else
    {
      finalText.append(this->collapseLinkText());
    }
  }
  return finalText;
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowserPrivate::collapseLinkText() const
{
  if (this->Collapsed)
  {
    return QString("… " + this->ShowDetailsText + "";
  }
  else
  {
    return QString(" " + this->HideDetailsText + "";
  }
}

//-----------------------------------------------------------------------------
ctkFittedTextBrowser::ctkFittedTextBrowser(QWidget* _parent)
  : QTextBrowser(_parent)
  , d_ptr(new ctkFittedTextBrowserPrivate(*this))
{
  this->connect(this, SIGNAL(textChanged()), SLOT(heightForWidthMayHaveChanged()));
  QSizePolicy newSizePolicy = QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
  this->setSizePolicy(newSizePolicy);
  this->connect(this, SIGNAL(anchorClicked(QUrl)), SLOT(anchorClicked(QUrl)));
}

//-----------------------------------------------------------------------------
ctkFittedTextBrowser::~ctkFittedTextBrowser()
{

}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::heightForWidthMayHaveChanged()
{
  this->updateGeometry();
}

//-----------------------------------------------------------------------------
int ctkFittedTextBrowser::heightForWidth(int _width) const
{
  QTextDocument* doc = this->document();
  qreal savedWidth = doc->textWidth();

  // Fudge factor. This is the difference between the frame and the
  // viewport.
  int fudge = 2 * this->frameWidth();

  int horizontalScrollbarHeight = 0;
  if (this->horizontalScrollBar()->isVisible())
  {
    horizontalScrollbarHeight = this->horizontalScrollBar()->height() + fudge;
  }

  // Do the calculation assuming no scrollbars
  doc->setTextWidth(_width - fudge);
  int noScrollbarHeight =
    doc->documentLayout()->documentSize().height() + fudge;

  // (If noScrollbarHeight is greater than the maximum height we'll be
  // allowed, then there will be scrollbars, and the actual required
  // height will be even higher. But since in this case we've already
  // hit the maximum height, it doesn't matter that we underestimate.)

  // Get minimum height (even if string is empty): one line of text
  int _minimumHeight = QFontMetrics(doc->defaultFont()).lineSpacing() + fudge;
  int ret = qMax(noScrollbarHeight, _minimumHeight) + horizontalScrollbarHeight;

  doc->setTextWidth(savedWidth);
  return ret;
}

//-----------------------------------------------------------------------------
QSize ctkFittedTextBrowser::minimumSizeHint() const {
  QSize s(this->size().width(), 0);
  if (s.width() == 0)
    {
    //s.setWidth(400); // arbitrary value
    return QTextBrowser::minimumSizeHint();
    }
  s.setHeight(this->heightForWidth(s.width()));
  return s;
}

//-----------------------------------------------------------------------------
QSize ctkFittedTextBrowser::sizeHint() const {
  return this->minimumSizeHint();
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::resizeEvent(QResizeEvent* e)
{
  this->QTextBrowser::resizeEvent(e);
  if (e->size().height() != this->heightForWidth(e->size().width()))
    {
    this->heightForWidthMayHaveChanged();
    }
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsibleText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text;
  d->CollapsibleText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowser::collapsibleText() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->CollapsibleText;
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsiblePlainText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::PlainText;
  d->CollapsibleText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsibleHtml(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Html;
  d->CollapsibleText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::anchorClicked(const QUrl &url)
{
  if (url.path().isEmpty())
  {
    if (url.fragment() == moreAnchor)
    {
      this->setCollapsed(false);
    }
    else if (url.fragment() == lessAnchor)
    {
      this->setCollapsed(true);
    }
  }
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setCollapsed(bool collapsed)
{
  Q_D(ctkFittedTextBrowser);
  if (d->Collapsed == collapsed)
  {
    // no change
    return;
  }
  d->Collapsed = collapsed;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
bool ctkFittedTextBrowser::collapsed() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->Collapsed;
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setShowDetailsText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  if (d->ShowDetailsText == text)
  {
    // no change
    return;
  }
  d->ShowDetailsText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowser::showDetailsText() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->ShowDetailsText;
}

//-----------------------------------------------------------------------------
void ctkFittedTextBrowser::setHideDetailsText(const QString &text)
{
  Q_D(ctkFittedTextBrowser);
  if (d->HideDetailsText == text)
  {
    // no change
    return;
  }
  d->HideDetailsText = text;
  d->updateCollapsedText();
}

//-----------------------------------------------------------------------------
QString ctkFittedTextBrowser::hideDetailsText() const
{
  Q_D(const ctkFittedTextBrowser);
  return d->HideDetailsText;
}
<|endoftext|>