<commit_before>/*
 *  Debug.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 01.01.09.
 *  code under LGPL
 *
 */

#include "Debug.h"
#include "StringUtils.h"

#ifdef WIN32

void RaiseDebugger() {
#ifdef DEBUG
	// TODO: what does that do if not run in a debugger?
	// If it just does nothing then, remove the surrounding #ifdef DEBUG
	// I read about a Win32's IsDebuggerPresent() function, perhaps you should use that one here.
	__asm  { int 3 };
#endif
}

#else

#if defined(__APPLE__)

#include <cassert>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>

// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
static bool AmIBeingDebugged()
    // Returns true if the current process is being debugged (either
    // running under the debugger or has a debugger attached post facto).
{
	// Initialize mib, which tells sysctl what info we want.  In this case,
	// we're looking for information about a specific process ID.
	int mib[] =
	{
		CTL_KERN,
		KERN_PROC,
		KERN_PROC_PID,
		getpid()
	};

	// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE.  The source and
	// binary interfaces may change.
	struct kinfo_proc info;
	size_t info_size = sizeof ( info );

	int sysctl_result = sysctl ( mib, arraysize ( mib ), &info, &info_size, NULL, 0 );
	DCHECK ( sysctl_result == 0 );
	if ( sysctl_result != 0 )
		return false;

	// This process is being debugged if the P_TRACED flag is set.
	return ( info.kp_proc.p_flag & P_TRACED ) != 0;
}

#else

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>

static bool AmIBeingDebugged() {
	// We can look in /proc/self/status for TracerPid.  We are likely used in crash
	// handling, so we are careful not to use the heap or have side effects.
	int status_fd = open("/proc/self/status", O_RDONLY);
	if (status_fd == -1)
		return false;

	// We assume our line will be in the first 1024 characters and that we can
	// read this much all at once.  In practice this will generally be true.
	// This simplifies and speeds up things considerably.
	char buf[1024];

	ssize_t num_read = read(status_fd, buf, sizeof(buf));
	fix_markend(buf);
	close(status_fd);
	if (num_read <= 0) return false;

	const char* searchStr = "TracerPid:\t";
	const char* f = strstr(buf, searchStr);
	if(f == NULL) return false;

	// Our pid is 0 without a debugger, assume this for any pid starting with 0.
	f += strlen(searchStr);
	return f < &buf[num_read] && *f != '0';
}

#endif // OSX/LINUX

#include <signal.h>

void RaiseDebugger() {
	if(AmIBeingDebugged()) {
		raise(SIGABRT);
	}
}

#endif

#ifdef WIN32
void OlxWriteCoreDump(const char* file_postfix) {}

#else

#ifdef GCOREDUMPER
#include <google/coredumper.h>
#endif
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <cstdio>

#ifndef GCOREDUMPER
static void GdbWriteCoreDump(const char* fname) {
	// WARNING: this is terribly slow like this
	char gdbparam[1000];
	sprintf(gdbparam,
			"attach %i \n"
			"gcore %s \n"
			"detach \n"
			"quit \n",
			getpid(), fname);
	FILE* p = popen("gdb -q", "w");
	if(p) {
		fprintf(p, "%s", gdbparam);
		fflush(p);
		int status = 0; wait(&status);
		pclose(p);
	}
}
#endif

void OlxWriteCoreDump(const char* file_postfix) {
	char corefile[PATH_MAX + 100];
	if(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, "");
	strcat(corefile, "/core.OpenLieroX");
	if(file_postfix) { strcat(corefile, "."); strcat(corefile, file_postfix); }
	printf("writing coredump to %s\n", corefile);

	printf("dumping core ... "); fflush(0);
#ifdef GCOREDUMPER
	WriteCoreDump(corefile);
#else
	GdbWriteCoreDump(corefile);
#endif
	printf("ready\n");
}

#endif

#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>

void DumpCallstackPrintf(void* callpnt) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	printf("backtrace() returned %d addresses\n", framesC);
	if(callpnt != NULL && framesC > 3) callstack[3] = callpnt; // expected to be called from signal handler
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			printf("%s\n", strs[i]);
		else
			break;
	}
	free(strs);
}

void DumpCallstack(void (*PrintOutFct) (const std::string&)) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	(*PrintOutFct) ("DumpCallstack: " + itoa(framesC) + " addresses:");
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			(*PrintOutFct) (std::string(" ") + strs[i] + "\n");
		else
			break;
	}
	free(strs);
}

#else

#include "StackWalker.h"  // Call Luke Stackwalker for help

typedef void (*PrintOutFct) (const std::string&);

// Override the default stackwalker with our own print functions
class PrintStackWalker : public StackWalker  {
private:
	PrintOutFct m_print;

public:
	PrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }
	void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
	{

	}

	void OnOutput(LPCSTR szText)
	{
		if (m_print == NULL)
			printf(szText);
		else
			m_print(std::string(szText));
		StackWalker::OnOutput(szText);
	}
};

void DumpCallstackPrintf(void* callpnt)
{
	PrintStackWalker sw;
	sw.ShowCallstack();

}
void DumpCallstack(void (*LineOutFct) (const std::string&))
{
	PrintStackWalker sw(LineOutFct);
	sw.ShowCallstack();
}

#endif

Logger notes(0,2,1000, "n: ");
Logger hints(0,1,100, "H: ");
Logger warnings(0,0,10, "W: ");
Logger errors(-1,-1,1, "E: ");

#include <iostream>
#include <sstream>
#include "ThreadPool.h"
#include "Options.h"
#include "console.h"
#include "StringUtils.h"

static SDL_mutex* globalCoutMutex = NULL;

Logger::Logger(int o, int ingame, int callst, const std::string& p)
: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {
	mutex = SDL_CreateMutex();
	if(!globalCoutMutex)
		globalCoutMutex = SDL_CreateMutex();
}

Logger::~Logger() {
	SDL_DestroyMutex(mutex); mutex = NULL;
	if(globalCoutMutex) {
		SDL_DestroyMutex(globalCoutMutex);
		globalCoutMutex = NULL;
	}
}

void Logger::lock() {
	SDL_mutexP(mutex);
}

void Logger::unlock() {
	SDL_mutexV(mutex);
}

static void CoutPrint(const std::string& str) {
	// TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.
	// TODO: c_str() is slow and not really needed here.
	printf("%s", str.c_str());
}

template<int col> void ConPrint(const std::string& str) {
	// TODO: Con_AddText adds a line but we only want to add str
	std::string buf = str;
	if(buf.size() > 0 && buf[buf.size()-1] == '\n') buf.erase(buf.size()-1);
	Con_AddText(col, buf, false);
}

// true if last was newline
static bool logger_output(Logger& log, const std::string& buf) {
	bool ret = true;
	if(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {
		SDL_mutexP(globalCoutMutex);
		ret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);
		//std::cout.flush();
		SDL_mutexV(globalCoutMutex);
	}
	if(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {
		DumpCallstackPrintf();
	}
	if(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {
		// the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this
		if(!strStartsWith(buf, "Ingame console: ")) {
			// we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level
			if(log.minIngameConVerb < 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);
			else if(log.minIngameConVerb == 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);
			else if(log.minIngameConVerb == 1)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);
			else if(log.minIngameConVerb < 5)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);
			else // >=5
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);
		}
		if(tLXOptions->iVerbosity >= log.minCallstackVerb) {
			DumpCallstack(ConPrint<CNC_DEV>);
		}
	}
	return ret;
}

Logger& Logger::flush() {
	lock();
	lastWasNewline = logger_output(*this, buffer);
	buffer = "";
	unlock();
	return *this;
}
<commit_msg>small fix<commit_after>/*
 *  Debug.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 01.01.09.
 *  code under LGPL
 *
 */

#include "Debug.h"
#include "StringUtils.h"

#ifdef WIN32

void RaiseDebugger() {
#ifdef DEBUG
	// TODO: what does that do if not run in a debugger?
	// If it just does nothing then, remove the surrounding #ifdef DEBUG
	// I read about a Win32's IsDebuggerPresent() function, perhaps you should use that one here.
	__asm  { int 3 };
#endif
}

#else

#if defined(__APPLE__)

#include <cassert>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>

// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
static bool AmIBeingDebugged()
    // Returns true if the current process is being debugged (either
    // running under the debugger or has a debugger attached post facto).
{
	// Initialize mib, which tells sysctl what info we want.  In this case,
	// we're looking for information about a specific process ID.
	int mib[] =
	{
		CTL_KERN,
		KERN_PROC,
		KERN_PROC_PID,
		getpid()
	};

	// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE.  The source and
	// binary interfaces may change.
	struct kinfo_proc info;
	size_t info_size = sizeof ( info );

	int sysctl_result = sysctl ( mib, sizeof(mib) / sizeof(*mib), &info, &info_size, NULL, 0 );
	if ( sysctl_result != 0 )
		return false;

	// This process is being debugged if the P_TRACED flag is set.
	return ( info.kp_proc.p_flag & P_TRACED ) != 0;
}

#else

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>

static bool AmIBeingDebugged() {
	// We can look in /proc/self/status for TracerPid.  We are likely used in crash
	// handling, so we are careful not to use the heap or have side effects.
	int status_fd = open("/proc/self/status", O_RDONLY);
	if (status_fd == -1)
		return false;

	// We assume our line will be in the first 1024 characters and that we can
	// read this much all at once.  In practice this will generally be true.
	// This simplifies and speeds up things considerably.
	char buf[1024];

	ssize_t num_read = read(status_fd, buf, sizeof(buf));
	fix_markend(buf);
	close(status_fd);
	if (num_read <= 0) return false;

	const char* searchStr = "TracerPid:\t";
	const char* f = strstr(buf, searchStr);
	if(f == NULL) return false;

	// Our pid is 0 without a debugger, assume this for any pid starting with 0.
	f += strlen(searchStr);
	return f < &buf[num_read] && *f != '0';
}

#endif // OSX/LINUX

#include <signal.h>

void RaiseDebugger() {
	if(AmIBeingDebugged()) {
		printf("I am being debugged, raising debugger ...\n");
		raise(SIGABRT);
	} else
		printf("I am not being debugged, ignoring debugger raise.\n");
}

#endif

#ifdef WIN32
void OlxWriteCoreDump(const char* file_postfix) {}

#else

#ifdef GCOREDUMPER
#include <google/coredumper.h>
#endif
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <cstdio>

#ifndef GCOREDUMPER
static void GdbWriteCoreDump(const char* fname) {
	// WARNING: this is terribly slow like this
	char gdbparam[1000];
	sprintf(gdbparam,
			"attach %i \n"
			"gcore %s \n"
			"detach \n"
			"quit \n",
			getpid(), fname);
	FILE* p = popen("gdb -q", "w");
	if(p) {
		fprintf(p, "%s", gdbparam);
		fflush(p);
		int status = 0; wait(&status);
		pclose(p);
	}
}
#endif

void OlxWriteCoreDump(const char* file_postfix) {
	char corefile[PATH_MAX + 100];
	if(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, "");
	strcat(corefile, "/core.OpenLieroX");
	if(file_postfix) { strcat(corefile, "."); strcat(corefile, file_postfix); }
	printf("writing coredump to %s\n", corefile);

	printf("dumping core ... "); fflush(0);
#ifdef GCOREDUMPER
	WriteCoreDump(corefile);
#else
	GdbWriteCoreDump(corefile);
#endif
	printf("ready\n");
}

#endif

#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>

void DumpCallstackPrintf(void* callpnt) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	printf("backtrace() returned %d addresses\n", framesC);
	if(callpnt != NULL && framesC > 3) callstack[3] = callpnt; // expected to be called from signal handler
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			printf("%s\n", strs[i]);
		else
			break;
	}
	free(strs);
}

void DumpCallstack(void (*PrintOutFct) (const std::string&)) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	(*PrintOutFct) ("DumpCallstack: " + itoa(framesC) + " addresses:");
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			(*PrintOutFct) (std::string(" ") + strs[i] + "\n");
		else
			break;
	}
	free(strs);
}

#else

#include "StackWalker.h"  // Call Luke Stackwalker for help

typedef void (*PrintOutFct) (const std::string&);

// Override the default stackwalker with our own print functions
class PrintStackWalker : public StackWalker  {
private:
	PrintOutFct m_print;

public:
	PrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }
	void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
	{

	}

	void OnOutput(LPCSTR szText)
	{
		if (m_print == NULL)
			printf(szText);
		else
			m_print(std::string(szText));
		StackWalker::OnOutput(szText);
	}
};

void DumpCallstackPrintf(void* callpnt)
{
	PrintStackWalker sw;
	sw.ShowCallstack();

}
void DumpCallstack(void (*LineOutFct) (const std::string&))
{
	PrintStackWalker sw(LineOutFct);
	sw.ShowCallstack();
}

#endif

Logger notes(0,2,1000, "n: ");
Logger hints(0,1,100, "H: ");
Logger warnings(0,0,10, "W: ");
Logger errors(-1,-1,1, "E: ");

#include <iostream>
#include <sstream>
#include "ThreadPool.h"
#include "Options.h"
#include "console.h"
#include "StringUtils.h"

static SDL_mutex* globalCoutMutex = NULL;

Logger::Logger(int o, int ingame, int callst, const std::string& p)
: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {
	mutex = SDL_CreateMutex();
	if(!globalCoutMutex)
		globalCoutMutex = SDL_CreateMutex();
}

Logger::~Logger() {
	SDL_DestroyMutex(mutex); mutex = NULL;
	if(globalCoutMutex) {
		SDL_DestroyMutex(globalCoutMutex);
		globalCoutMutex = NULL;
	}
}

void Logger::lock() {
	SDL_mutexP(mutex);
}

void Logger::unlock() {
	SDL_mutexV(mutex);
}

static void CoutPrint(const std::string& str) {
	// TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.
	// TODO: c_str() is slow and not really needed here.
	printf("%s", str.c_str());
}

template<int col> void ConPrint(const std::string& str) {
	// TODO: Con_AddText adds a line but we only want to add str
	std::string buf = str;
	if(buf.size() > 0 && buf[buf.size()-1] == '\n') buf.erase(buf.size()-1);
	Con_AddText(col, buf, false);
}

// true if last was newline
static bool logger_output(Logger& log, const std::string& buf) {
	bool ret = true;
	if(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {
		SDL_mutexP(globalCoutMutex);
		ret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);
		//std::cout.flush();
		SDL_mutexV(globalCoutMutex);
	}
	if(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {
		DumpCallstackPrintf();
	}
	if(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {
		// the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this
		if(!strStartsWith(buf, "Ingame console: ")) {
			// we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level
			if(log.minIngameConVerb < 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);
			else if(log.minIngameConVerb == 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);
			else if(log.minIngameConVerb == 1)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);
			else if(log.minIngameConVerb < 5)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);
			else // >=5
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);
		}
		if(tLXOptions->iVerbosity >= log.minCallstackVerb) {
			DumpCallstack(ConPrint<CNC_DEV>);
		}
	}
	return ret;
}

Logger& Logger::flush() {
	lock();
	lastWasNewline = logger_output(*this, buffer);
	buffer = "";
	unlock();
	return *this;
}
<|endoftext|>


<commit_before>/*
 *  Debug.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 01.01.09.
 *  code under LGPL
 *
 */

#include "Debug.h"

#ifdef WIN32
void OlxWriteCoreDump(const char* file_postfix) {}

#else

#ifdef GCOREDUMPER
#include <google/coredumper.h>
#endif
#include <unistd.h>
#include <sys/types.h>
#include <cstring>
#include <cstdio>

#ifndef GCOREDUMPER
static void GdbWriteCoreDump(const char* fname) {
	// WARNING: this is terribly slow like this
	char gdbparam[1000];
	sprintf(gdbparam,
			"attach %i \n"
			"gcore %s \n"
			"detach \n",
			getpid(), fname);
	FILE* p = popen("gdb", "w");
	if(p) {
		fprintf(p, "%s", gdbparam);
		fflush(p);
		pclose(p);
	}
}
#endif

void OlxWriteCoreDump(const char* file_postfix) {
	char corefile[PATH_MAX + 100];
	if(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, "");
	strcat(corefile, "/core.OpenLieroX");
	if(file_postfix) { strcat(corefile, "."); strcat(corefile, file_postfix); }
	printf("writing coredump to %s\n", corefile);

	printf("dumping core ... "); fflush(0);
#ifdef GCOREDUMPER
	WriteCoreDump(corefile);
#else
	GdbWriteCoreDump(corefile);
#endif
	printf("ready\n");
}

#endif

#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>

void DumpCallstackPrintf(void* callpnt) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	printf("backtrace() returned %d addresses\n", framesC);
	if(callpnt != NULL && framesC > 3) callstack[3] = callpnt; // expected to be called from signal handler
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			printf("%s\n", strs[i]);
		else
			break;
	}
	free(strs);
}

void DumpCallstack(void (*PrintOutFct) (const std::string&)) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	(*PrintOutFct) ("DumpCallstack: " + itoa(framesC) + " addresses:");
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			(*PrintOutFct) (std::string(" ") + strs[i] + "\n");
		else
			break;
	}
	free(strs);
}

#else

#include "StackWalker.h"  // Call Luke Stackwalker for help

typedef void (*PrintOutFct) (const std::string&);

// Override the default stackwalker with our own print functions
class PrintStackWalker : public StackWalker  {
private:
	PrintOutFct m_print;

public:
	PrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }
	void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
	{

	}

	void OnOutput(LPCSTR szText)
	{
		if (m_print == NULL)
			printf(szText);
		else
			m_print(std::string(szText));
		StackWalker::OnOutput(szText);
	}
};

void DumpCallstackPrintf(void* callpnt)
{
	PrintStackWalker sw;
	sw.ShowCallstack();

}
void DumpCallstack(void (*LineOutFct) (const std::string&))
{
	PrintStackWalker sw(LineOutFct);
	sw.ShowCallstack();
}

#endif

Logger notes(0,2,1000, "n: ");
Logger hints(0,1,100, "H: ");
Logger warnings(0,0,10, "W: ");
Logger errors(-1,-1,1, "E: ");

#include <iostream>
#include <sstream>
#include "ThreadPool.h"
#include "Options.h"
#include "console.h"
#include "StringUtils.h"

static SDL_mutex* globalCoutMutex = NULL;

Logger::Logger(int o, int ingame, int callst, const std::string& p)
: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {
	mutex = SDL_CreateMutex();
	if(!globalCoutMutex)
		globalCoutMutex = SDL_CreateMutex();
}

Logger::~Logger() {
	SDL_DestroyMutex(mutex); mutex = NULL;
	if(globalCoutMutex) {
		SDL_DestroyMutex(globalCoutMutex);
		globalCoutMutex = NULL;
	}
}

void Logger::lock() {
	SDL_mutexP(mutex);
}

void Logger::unlock() {
	SDL_mutexV(mutex);
}

static void CoutPrint(const std::string& str) {
	// TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.
	// TODO: c_str() is slow and not really needed here.
	printf("%s", str.c_str());
}

template<int col> void ConPrint(const std::string& str) {
	// TODO: Con_AddText adds a line but we only want to add str
	std::string buf = str;
	if(buf.size() > 0 && buf[buf.size()-1] == '\n') buf.erase(buf.size()-1);
	Con_AddText(col, buf, false);
}

// true if last was newline
static bool logger_output(Logger& log, const std::string& buf) {
	bool ret = true;
	if(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {
		SDL_mutexP(globalCoutMutex);
		ret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);
		//std::cout.flush();
		SDL_mutexV(globalCoutMutex);
	}
	if(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {
		DumpCallstackPrintf();
	}
	if(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {
		// the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this
		if(!strStartsWith(buf, "Ingame console: ")) {
			// we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level
			if(log.minIngameConVerb < 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);
			else if(log.minIngameConVerb == 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);
			else if(log.minIngameConVerb == 1)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);
			else if(log.minIngameConVerb < 5)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);
			else // >=5
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);
		}
		if(tLXOptions->iVerbosity >= log.minCallstackVerb) {
			DumpCallstack(ConPrint<CNC_DEV>);
		}
	}
	return ret;
}

Logger& Logger::flush() {
	lock();
	lastWasNewline = logger_output(*this, buffer);
	buffer = "";
	unlock();
	return *this;
}
<commit_msg>wait until gdb is ready with coredumping<commit_after>/*
 *  Debug.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 01.01.09.
 *  code under LGPL
 *
 */

#include "Debug.h"

#ifdef WIN32
void OlxWriteCoreDump(const char* file_postfix) {}

#else

#ifdef GCOREDUMPER
#include <google/coredumper.h>
#endif
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <cstdio>

#ifndef GCOREDUMPER
static void GdbWriteCoreDump(const char* fname) {
	// WARNING: this is terribly slow like this
	char gdbparam[1000];
	sprintf(gdbparam,
			"attach %i \n"
			"gcore %s \n"
			"detach \n"
			"quit \n",
			getpid(), fname);
	FILE* p = popen("gdb -q", "w");
	if(p) {
		fprintf(p, "%s", gdbparam);
		fflush(p);
		int status = 0; wait(&status);
		pclose(p);
	}
}
#endif

void OlxWriteCoreDump(const char* file_postfix) {
	char corefile[PATH_MAX + 100];
	if(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, "");
	strcat(corefile, "/core.OpenLieroX");
	if(file_postfix) { strcat(corefile, "."); strcat(corefile, file_postfix); }
	printf("writing coredump to %s\n", corefile);

	printf("dumping core ... "); fflush(0);
#ifdef GCOREDUMPER
	WriteCoreDump(corefile);
#else
	GdbWriteCoreDump(corefile);
#endif
	printf("ready\n");
}

#endif

#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>

void DumpCallstackPrintf(void* callpnt) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	printf("backtrace() returned %d addresses\n", framesC);
	if(callpnt != NULL && framesC > 3) callstack[3] = callpnt; // expected to be called from signal handler
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			printf("%s\n", strs[i]);
		else
			break;
	}
	free(strs);
}

void DumpCallstack(void (*PrintOutFct) (const std::string&)) {
	void *callstack[128];
	int framesC = backtrace(callstack, sizeof(callstack));
	(*PrintOutFct) ("DumpCallstack: " + itoa(framesC) + " addresses:");
	char** strs = backtrace_symbols(callstack, framesC);
	for(int i = 0; i < framesC; ++i) {
		if(strs[i])
			(*PrintOutFct) (std::string(" ") + strs[i] + "\n");
		else
			break;
	}
	free(strs);
}

#else

#include "StackWalker.h"  // Call Luke Stackwalker for help

typedef void (*PrintOutFct) (const std::string&);

// Override the default stackwalker with our own print functions
class PrintStackWalker : public StackWalker  {
private:
	PrintOutFct m_print;

public:
	PrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }
	void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
	{

	}

	void OnOutput(LPCSTR szText)
	{
		if (m_print == NULL)
			printf(szText);
		else
			m_print(std::string(szText));
		StackWalker::OnOutput(szText);
	}
};

void DumpCallstackPrintf(void* callpnt)
{
	PrintStackWalker sw;
	sw.ShowCallstack();

}
void DumpCallstack(void (*LineOutFct) (const std::string&))
{
	PrintStackWalker sw(LineOutFct);
	sw.ShowCallstack();
}

#endif

Logger notes(0,2,1000, "n: ");
Logger hints(0,1,100, "H: ");
Logger warnings(0,0,10, "W: ");
Logger errors(-1,-1,1, "E: ");

#include <iostream>
#include <sstream>
#include "ThreadPool.h"
#include "Options.h"
#include "console.h"
#include "StringUtils.h"

static SDL_mutex* globalCoutMutex = NULL;

Logger::Logger(int o, int ingame, int callst, const std::string& p)
: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {
	mutex = SDL_CreateMutex();
	if(!globalCoutMutex)
		globalCoutMutex = SDL_CreateMutex();
}

Logger::~Logger() {
	SDL_DestroyMutex(mutex); mutex = NULL;
	if(globalCoutMutex) {
		SDL_DestroyMutex(globalCoutMutex);
		globalCoutMutex = NULL;
	}
}

void Logger::lock() {
	SDL_mutexP(mutex);
}

void Logger::unlock() {
	SDL_mutexV(mutex);
}

static void CoutPrint(const std::string& str) {
	// TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.
	// TODO: c_str() is slow and not really needed here.
	printf("%s", str.c_str());
}

template<int col> void ConPrint(const std::string& str) {
	// TODO: Con_AddText adds a line but we only want to add str
	std::string buf = str;
	if(buf.size() > 0 && buf[buf.size()-1] == '\n') buf.erase(buf.size()-1);
	Con_AddText(col, buf, false);
}

// true if last was newline
static bool logger_output(Logger& log, const std::string& buf) {
	bool ret = true;
	if(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {
		SDL_mutexP(globalCoutMutex);
		ret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);
		//std::cout.flush();
		SDL_mutexV(globalCoutMutex);
	}
	if(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {
		DumpCallstackPrintf();
	}
	if(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {
		// the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this
		if(!strStartsWith(buf, "Ingame console: ")) {
			// we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level
			if(log.minIngameConVerb < 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);
			else if(log.minIngameConVerb == 0)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);
			else if(log.minIngameConVerb == 1)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);
			else if(log.minIngameConVerb < 5)
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);
			else // >=5
				ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);
		}
		if(tLXOptions->iVerbosity >= log.minCallstackVerb) {
			DumpCallstack(ConPrint<CNC_DEV>);
		}
	}
	return ret;
}

Logger& Logger::flush() {
	lock();
	lastWasNewline = logger_output(*this, buffer);
	buffer = "";
	unlock();
	return *this;
}
<|endoftext|>


<commit_before>#include <iostream>

#include <SFML/Graphics.hpp>
#include "game.h"

Game::Game():
    playing(true),
    screen(),
    map(nullptr)
    //map_camera(nullptr),
    //unitRepository(nullptr)
{
    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;
    screen.create(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close, settings);
    screen.setFramerateLimit(IDEAL_FPS);
    screen.setMouseCursorVisible(false);

    if (!init()){
        std::cerr << "Failed to initialized game.";
        playing = false;
    }
}

int Game::execute() {

    sf::Clock clock;

  while(playing) {
    sf::Event event;
    actionMap.clearEvents();
    sf::Time dt = clock.restart();
    while(screen.pollEvent(event)) {
      actionMap.pushEvent(event);
    }

    updateState(dt);
    render();
  }

  return 0;
}

bool Game::init() {
  if (!terrain.loadFromFile("graphics/terrain.png")) {
    std::cout << "Failed to read graphics/terrain.png data" << std::endl;
    return false;
  }

  sf::Image temp;
  if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
    std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
    return false;
  }

  temp.createMaskFromColor(sf::Color(255, 0, 255));
  shroud_edges.loadFromImage(temp);

  map.reset(new Map(terrain, shroud_edges));
  map->load("maps/4PL_Mountains.ini");

  camera.reset({0,0,800,600});
  screen.setView(camera);

  //init a trike
  sf::Image trikeImage;
  trikeImage.loadFromFile("graphics/Unit_Trike.bmp");
  trikeImage.createMaskFromColor(sf::Color(0,0,0));
  sf::Texture* trikeTexture = new sf::Texture; //yes we are leaking! Player should own this
  trikeTexture->loadFromImage(trikeImage);

  sf::Image trikeShadowImage;
  trikeShadowImage.loadFromFile("graphics/Unit_Trike_s.bmp");
  trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));
  sf::Texture* trikeShadowTexture = new sf::Texture;
  trikeShadowTexture->loadFromImage(trikeShadowImage);

  sf::Image selectedImage;
  selectedImage.loadFromFile("graphics/selected.bmp");
  selectedImage.createMaskFromColor(sf::Color(255, 0, 255));
  sf::Texture* selectedTexture = new sf::Texture; //more leaks!
  selectedTexture->loadFromImage(selectedImage);
  units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));

  //remove shroud here
  map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);

  ////init two players
  //int idCount = 0;
  //players.emplace_back(House::Sardaukar, idCount++);
  //players.emplace_back(House::Harkonnen, idCount++);

  //units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));

  //// soldiers
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));

  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));

  //thor Actions here

  actionMap["boxStart"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);
  actionMap["orderMove"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);
  actionMap["boxDrag"] = thor::Action(sf::Mouse::Left, thor::Action::Hold);
  actionMap["boxRelease"] = thor::Action(sf::Mouse::Left, thor::Action::ReleaseOnce);
  actionMap["deselectAll"] = thor::Action(sf::Mouse::Right, thor::Action::PressOnce);
  actionMap["close"] = thor::Action(sf::Event::Closed) || thor::Action(sf::Keyboard::Q, thor::Action::PressOnce);
  actionMap["cameraLeft"] = thor::Action(sf::Keyboard::Left, thor::Action::Hold);
  actionMap["cameraRight"] = thor::Action(sf::Keyboard::Right, thor::Action::Hold);
  actionMap["cameraUp"] = thor::Action(sf::Keyboard::Up, thor::Action::Hold);
  actionMap["cameraDown"] = thor::Action(sf::Keyboard::Down, thor::Action::Hold);

  typedef thor::ActionContext<std::string> actionContext;

  system.connect("close", [this](actionContext){playing = false;});

  system.connect("boxRelease", [this](actionContext){
    for (auto& unit : units){
      if (box.intersects(unit->getBounds())){
        unit->select();
        system.connect("orderMove", [this, &unit](actionContext context){
          unit->order_move(screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y)));
        });
        mouse.setType(Mouse::Type::Move); //at least one unit selected...
      }
    }
    box.clear();
  });

  system.connect("boxStart", [this](actionContext context){
    sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y));
    box.setTopLeft(toSet);
  });

  system.connect("deselectAll", [this](actionContext){
//    system.clearConnections("orderMove"); // -> This is bugged in Thor
    mouse.setType(Mouse::Type::Default);
    for (auto& unit : units)
      unit->unselect();
  });

  system.connect("boxDrag", [this](actionContext){
    box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));
  });

  const float cameraSpeed = 15.f;

  moveVector = sf::Vector2f();

  system.connect("cameraLeft", [this, cameraSpeed](actionContext) {moveVector.x -= cameraSpeed;});
  system.connect("cameraRight", [this, cameraSpeed](actionContext){moveVector.x = cameraSpeed; });
  system.connect("cameraUp", [this, cameraSpeed](actionContext)   {moveVector.y -= cameraSpeed;});
  system.connect("cameraDown", [this, cameraSpeed](actionContext) {moveVector.y = cameraSpeed; });

  return true;
}

void Game::render() {
  screen.clear();

  screen.setView(camera);

  screen.draw(*map);

  for (const auto& unit : units)
      screen.draw(*unit);

  map->drawShrouded(screen, sf::RenderStates::Default);

  screen.draw(box);

  screen.draw(fpsCounter);

  screen.setView(camera);
  screen.draw(mouse);

  screen.display();
}

void Game::updateState(sf::Time dt) {
  actionMap.invokeCallbacks(system, &screen);

  mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));

  sf::Vector2f topLeft = camera.getCenter() - (camera.getSize() / 2.f);
  sf::Vector2f downRight = camera.getCenter() + (camera.getSize() / 2.f);

  if (moveVector.x < 0 && topLeft.x <= 0) moveVector.x = 0;
  if (moveVector.y < 0 && topLeft.y <= 0) moveVector.y = 0;
  if (moveVector.x > 0 && downRight.x >= (map->getMaxWidth() + 3) * Cell::TILE_SIZE) moveVector.x = 0;
  if (moveVector.y > 0 && downRight.y >= (map->getMaxHeight() + 3) * Cell::TILE_SIZE) moveVector.y = 0;
  camera.move(moveVector);
  moveVector = sf::Vector2f();

  for (auto& unit: units){
      unit->updateState();
  }

  fpsCounter.update(dt);
  map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));
}
<commit_msg>map camera boundaries are now respected for every camera speed<commit_after>#include <iostream>

#include <SFML/Graphics.hpp>
#include "game.h"

Game::Game():
    playing(true),
    screen(),
    map(nullptr)
    //map_camera(nullptr),
    //unitRepository(nullptr)
{
    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;
    screen.create(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close, settings);
    screen.setFramerateLimit(IDEAL_FPS);
    screen.setMouseCursorVisible(false);

    if (!init()){
        std::cerr << "Failed to initialized game.";
        playing = false;
    }
}

int Game::execute() {

    sf::Clock clock;

  while(playing) {
    sf::Event event;
    actionMap.clearEvents();
    sf::Time dt = clock.restart();
    while(screen.pollEvent(event)) {
      actionMap.pushEvent(event);
    }

    updateState(dt);
    render();
  }

  return 0;
}

bool Game::init() {
  if (!terrain.loadFromFile("graphics/terrain.png")) {
    std::cout << "Failed to read graphics/terrain.png data" << std::endl;
    return false;
  }

  sf::Image temp;
  if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
    std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
    return false;
  }

  temp.createMaskFromColor(sf::Color(255, 0, 255));
  shroud_edges.loadFromImage(temp);

  map.reset(new Map(terrain, shroud_edges));
  map->load("maps/4PL_Mountains.ini");

  camera.reset({0,0,800,600});
  screen.setView(camera);

  //init a trike
  sf::Image trikeImage;
  trikeImage.loadFromFile("graphics/Unit_Trike.bmp");
  trikeImage.createMaskFromColor(sf::Color(0,0,0));
  sf::Texture* trikeTexture = new sf::Texture; //yes we are leaking! Player should own this
  trikeTexture->loadFromImage(trikeImage);

  sf::Image trikeShadowImage;
  trikeShadowImage.loadFromFile("graphics/Unit_Trike_s.bmp");
  trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));
  sf::Texture* trikeShadowTexture = new sf::Texture;
  trikeShadowTexture->loadFromImage(trikeShadowImage);

  sf::Image selectedImage;
  selectedImage.loadFromFile("graphics/selected.bmp");
  selectedImage.createMaskFromColor(sf::Color(255, 0, 255));
  sf::Texture* selectedTexture = new sf::Texture; //more leaks!
  selectedTexture->loadFromImage(selectedImage);
  units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));

  //remove shroud here
  map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);

  ////init two players
  //int idCount = 0;
  //players.emplace_back(House::Sardaukar, idCount++);
  //players.emplace_back(House::Harkonnen, idCount++);

  //units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));

  //// soldiers
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));

  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));

  //thor Actions here

  actionMap["boxStart"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);
  actionMap["orderMove"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);
  actionMap["boxDrag"] = thor::Action(sf::Mouse::Left, thor::Action::Hold);
  actionMap["boxRelease"] = thor::Action(sf::Mouse::Left, thor::Action::ReleaseOnce);
  actionMap["deselectAll"] = thor::Action(sf::Mouse::Right, thor::Action::PressOnce);
  actionMap["close"] = thor::Action(sf::Event::Closed) || thor::Action(sf::Keyboard::Q, thor::Action::PressOnce);
  actionMap["cameraLeft"] = thor::Action(sf::Keyboard::Left, thor::Action::Hold);
  actionMap["cameraRight"] = thor::Action(sf::Keyboard::Right, thor::Action::Hold);
  actionMap["cameraUp"] = thor::Action(sf::Keyboard::Up, thor::Action::Hold);
  actionMap["cameraDown"] = thor::Action(sf::Keyboard::Down, thor::Action::Hold);

  typedef thor::ActionContext<std::string> actionContext;

  system.connect("close", [this](actionContext){playing = false;});

  system.connect("boxRelease", [this](actionContext){
    for (auto& unit : units){
      if (box.intersects(unit->getBounds())){
        unit->select();
        system.connect("orderMove", [this, &unit](actionContext context){
          unit->order_move(screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y)));
        });
        mouse.setType(Mouse::Type::Move); //at least one unit selected...
      }
    }
    box.clear();
  });

  system.connect("boxStart", [this](actionContext context){
    sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y));
    box.setTopLeft(toSet);
  });

  system.connect("deselectAll", [this](actionContext){
//    system.clearConnections("orderMove"); // -> This is bugged in Thor
    mouse.setType(Mouse::Type::Default);
    for (auto& unit : units)
      unit->unselect();
  });

  system.connect("boxDrag", [this](actionContext){
    box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));
  });

  const float cameraSpeed = 15.f;

  moveVector = sf::Vector2f();

  system.connect("cameraLeft", [this, cameraSpeed](actionContext) {moveVector.x -= cameraSpeed;});
  system.connect("cameraRight", [this, cameraSpeed](actionContext){moveVector.x = cameraSpeed; });
  system.connect("cameraUp", [this, cameraSpeed](actionContext)   {moveVector.y -= cameraSpeed;});
  system.connect("cameraDown", [this, cameraSpeed](actionContext) {moveVector.y = cameraSpeed; });

  return true;
}

void Game::render() {
  screen.clear();

  screen.setView(camera);

  screen.draw(*map);

  for (const auto& unit : units)
      screen.draw(*unit);

  map->drawShrouded(screen, sf::RenderStates::Default);

  screen.draw(box);

  screen.draw(fpsCounter);

  screen.setView(camera);

  screen.draw(mouse);

  screen.display();
}

void Game::updateState(sf::Time dt) {
  actionMap.invokeCallbacks(system, &screen);

  mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));

  camera.move(moveVector);
  sf::Vector2f half_of_camera = camera.getSize() / 2.f;
  sf::Vector2f topLeft = camera.getCenter() - (half_of_camera);
  sf::Vector2f downRight = camera.getCenter() + (half_of_camera);

  if (topLeft.x <= Cell::TILE_SIZE) camera.setCenter(half_of_camera.x + Cell::TILE_SIZE, camera.getCenter().y);
  if (topLeft.y <= Cell::TILE_SIZE) camera.setCenter(camera.getCenter().x, half_of_camera.y + Cell::TILE_SIZE);

  int max_width = (map->getMaxWidth() + 1) * Cell::TILE_SIZE;
  int max_height = (map->getMaxHeight() + 1) * Cell::TILE_SIZE;

  if (downRight.x >= max_width) camera.setCenter(max_width - half_of_camera.x, camera.getCenter().y);
  if (downRight.y >= max_height) camera.setCenter(camera.getCenter().x, max_height - half_of_camera.y);

  moveVector = sf::Vector2f();

  for (auto& unit: units){
      unit->updateState();
  }

  fpsCounter.update(dt);
  map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sqlite3.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <zlib.h>
#include <math.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <protozero/pbf_reader.hpp>
#include "mvt.hpp"
#include "projection.hpp"
#include "geometry.hpp"
#include "write_json.hpp"

int minzoom = 0;
int maxzoom = 32;
bool force = false;

void do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, unsigned y) {
	printf("{ \"zoom\": %d, \"x\": %u, \"y\": %u, \"bytes\": %zu, \"compressed\": %s", z, x, y, size, compressed ? "true" : "false");

	printf(", \"layers\": { ");
	for (size_t i = 0; i < tile.layers.size(); i++) {
		if (i != 0) {
			printf(", ");
		}
		fprintq(stdout, tile.layers[i].name.c_str());

		int points = 0, lines = 0, polygons = 0;
		for (size_t j = 0; j < tile.layers[i].features.size(); j++) {
			if (tile.layers[i].features[j].type == mvt_point) {
				points++;
			} else if (tile.layers[i].features[j].type == mvt_linestring) {
				lines++;
			} else if (tile.layers[i].features[j].type == mvt_polygon) {
				polygons++;
			}
		}

		printf(": { \"points\": %d, \"lines\": %d, \"polygons\": %d, \"extent\": %lld }", points, lines, polygons, tile.layers[i].extent);
	}

	printf(" } }\n");
}

void handle(std::string message, int z, unsigned x, unsigned y, int describe, std::set<std::string> const &to_decode, bool pipeline, bool stats) {
	mvt_tile tile;
	bool was_compressed;

	try {
		if (!tile.decode(message, was_compressed)) {
			fprintf(stderr, "Couldn't parse tile %d/%u/%u\n", z, x, y);
			exit(EXIT_FAILURE);
		}
	} catch (protozero::unknown_pbf_wire_type_exception e) {
		fprintf(stderr, "PBF decoding error in tile %d/%u/%u\n", z, x, y);
		exit(EXIT_FAILURE);
	}

	if (stats) {
		do_stats(tile, message.size(), was_compressed, z, x, y);
		return;
	}

	if (!pipeline) {
		printf("{ \"type\": \"FeatureCollection\"");

		if (describe) {
			printf(", \"properties\": { \"zoom\": %d, \"x\": %d, \"y\": %d", z, x, y);
			if (!was_compressed) {
				printf(", \"compressed\": false");
			}
			printf(" }");

			if (projection != projections) {
				printf(", \"crs\": { \"type\": \"name\", \"properties\": { \"name\": ");
				fprintq(stdout, projection->alias);
				printf(" } }");
			}
		}

		printf(", \"features\": [\n");
	}

	bool first_layer = true;
	for (size_t l = 0; l < tile.layers.size(); l++) {
		mvt_layer &layer = tile.layers[l];

		if (layer.extent <= 0) {
			fprintf(stderr, "Impossible layer extent %lld in mbtiles\n", layer.extent);
			exit(EXIT_FAILURE);
		}

		if (to_decode.size() != 0 && !to_decode.count(layer.name)) {
			continue;
		}

		if (!pipeline) {
			if (describe) {
				if (!first_layer) {
					printf(",\n");
				}

				printf("{ \"type\": \"FeatureCollection\"");
				printf(", \"properties\": { \"layer\": ");
				fprintq(stdout, layer.name.c_str());
				printf(", \"version\": %d, \"extent\": %lld", layer.version, layer.extent);
				printf(" }");
				printf(", \"features\": [\n");

				first_layer = false;
			}
		}

		// X and Y are unsigned, so no need to check <0
		if (x > (1 << z) || y > (1 << z)) {
			fprintf(stderr, "Impossible tile %d/%u/%u\n", z, x, y);
			exit(EXIT_FAILURE);
		}

		layer_to_geojson(stdout, layer, z, x, y, !pipeline, pipeline, pipeline, 0, 0, 0, !force);

		if (!pipeline) {
			if (describe) {
				printf("] }\n");
			}
		}
	}

	if (!pipeline) {
		printf("] }\n");
	}
}

void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) {
	sqlite3 *db;
	int oz = z;
	unsigned ox = x, oy = y;

	int fd = open(fname, O_RDONLY | O_CLOEXEC);
	if (fd >= 0) {
		struct stat st;
		if (fstat(fd, &st) == 0) {
			if (st.st_size < 50 * 1024 * 1024) {
				char *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
				if (map != NULL && map != MAP_FAILED) {
					if (strcmp(map, "SQLite format 3") != 0) {
						if (z >= 0) {
							std::string s = std::string(map, st.st_size);
							handle(s, z, x, y, 1, to_decode, pipeline, stats);
							munmap(map, st.st_size);
							return;
						} else {
							fprintf(stderr, "Must specify zoom/x/y to decode a single pbf file\n");
							exit(EXIT_FAILURE);
						}
					}
				}
				munmap(map, st.st_size);
			}
		} else {
			perror("fstat");
		}
		if (close(fd) != 0) {
			perror("close");
			exit(EXIT_FAILURE);
		}
	} else {
		perror(fname);
	}

	if (sqlite3_open(fname, &db) != SQLITE_OK) {
		fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db));
		exit(EXIT_FAILURE);
	}

	if (z < 0) {
		int within = 0;

		if (!pipeline && !stats) {
			printf("{ \"type\": \"FeatureCollection\", \"properties\": {\n");

			const char *sql2 = "SELECT name, value from metadata order by name;";
			sqlite3_stmt *stmt2;
			if (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) {
				fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
				exit(EXIT_FAILURE);
			}

			while (sqlite3_step(stmt2) == SQLITE_ROW) {
				if (within) {
					printf(",\n");
				}
				within = 1;

				const unsigned char *name = sqlite3_column_text(stmt2, 0);
				const unsigned char *value = sqlite3_column_text(stmt2, 1);

				if (name == NULL || value == NULL) {
					fprintf(stderr, "Corrupt mbtiles file: null metadata\n");
					exit(EXIT_FAILURE);
				}

				fprintq(stdout, (char *) name);
				printf(": ");
				fprintq(stdout, (char *) value);
			}

			sqlite3_finalize(stmt2);
		}

		if (stats) {
			printf("[\n");
		}

		const char *sql = "SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;";
		sqlite3_stmt *stmt;
		if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
			fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
			exit(EXIT_FAILURE);
		}

		sqlite3_bind_int(stmt, 1, minzoom);
		sqlite3_bind_int(stmt, 2, maxzoom);

		if (!pipeline && !stats) {
			printf("\n}, \"features\": [\n");
		}

		within = 0;
		while (sqlite3_step(stmt) == SQLITE_ROW) {
			if (!pipeline && !stats) {
				if (within) {
					printf(",\n");
				}
				within = 1;
			}
			if (stats) {
				if (within) {
					printf(",\n");
				}
				within = 1;
			}

			int len = sqlite3_column_bytes(stmt, 0);
			int tz = sqlite3_column_int(stmt, 1);
			int tx = sqlite3_column_int(stmt, 2);
			int ty = sqlite3_column_int(stmt, 3);

			if (tz < 0 || tz >= 32) {
				fprintf(stderr, "Impossible zoom level %d in mbtiles\n", tz);
				exit(EXIT_FAILURE);
			}

			ty = (1LL << tz) - 1 - ty;
			const char *s = (const char *) sqlite3_column_blob(stmt, 0);

			handle(std::string(s, len), tz, tx, ty, 1, to_decode, pipeline, stats);
		}

		if (!pipeline && !stats) {
			printf("] }\n");
		}
		if (stats) {
			printf("]\n");
		}

		sqlite3_finalize(stmt);
	} else {
		int handled = 0;
		while (z >= 0 && !handled) {
			const char *sql = "SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;";
			sqlite3_stmt *stmt;
			if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
				fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
				exit(EXIT_FAILURE);
			}

			sqlite3_bind_int(stmt, 1, z);
			sqlite3_bind_int(stmt, 2, x);
			sqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y);

			while (sqlite3_step(stmt) == SQLITE_ROW) {
				int len = sqlite3_column_bytes(stmt, 0);
				const char *s = (const char *) sqlite3_column_blob(stmt, 0);

				if (z != oz) {
					fprintf(stderr, "%s: Warning: using tile %d/%u/%u instead of %d/%u/%u\n", fname, z, x, y, oz, ox, oy);
				}

				handle(std::string(s, len), z, x, y, 0, to_decode, pipeline, stats);
				handled = 1;
			}

			sqlite3_finalize(stmt);

			z--;
			x /= 2;
			y /= 2;
		}
	}

	if (sqlite3_close(db) != SQLITE_OK) {
		fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db));
		exit(EXIT_FAILURE);
	}
}

void usage(char **argv) {
	fprintf(stderr, "Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\n", argv[0]);
	exit(EXIT_FAILURE);
}

int main(int argc, char **argv) {
	extern int optind;
	extern char *optarg;
	int i;
	std::set<std::string> to_decode;
	bool pipeline = false;
	bool stats = false;

	struct option long_options[] = {
		{"projection", required_argument, 0, 's'},
		{"maximum-zoom", required_argument, 0, 'z'},
		{"minimum-zoom", required_argument, 0, 'Z'},
		{"layer", required_argument, 0, 'l'},
		{"tag-layer-and-zoom", no_argument, 0, 'c'},
		{"stats", no_argument, 0, 'S'},
		{"force", no_argument, 0, 'f'},
		{0, 0, 0, 0},
	};

	std::string getopt_str;
	for (size_t lo = 0; long_options[lo].name != NULL; lo++) {
		if (long_options[lo].val > ' ') {
			getopt_str.push_back(long_options[lo].val);

			if (long_options[lo].has_arg == required_argument) {
				getopt_str.push_back(':');
			}
		}
	}

	while ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) {
		switch (i) {
		case 0:
			break;

		case 's':
			set_projection_or_exit(optarg);
			break;

		case 'z':
			maxzoom = atoi(optarg);
			break;

		case 'Z':
			minzoom = atoi(optarg);
			break;

		case 'l':
			to_decode.insert(optarg);
			break;

		case 'c':
			pipeline = true;
			break;

		case 'S':
			stats = true;
			break;

		case 'f':
			force = true;
			break;

		default:
			usage(argv);
		}
	}

	if (argc == optind + 4) {
		decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats);
	} else if (argc == optind + 1) {
		decode(argv[optind], -1, -1, -1, to_decode, pipeline, stats);
	} else {
		usage(argv);
	}

	return 0;
}
<commit_msg>Fix signed comparison warning from g++<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sqlite3.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <zlib.h>
#include <math.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <protozero/pbf_reader.hpp>
#include "mvt.hpp"
#include "projection.hpp"
#include "geometry.hpp"
#include "write_json.hpp"

int minzoom = 0;
int maxzoom = 32;
bool force = false;

void do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, unsigned y) {
	printf("{ \"zoom\": %d, \"x\": %u, \"y\": %u, \"bytes\": %zu, \"compressed\": %s", z, x, y, size, compressed ? "true" : "false");

	printf(", \"layers\": { ");
	for (size_t i = 0; i < tile.layers.size(); i++) {
		if (i != 0) {
			printf(", ");
		}
		fprintq(stdout, tile.layers[i].name.c_str());

		int points = 0, lines = 0, polygons = 0;
		for (size_t j = 0; j < tile.layers[i].features.size(); j++) {
			if (tile.layers[i].features[j].type == mvt_point) {
				points++;
			} else if (tile.layers[i].features[j].type == mvt_linestring) {
				lines++;
			} else if (tile.layers[i].features[j].type == mvt_polygon) {
				polygons++;
			}
		}

		printf(": { \"points\": %d, \"lines\": %d, \"polygons\": %d, \"extent\": %lld }", points, lines, polygons, tile.layers[i].extent);
	}

	printf(" } }\n");
}

void handle(std::string message, int z, unsigned x, unsigned y, int describe, std::set<std::string> const &to_decode, bool pipeline, bool stats) {
	mvt_tile tile;
	bool was_compressed;

	try {
		if (!tile.decode(message, was_compressed)) {
			fprintf(stderr, "Couldn't parse tile %d/%u/%u\n", z, x, y);
			exit(EXIT_FAILURE);
		}
	} catch (protozero::unknown_pbf_wire_type_exception e) {
		fprintf(stderr, "PBF decoding error in tile %d/%u/%u\n", z, x, y);
		exit(EXIT_FAILURE);
	}

	if (stats) {
		do_stats(tile, message.size(), was_compressed, z, x, y);
		return;
	}

	if (!pipeline) {
		printf("{ \"type\": \"FeatureCollection\"");

		if (describe) {
			printf(", \"properties\": { \"zoom\": %d, \"x\": %d, \"y\": %d", z, x, y);
			if (!was_compressed) {
				printf(", \"compressed\": false");
			}
			printf(" }");

			if (projection != projections) {
				printf(", \"crs\": { \"type\": \"name\", \"properties\": { \"name\": ");
				fprintq(stdout, projection->alias);
				printf(" } }");
			}
		}

		printf(", \"features\": [\n");
	}

	bool first_layer = true;
	for (size_t l = 0; l < tile.layers.size(); l++) {
		mvt_layer &layer = tile.layers[l];

		if (layer.extent <= 0) {
			fprintf(stderr, "Impossible layer extent %lld in mbtiles\n", layer.extent);
			exit(EXIT_FAILURE);
		}

		if (to_decode.size() != 0 && !to_decode.count(layer.name)) {
			continue;
		}

		if (!pipeline) {
			if (describe) {
				if (!first_layer) {
					printf(",\n");
				}

				printf("{ \"type\": \"FeatureCollection\"");
				printf(", \"properties\": { \"layer\": ");
				fprintq(stdout, layer.name.c_str());
				printf(", \"version\": %d, \"extent\": %lld", layer.version, layer.extent);
				printf(" }");
				printf(", \"features\": [\n");

				first_layer = false;
			}
		}

		// X and Y are unsigned, so no need to check <0
		if (x > (1ULL << z) || y > (1ULL << z)) {
			fprintf(stderr, "Impossible tile %d/%u/%u\n", z, x, y);
			exit(EXIT_FAILURE);
		}

		layer_to_geojson(stdout, layer, z, x, y, !pipeline, pipeline, pipeline, 0, 0, 0, !force);

		if (!pipeline) {
			if (describe) {
				printf("] }\n");
			}
		}
	}

	if (!pipeline) {
		printf("] }\n");
	}
}

void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) {
	sqlite3 *db;
	int oz = z;
	unsigned ox = x, oy = y;

	int fd = open(fname, O_RDONLY | O_CLOEXEC);
	if (fd >= 0) {
		struct stat st;
		if (fstat(fd, &st) == 0) {
			if (st.st_size < 50 * 1024 * 1024) {
				char *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
				if (map != NULL && map != MAP_FAILED) {
					if (strcmp(map, "SQLite format 3") != 0) {
						if (z >= 0) {
							std::string s = std::string(map, st.st_size);
							handle(s, z, x, y, 1, to_decode, pipeline, stats);
							munmap(map, st.st_size);
							return;
						} else {
							fprintf(stderr, "Must specify zoom/x/y to decode a single pbf file\n");
							exit(EXIT_FAILURE);
						}
					}
				}
				munmap(map, st.st_size);
			}
		} else {
			perror("fstat");
		}
		if (close(fd) != 0) {
			perror("close");
			exit(EXIT_FAILURE);
		}
	} else {
		perror(fname);
	}

	if (sqlite3_open(fname, &db) != SQLITE_OK) {
		fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db));
		exit(EXIT_FAILURE);
	}

	if (z < 0) {
		int within = 0;

		if (!pipeline && !stats) {
			printf("{ \"type\": \"FeatureCollection\", \"properties\": {\n");

			const char *sql2 = "SELECT name, value from metadata order by name;";
			sqlite3_stmt *stmt2;
			if (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) {
				fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
				exit(EXIT_FAILURE);
			}

			while (sqlite3_step(stmt2) == SQLITE_ROW) {
				if (within) {
					printf(",\n");
				}
				within = 1;

				const unsigned char *name = sqlite3_column_text(stmt2, 0);
				const unsigned char *value = sqlite3_column_text(stmt2, 1);

				if (name == NULL || value == NULL) {
					fprintf(stderr, "Corrupt mbtiles file: null metadata\n");
					exit(EXIT_FAILURE);
				}

				fprintq(stdout, (char *) name);
				printf(": ");
				fprintq(stdout, (char *) value);
			}

			sqlite3_finalize(stmt2);
		}

		if (stats) {
			printf("[\n");
		}

		const char *sql = "SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;";
		sqlite3_stmt *stmt;
		if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
			fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
			exit(EXIT_FAILURE);
		}

		sqlite3_bind_int(stmt, 1, minzoom);
		sqlite3_bind_int(stmt, 2, maxzoom);

		if (!pipeline && !stats) {
			printf("\n}, \"features\": [\n");
		}

		within = 0;
		while (sqlite3_step(stmt) == SQLITE_ROW) {
			if (!pipeline && !stats) {
				if (within) {
					printf(",\n");
				}
				within = 1;
			}
			if (stats) {
				if (within) {
					printf(",\n");
				}
				within = 1;
			}

			int len = sqlite3_column_bytes(stmt, 0);
			int tz = sqlite3_column_int(stmt, 1);
			int tx = sqlite3_column_int(stmt, 2);
			int ty = sqlite3_column_int(stmt, 3);

			if (tz < 0 || tz >= 32) {
				fprintf(stderr, "Impossible zoom level %d in mbtiles\n", tz);
				exit(EXIT_FAILURE);
			}

			ty = (1LL << tz) - 1 - ty;
			const char *s = (const char *) sqlite3_column_blob(stmt, 0);

			handle(std::string(s, len), tz, tx, ty, 1, to_decode, pipeline, stats);
		}

		if (!pipeline && !stats) {
			printf("] }\n");
		}
		if (stats) {
			printf("]\n");
		}

		sqlite3_finalize(stmt);
	} else {
		int handled = 0;
		while (z >= 0 && !handled) {
			const char *sql = "SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;";
			sqlite3_stmt *stmt;
			if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
				fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
				exit(EXIT_FAILURE);
			}

			sqlite3_bind_int(stmt, 1, z);
			sqlite3_bind_int(stmt, 2, x);
			sqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y);

			while (sqlite3_step(stmt) == SQLITE_ROW) {
				int len = sqlite3_column_bytes(stmt, 0);
				const char *s = (const char *) sqlite3_column_blob(stmt, 0);

				if (z != oz) {
					fprintf(stderr, "%s: Warning: using tile %d/%u/%u instead of %d/%u/%u\n", fname, z, x, y, oz, ox, oy);
				}

				handle(std::string(s, len), z, x, y, 0, to_decode, pipeline, stats);
				handled = 1;
			}

			sqlite3_finalize(stmt);

			z--;
			x /= 2;
			y /= 2;
		}
	}

	if (sqlite3_close(db) != SQLITE_OK) {
		fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db));
		exit(EXIT_FAILURE);
	}
}

void usage(char **argv) {
	fprintf(stderr, "Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\n", argv[0]);
	exit(EXIT_FAILURE);
}

int main(int argc, char **argv) {
	extern int optind;
	extern char *optarg;
	int i;
	std::set<std::string> to_decode;
	bool pipeline = false;
	bool stats = false;

	struct option long_options[] = {
		{"projection", required_argument, 0, 's'},
		{"maximum-zoom", required_argument, 0, 'z'},
		{"minimum-zoom", required_argument, 0, 'Z'},
		{"layer", required_argument, 0, 'l'},
		{"tag-layer-and-zoom", no_argument, 0, 'c'},
		{"stats", no_argument, 0, 'S'},
		{"force", no_argument, 0, 'f'},
		{0, 0, 0, 0},
	};

	std::string getopt_str;
	for (size_t lo = 0; long_options[lo].name != NULL; lo++) {
		if (long_options[lo].val > ' ') {
			getopt_str.push_back(long_options[lo].val);

			if (long_options[lo].has_arg == required_argument) {
				getopt_str.push_back(':');
			}
		}
	}

	while ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) {
		switch (i) {
		case 0:
			break;

		case 's':
			set_projection_or_exit(optarg);
			break;

		case 'z':
			maxzoom = atoi(optarg);
			break;

		case 'Z':
			minzoom = atoi(optarg);
			break;

		case 'l':
			to_decode.insert(optarg);
			break;

		case 'c':
			pipeline = true;
			break;

		case 'S':
			stats = true;
			break;

		case 'f':
			force = true;
			break;

		default:
			usage(argv);
		}
	}

	if (argc == optind + 4) {
		decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats);
	} else if (argc == optind + 1) {
		decode(argv[optind], -1, -1, -1, to_decode, pipeline, stats);
	} else {
		usage(argv);
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "modify.h"

#include <akonadiconnection.h>
#include <storage/datastore.h>
#include <storage/entity.h>
#include <storage/transaction.h>
#include "libs/imapparser_p.h"
#include "imapstreamparser.h"
#include <handlerhelper.h>
#include <response.h>
#include <storage/itemretriever.h>
#include <storage/selectquerybuilder.h>
#include <storage/collectionqueryhelper.h>
#include <libs/protocol_p.h>
#include <search/searchmanager.h>
#include <akdebug.h>

using namespace Akonadi;

Modify::Modify( Scope::SelectionScope scope )
  : m_scope( scope )
{
}

bool Modify::parseStream()
{
  m_scope.parseScope( m_streamParser );
  SelectQueryBuilder<Collection> qb;
  CollectionQueryHelper::scopeToQuery( m_scope, connection(), qb );
  if ( !qb.exec() ) {
    throw HandlerException( "Unable to execute collection query" );
  }
  const Collection::List collections = qb.result();
  if ( collections.isEmpty() ) {
    throw HandlerException( "No such collection" );
  }
  if ( collections.size() > 1 ) { // TODO
    throw HandlerException( "Mass-modifying collections is not yet implemented" );
  }
  Collection collection = collections.first();

  //TODO: do it cleanly with the streaming parser, which doesn't have look-ahead at this moment
  QByteArray line = m_streamParser->readUntilCommandEnd();
  m_streamParser->insertData( "\n" );

  int p = 0;
  if ( ( p = line.indexOf( AKONADI_PARAM_PARENT ) ) > 0 ) {
    QByteArray tmp;
    ImapParser::parseString( line, tmp, p + 6 );
    const Collection newParent = HandlerHelper::collectionFromIdOrName( tmp );
    if ( newParent.isValid() && collection.parentId() != newParent.id()
         && collection.resourceId() != newParent.resourceId() ) {
      ItemRetriever retriever( connection() );
      retriever.setCollection( collection, true );
      retriever.setRetrieveFullPayload( true );
      if ( !retriever.exec() ) {
        throw HandlerException( retriever.lastError() );
      }
    }
  }

  DataStore *db = connection()->storageBackend();
  Transaction transaction( db );
  QList<QByteArray> changes;

  int pos = 0;
  while ( pos < line.length() ) {
    QByteArray type;
    pos = ImapParser::parseString( line, type, pos );
    if ( type == AKONADI_PARAM_MIMETYPE ) {
      QList<QByteArray> mimeTypes;
      pos = ImapParser::parseParenthesizedList( line, mimeTypes, pos );
      QStringList mts;
      Q_FOREACH ( const QByteArray &ba, mimeTypes ) {
        mts << QString::fromLatin1( ba );
      }
      MimeType::List currentMts = collection.mimeTypes();
      bool equal = true;
      Q_FOREACH ( const MimeType &currentMt, currentMts ) {
        if ( mts.contains( currentMt.name() ) ) {
          mts.removeAll( currentMt.name() );
          continue;
        }
        equal = false;
        if ( !collection.removeMimeType( currentMt ) ) {
          throw HandlerException( "Unable to remove collection mimetype" );
        }
      }
      if ( !db->appendMimeTypeForCollection( collection.id(), mts ) ) {
        return failureResponse( "Unable to add collection mimetypes" );
      }
      if ( !equal || !mts.isEmpty() ) {
        changes.append( AKONADI_PARAM_MIMETYPE );
      }
    } else if ( type == AKONADI_PARAM_CACHEPOLICY ) {
      bool changed = false;
      pos = HandlerHelper::parseCachePolicy( line, collection, pos, &changed );
      if ( changed ) {
        changes.append( AKONADI_PARAM_CACHEPOLICY );
      }
    } else if ( type == AKONADI_PARAM_NAME ) {
      QString newName;
      pos = ImapParser::parseString( line, newName, pos );
      if ( collection.name() == newName ) {
        continue;
      }
      if ( !CollectionQueryHelper::hasAllowedName( collection, newName, collection.parentId() ) ) {
        throw HandlerException( "Collection with the same name exists already" );
      }
      collection.setName( newName );
      changes.append( AKONADI_PARAM_NAME );
    } else if ( type == AKONADI_PARAM_PARENT ) {
      qint64 newParent;
      bool ok = false;
      pos = ImapParser::parseNumber( line, newParent, &ok, pos );
      if ( !ok ) {
        return failureResponse( "Invalid syntax" );
      }
      if ( collection.parentId() == newParent ) {
        continue;
      }
      if ( !db->moveCollection( collection, Collection::retrieveById( newParent ) ) ) {
        return failureResponse( "Unable to reparent collection" );
      }
      changes.append( AKONADI_PARAM_PARENT );
    } else if ( type == AKONADI_PARAM_VIRTUAL ) {
      QString newValue;
      pos = ImapParser::parseString( line, newValue, pos );
      if ( newValue.toInt() != collection.isVirtual() ) {
          return failureResponse( "Can't modify VIRTUAL collection flag" );
      }
    } else if ( type == AKONADI_PARAM_REMOTEID ) {
      QString rid;
      pos = ImapParser::parseString( line, rid, pos );
      if ( rid == collection.remoteId() ) {
        continue;
      }
      if ( !connection()->isOwnerResource( collection ) ) {
        throw HandlerException( "Only resources can modify remote identifiers" );
      }
      collection.setRemoteId( rid );
      changes.append( AKONADI_PARAM_REMOTEID );
    } else if ( type == AKONADI_PARAM_REMOTEREVISION ) {
      QString remoteRevision;
      pos = ImapParser::parseString( line, remoteRevision, pos );
      if ( remoteRevision == collection.remoteRevision() ) {
        continue;
      }
      collection.setRemoteRevision( remoteRevision );
      changes.append( AKONADI_PARAM_REMOTEREVISION );
    } else if ( type == AKONADI_PARAM_PERSISTENTSEARCH ) {
      QByteArray tmp;
      QList<QByteArray> queryArgs;
      pos = ImapParser::parseString( line, tmp, pos );
      ImapParser::parseParenthesizedList( tmp, queryArgs );
      QString queryString, queryCollections, queryAttributes;
      QStringList attrs;
      for ( int i = 0; i < queryArgs.size() - 1; ++i ) {
        const QByteArray key = queryArgs.at( i );
        if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYSTRING ) {
          queryString = QString::fromUtf8( queryArgs.at( i + 1 ) );
          ++i;
        } else if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYCOLLECTIONS ) {
          QList<QByteArray> cols;
          ImapParser::parseParenthesizedList( queryArgs.at( i +  1), cols );
          queryCollections = QString::fromLatin1( ImapParser::join( cols, " " ) );
          ++i;
        } else  if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYLANG ) {
          attrs << QString::fromLatin1( key ) << QString::fromUtf8( queryArgs.at( i + 1 ) );
          ++i;
        } else if ( key == AKONADI_PARAM_REMOTE ) {
          attrs << QString::fromLatin1( key );
        } else if ( key == AKONADI_PARAM_RECURSIVE ) {
          attrs << QString::fromLatin1( key );
        }
      }

      queryAttributes = attrs.join( QLatin1String( " " ) );

      if ( collection.queryAttributes() != queryAttributes
          || collection.queryString() != queryString
          || changes.contains( AKONADI_PARAM_MIMETYPE ) ) {
        collection.setQueryString( queryString );
        collection.setQueryAttributes( queryAttributes );

        SearchManager::instance()->updateSearch( collection, db->notificationCollector() );

        changes.append( AKONADI_PARAM_PERSISTENTSEARCH );
      }
    } else if ( type.isEmpty() ) {
      break; // input end
    } else {
      // custom attribute
      if ( type.startsWith( '-' ) ) {
        type = type.mid( 1 );
        if ( db->removeCollectionAttribute( collection, type ) ) {
          changes.append( type );
        }
      } else {
        QByteArray value;
        pos = ImapParser::parseString( line, value, pos );

        SelectQueryBuilder<CollectionAttribute> qb;
          qb.addValueCondition( CollectionAttribute::collectionIdColumn(), Query::Equals, collection.id() );
        qb.addValueCondition( CollectionAttribute::typeColumn(), Query::Equals, type );
        if ( !qb.exec() ) {
          throw HandlerException( "Unable to retrieve collection attribute" );
        }

        const CollectionAttribute::List attrs = qb.result();
        if ( attrs.isEmpty() ) {
          CollectionAttribute attr;
          attr.setCollectionId( collection.id() );
          attr.setType( type );
          attr.setValue( value );
          if ( !attr.insert() ) {
            throw HandlerException( "Unable to add collection attribute" );
          }
          changes.append( type );
        } else if ( attrs.size() == 1 ) {
          CollectionAttribute attr = attrs.first();
          if ( attr.value() == value ) {
            continue;
          }
          attr.setValue( value );
          if ( !attr.update() ) {
            throw HandlerException( "Unable to update collection attribute" );
          }
          changes.append( type );
        } else {
          throw HandlerException( "WTF: more than one attribute with the same name" );
        }
      }
    }
  }

  if ( !changes.isEmpty() ) {
    if ( collection.hasPendingChanges() && !collection.update() ) {
      return failureResponse( "Unable to update collection" );
    }
    db->notificationCollector()->collectionChanged( collection, changes );
    if ( !transaction.commit() ) {
      return failureResponse( "Unable to commit transaction" );
    }
  }

  Response response;
  response.setTag( tag() );
  response.setString( "MODIFY done" );
  Q_EMIT responseAvailable( response );
  return true;
}
<commit_msg>Fix parsing of persistent search attributes in MODIFY command<commit_after>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "modify.h"

#include <akonadiconnection.h>
#include <storage/datastore.h>
#include <storage/entity.h>
#include <storage/transaction.h>
#include "libs/imapparser_p.h"
#include "imapstreamparser.h"
#include <handlerhelper.h>
#include <response.h>
#include <storage/itemretriever.h>
#include <storage/selectquerybuilder.h>
#include <storage/collectionqueryhelper.h>
#include <libs/protocol_p.h>
#include <search/searchmanager.h>
#include <akdebug.h>

using namespace Akonadi;

Modify::Modify( Scope::SelectionScope scope )
  : m_scope( scope )
{
}

bool Modify::parseStream()
{
  m_scope.parseScope( m_streamParser );
  SelectQueryBuilder<Collection> qb;
  CollectionQueryHelper::scopeToQuery( m_scope, connection(), qb );
  if ( !qb.exec() ) {
    throw HandlerException( "Unable to execute collection query" );
  }
  const Collection::List collections = qb.result();
  if ( collections.isEmpty() ) {
    throw HandlerException( "No such collection" );
  }
  if ( collections.size() > 1 ) { // TODO
    throw HandlerException( "Mass-modifying collections is not yet implemented" );
  }
  Collection collection = collections.first();

  //TODO: do it cleanly with the streaming parser, which doesn't have look-ahead at this moment
  QByteArray line = m_streamParser->readUntilCommandEnd();
  m_streamParser->insertData( "\n" );

  int p = 0;
  if ( ( p = line.indexOf( AKONADI_PARAM_PARENT ) ) > 0 ) {
    QByteArray tmp;
    ImapParser::parseString( line, tmp, p + 6 );
    const Collection newParent = HandlerHelper::collectionFromIdOrName( tmp );
    if ( newParent.isValid() && collection.parentId() != newParent.id()
         && collection.resourceId() != newParent.resourceId() ) {
      ItemRetriever retriever( connection() );
      retriever.setCollection( collection, true );
      retriever.setRetrieveFullPayload( true );
      if ( !retriever.exec() ) {
        throw HandlerException( retriever.lastError() );
      }
    }
  }

  DataStore *db = connection()->storageBackend();
  Transaction transaction( db );
  QList<QByteArray> changes;

  int pos = 0;
  while ( pos < line.length() ) {
    QByteArray type;
    pos = ImapParser::parseString( line, type, pos );
    if ( type == AKONADI_PARAM_MIMETYPE ) {
      QList<QByteArray> mimeTypes;
      pos = ImapParser::parseParenthesizedList( line, mimeTypes, pos );
      QStringList mts;
      Q_FOREACH ( const QByteArray &ba, mimeTypes ) {
        mts << QString::fromLatin1( ba );
      }
      MimeType::List currentMts = collection.mimeTypes();
      bool equal = true;
      Q_FOREACH ( const MimeType &currentMt, currentMts ) {
        if ( mts.contains( currentMt.name() ) ) {
          mts.removeAll( currentMt.name() );
          continue;
        }
        equal = false;
        if ( !collection.removeMimeType( currentMt ) ) {
          throw HandlerException( "Unable to remove collection mimetype" );
        }
      }
      if ( !db->appendMimeTypeForCollection( collection.id(), mts ) ) {
        return failureResponse( "Unable to add collection mimetypes" );
      }
      if ( !equal || !mts.isEmpty() ) {
        changes.append( AKONADI_PARAM_MIMETYPE );
      }
    } else if ( type == AKONADI_PARAM_CACHEPOLICY ) {
      bool changed = false;
      pos = HandlerHelper::parseCachePolicy( line, collection, pos, &changed );
      if ( changed ) {
        changes.append( AKONADI_PARAM_CACHEPOLICY );
      }
    } else if ( type == AKONADI_PARAM_NAME ) {
      QString newName;
      pos = ImapParser::parseString( line, newName, pos );
      if ( collection.name() == newName ) {
        continue;
      }
      if ( !CollectionQueryHelper::hasAllowedName( collection, newName, collection.parentId() ) ) {
        throw HandlerException( "Collection with the same name exists already" );
      }
      collection.setName( newName );
      changes.append( AKONADI_PARAM_NAME );
    } else if ( type == AKONADI_PARAM_PARENT ) {
      qint64 newParent;
      bool ok = false;
      pos = ImapParser::parseNumber( line, newParent, &ok, pos );
      if ( !ok ) {
        return failureResponse( "Invalid syntax" );
      }
      if ( collection.parentId() == newParent ) {
        continue;
      }
      if ( !db->moveCollection( collection, Collection::retrieveById( newParent ) ) ) {
        return failureResponse( "Unable to reparent collection" );
      }
      changes.append( AKONADI_PARAM_PARENT );
    } else if ( type == AKONADI_PARAM_VIRTUAL ) {
      QString newValue;
      pos = ImapParser::parseString( line, newValue, pos );
      if ( newValue.toInt() != collection.isVirtual() ) {
          return failureResponse( "Can't modify VIRTUAL collection flag" );
      }
    } else if ( type == AKONADI_PARAM_REMOTEID ) {
      QString rid;
      pos = ImapParser::parseString( line, rid, pos );
      if ( rid == collection.remoteId() ) {
        continue;
      }
      if ( !connection()->isOwnerResource( collection ) ) {
        throw HandlerException( "Only resources can modify remote identifiers" );
      }
      collection.setRemoteId( rid );
      changes.append( AKONADI_PARAM_REMOTEID );
    } else if ( type == AKONADI_PARAM_REMOTEREVISION ) {
      QString remoteRevision;
      pos = ImapParser::parseString( line, remoteRevision, pos );
      if ( remoteRevision == collection.remoteRevision() ) {
        continue;
      }
      collection.setRemoteRevision( remoteRevision );
      changes.append( AKONADI_PARAM_REMOTEREVISION );
    } else if ( type == AKONADI_PARAM_PERSISTENTSEARCH ) {
      QByteArray tmp;
      QList<QByteArray> queryArgs;
      pos = ImapParser::parseString( line, tmp, pos );
      ImapParser::parseParenthesizedList( tmp, queryArgs );
      QString queryString, queryCollections, queryAttributes;
      QStringList attrs;
      for ( int i = 0; i < queryArgs.size(); ++i ) {
        const QByteArray key = queryArgs.at( i );
        qDebug() << key;
        if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYSTRING ) {
          queryString = QString::fromUtf8( queryArgs.at( i + 1 ) );
          ++i;
        } else if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYCOLLECTIONS ) {
          QList<QByteArray> cols;
          ImapParser::parseParenthesizedList( queryArgs.at( i +  1), cols );
          queryCollections = QString::fromLatin1( ImapParser::join( cols, " " ) );
          ++i;
        } else  if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYLANG ) {
          // Ignore query lang
          ++i;
        } else if ( key == AKONADI_PARAM_REMOTE ) {
          attrs << QString::fromLatin1( key );
        } else if ( key == AKONADI_PARAM_RECURSIVE ) {
          attrs << QString::fromLatin1( key );
        }
      }

      queryAttributes = attrs.join( QLatin1String( " " ) );

      if ( collection.queryAttributes() != queryAttributes
          || collection.queryCollections() != queryCollections
          || collection.queryString() != queryString
          || changes.contains( AKONADI_PARAM_MIMETYPE ) ) {
        collection.setQueryString( queryString );
        collection.setQueryCollections( queryCollections );
        collection.setQueryAttributes( queryAttributes );

        SearchManager::instance()->updateSearch( collection, db->notificationCollector() );

        changes.append( AKONADI_PARAM_PERSISTENTSEARCH );
      }
    } else if ( type.isEmpty() ) {
      break; // input end
    } else {
      // custom attribute
      if ( type.startsWith( '-' ) ) {
        type = type.mid( 1 );
        if ( db->removeCollectionAttribute( collection, type ) ) {
          changes.append( type );
        }
      } else {
        QByteArray value;
        pos = ImapParser::parseString( line, value, pos );

        SelectQueryBuilder<CollectionAttribute> qb;
          qb.addValueCondition( CollectionAttribute::collectionIdColumn(), Query::Equals, collection.id() );
        qb.addValueCondition( CollectionAttribute::typeColumn(), Query::Equals, type );
        if ( !qb.exec() ) {
          throw HandlerException( "Unable to retrieve collection attribute" );
        }

        const CollectionAttribute::List attrs = qb.result();
        if ( attrs.isEmpty() ) {
          CollectionAttribute attr;
          attr.setCollectionId( collection.id() );
          attr.setType( type );
          attr.setValue( value );
          if ( !attr.insert() ) {
            throw HandlerException( "Unable to add collection attribute" );
          }
          changes.append( type );
        } else if ( attrs.size() == 1 ) {
          CollectionAttribute attr = attrs.first();
          if ( attr.value() == value ) {
            continue;
          }
          attr.setValue( value );
          if ( !attr.update() ) {
            throw HandlerException( "Unable to update collection attribute" );
          }
          changes.append( type );
        } else {
          throw HandlerException( "WTF: more than one attribute with the same name" );
        }
      }
    }
  }

  if ( !changes.isEmpty() ) {
    if ( collection.hasPendingChanges() && !collection.update() ) {
      return failureResponse( "Unable to update collection" );
    }
    db->notificationCollector()->collectionChanged( collection, changes );
    if ( !transaction.commit() ) {
      return failureResponse( "Unable to commit transaction" );
    }
  }

  Response response;
  response.setTag( tag() );
  response.setString( "MODIFY done" );
  Q_EMIT responseAvailable( response );
  return true;
}
<|endoftext|>


<commit_before>/* json_endpoint.cc
   Jeremy Barnes, 22 February 2011
   Copyright (c) 2011 Datacratic.  All rights reserved.

*/

#include "soa/service//json_endpoint.h"
#include "jml/arch/exception.h"
#include "soa/jsoncpp/json.h"

using namespace ML;
using namespace std;

namespace Datacratic {

/*****************************************************************************/
/* JSON CONNECTION HANDLER                                                   */
/*****************************************************************************/

JsonConnectionHandler::
JsonConnectionHandler()
{
}

void
JsonConnectionHandler::
handleHttpHeader(const HttpHeader & header)
{
    if (!header.contentType.empty()
        && header.contentType.find("json") == string::npos
        && header.contentType.find("text") == string::npos)
        throw Exception("invalid content type '%s' for JSON",
                        header.contentType.c_str());
    if (header.verb != "POST")
        throw Exception("invalid verb");
}

void
JsonConnectionHandler::
handleHttpPayload(const HttpHeader & header,
                  const std::string & payload)
{
    Json::Value request;

    const char * start = payload.c_str();
    const char * end = start + payload.length();

    while (end > start && end[-1] == '\n') --end;

    try {
        Json::Reader reader;
        if (!reader.parse(start, end, request, false)) {
            //cerr << "JSON parsing error" << endl;
            doError("parsing JSON payload: "
                    + reader.getFormattedErrorMessages());
       //     return;
        }
    } catch (const std::exception & exc) {
        doError("parsing JSON request: " + string(exc.what()));
        return;
    }

    addActivity("finishedJsonParsing");

    handleJson(header, request, string(start, end));
}

void
JsonConnectionHandler::
handleHttpChunk(const HttpHeader & header,
                const std::string & chunkHeader,
                const std::string & chunk)
{
    Json::Value request;

    const char * start = chunk.c_str();
    const char * end = start + chunk.length();

    while (end > start && end[-1] == '\n') --end;

    try {
        Json::Reader reader;
        if (!reader.parse(start, end, request, false)) {
            //cerr << "JSON parsing error" << endl;
            doError("parsing JSON chunk: "
                    + reader.getFormattedErrorMessages());
            return;
        }
    } catch (const std::exception & exc) {
        doError("parsing JSON request: " + string(exc.what()));
        return;
    }

    addActivity("finishedJsonParsing");

    handleJson(header, request, string(start, end));
}

} // namespace Datacratic

<commit_msg>rollback<commit_after>/* json_endpoint.cc
   Jeremy Barnes, 22 February 2011
   Copyright (c) 2011 Datacratic.  All rights reserved.

*/

#include "soa/service//json_endpoint.h"
#include "jml/arch/exception.h"
#include "soa/jsoncpp/json.h"

using namespace ML;
using namespace std;

namespace Datacratic {

/*****************************************************************************/
/* JSON CONNECTION HANDLER                                                   */
/*****************************************************************************/

JsonConnectionHandler::
JsonConnectionHandler()
{
}

void
JsonConnectionHandler::
handleHttpHeader(const HttpHeader & header)
{
    if (!header.contentType.empty()
        && header.contentType.find("json") == string::npos
        && header.contentType.find("text") == string::npos)
        throw Exception("invalid content type '%s' for JSON",
                        header.contentType.c_str());
    if (header.verb != "POST")
        throw Exception("invalid verb");
}

void
JsonConnectionHandler::
handleHttpPayload(const HttpHeader & header,
                  const std::string & payload)
{
    Json::Value request;

    const char * start = payload.c_str();
    const char * end = start + payload.length();

    while (end > start && end[-1] == '\n') --end;

    try {
        Json::Reader reader;
        if (!reader.parse(start, end, request, false)) {
            //cerr << "JSON parsing error" << endl;
            doError("parsing JSON payload: "
                    + reader.getFormattedErrorMessages());
          return;
        }
    } catch (const std::exception & exc) {
        doError("parsing JSON request: " + string(exc.what()));
        return;
    }

    addActivity("finishedJsonParsing");

    handleJson(header, request, string(start, end));
}

void
JsonConnectionHandler::
handleHttpChunk(const HttpHeader & header,
                const std::string & chunkHeader,
                const std::string & chunk)
{
    Json::Value request;

    const char * start = chunk.c_str();
    const char * end = start + chunk.length();

    while (end > start && end[-1] == '\n') --end;

    try {
        Json::Reader reader;
        if (!reader.parse(start, end, request, false)) {
            //cerr << "JSON parsing error" << endl;
            doError("parsing JSON chunk: "
                    + reader.getFormattedErrorMessages());
            return;
        }
    } catch (const std::exception & exc) {
        doError("parsing JSON request: " + string(exc.what()));
        return;
    }

    addActivity("finishedJsonParsing");

    handleJson(header, request, string(start, end));
}

} // namespace Datacratic

<|endoftext|>