<commit_before>#include "master.hpp"

namespace factor
{

THREADHANDLE start_thread(void *(*start_routine)(void *),void *args)
{
	pthread_attr_t attr;
	pthread_t thread;
	if (pthread_attr_init (&attr) != 0)
		fatal_error("pthread_attr_init() failed",0);
	if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)
		fatal_error("pthread_attr_setdetachstate() failed",0);
	if (pthread_create (&thread, &attr, start_routine, args) != 0)
		fatal_error("pthread_create() failed",0);
	pthread_attr_destroy(&attr);
	return thread;
}

static void *null_dll;

void sleep_nanos(u64 nsec)
{
	timespec ts;
	timespec ts_rem;
	int ret;
	ts.tv_sec = nsec / 1000000000;
	ts.tv_nsec = nsec % 1000000000;
	ret = nanosleep(&ts,&ts_rem);
	while(ret == -1 && errno == EINTR)
	{
		memcpy(&ts, &ts_rem, sizeof(ts));
		ret = nanosleep(&ts, &ts_rem);
	}

	if(ret == -1)
		fatal_error("nanosleep failed", 0);
}

void factor_vm::init_ffi()
{
	null_dll = dlopen(NULL,RTLD_LAZY);
}

void factor_vm::ffi_dlopen(dll *dll)
{
	dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);
}

void *factor_vm::ffi_dlsym_raw(dll *dll, symbol_char *symbol)
{
	return dlsym(dll ? dll->handle : null_dll, symbol);
}

void *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)
{
	return FUNCTION_CODE_POINTER(ffi_dlsym_raw(dll, symbol));
}

#ifdef FACTOR_PPC
void *factor_vm::ffi_dlsym_toc(dll *dll, symbol_char *symbol)
{
	return FUNCTION_TOC_POINTER(ffi_dlsym_raw(dll, symbol));
}
#endif

void factor_vm::ffi_dlclose(dll *dll)
{
	if(dlclose(dll->handle))
		general_error(ERROR_FFI,false_object,false_object);
	dll->handle = NULL;
}

void factor_vm::primitive_existsp()
{
	struct stat sb;
	char *path = (char *)(untag_check<byte_array>(ctx->pop()) + 1);
	ctx->push(tag_boolean(stat(path,&sb) >= 0));
}

void factor_vm::move_file(const vm_char *path1, const vm_char *path2)
{
	int ret = 0;
	do
	{
		ret = rename((path1),(path2));
	}
	while(ret < 0 && errno == EINTR);

	if(ret < 0)
		general_error(ERROR_IO,tag_fixnum(errno),false_object);
}

segment::segment(cell size_, bool executable_p)
{
	size = size_;

	int pagesize = getpagesize();

	int prot;
	if(executable_p)
		prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
	else
		prot = (PROT_READ | PROT_WRITE);

	char *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);
	if(array == (char*)-1) out_of_memory();

	if(mprotect(array,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect low guard page",(cell)array);

	if(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect high guard page",(cell)array);

	start = (cell)(array + pagesize);
	end = start + size;
}

segment::~segment()
{
	int pagesize = getpagesize();
	int retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);
	if(retval)
		fatal_error("Segment deallocation failed",0);
}

void code_heap::guard_safepoint()
{
	if(mprotect(safepoint_page,getpagesize(),PROT_NONE) == -1)
		fatal_error("Cannot protect safepoint guard page",(cell)safepoint_page);
}

void code_heap::unguard_safepoint()
{
	if(mprotect(safepoint_page,getpagesize(),PROT_WRITE) == -1)
		fatal_error("Cannot unprotect safepoint guard page",(cell)safepoint_page);
}

void factor_vm::dispatch_signal(void *uap, void (handler)())
{
	UAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));
	UAP_PROGRAM_COUNTER(uap) = (cell)FUNCTION_CODE_POINTER(handler);
	UAP_SET_TOC_POINTER(uap, (cell)FUNCTION_TOC_POINTER(handler));
	ctx->callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);
}

void memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_fault_addr = (cell)siginfo->si_addr;
	vm->dispatch_signal(uap,factor::memory_signal_handler_impl);
}

void synchronous_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->dispatch_signal(uap,factor::synchronous_signal_handler_impl);
}

void next_safepoint_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm_p();
	if (vm)
		vm->enqueue_safepoint_signal(signal);
}

void ignore_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
}

void fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
	uap_clear_fpu_status(uap);

	vm->dispatch_signal(uap,
		(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
		? factor::synchronous_signal_handler_impl
		: factor::fp_signal_handler_impl);
}

static void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)
{
	int ret;
	do
	{
		ret = sigaction(signum, act, oldact);
	}
	while(ret == -1 && errno == EINTR);

	if(ret == -1)
		fatal_error("sigaction failed", 0);
}

void factor_vm::unix_init_signals()
{
	/* OpenBSD doesn't support sigaltstack() if we link against
	libpthread. See http://redmine.ruby-lang.org/issues/show/1239 */

#ifndef __OpenBSD__
	signal_callstack_seg = new segment(callstack_size,false);

	stack_t signal_callstack;
	signal_callstack.ss_sp = (char *)signal_callstack_seg->start;
	signal_callstack.ss_size = signal_callstack_seg->size;
	signal_callstack.ss_flags = 0;

	if(sigaltstack(&signal_callstack,(stack_t *)NULL) < 0)
		fatal_error("sigaltstack() failed",0);
#endif

	struct sigaction memory_sigaction;
	struct sigaction synchronous_sigaction;
	struct sigaction next_safepoint_sigaction;
	struct sigaction fpe_sigaction;
	struct sigaction ignore_sigaction;

	memset(&memory_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&memory_sigaction.sa_mask);
	memory_sigaction.sa_sigaction = memory_signal_handler;
	memory_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGBUS,&memory_sigaction,NULL);
	sigaction_safe(SIGSEGV,&memory_sigaction,NULL);
	sigaction_safe(SIGTRAP,&memory_sigaction,NULL);

	memset(&fpe_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&fpe_sigaction.sa_mask);
	fpe_sigaction.sa_sigaction = fpe_signal_handler;
	fpe_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGFPE,&fpe_sigaction,NULL);

	memset(&synchronous_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&synchronous_sigaction.sa_mask);
	synchronous_sigaction.sa_sigaction = synchronous_signal_handler;
	synchronous_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGILL,&synchronous_sigaction,NULL);
	sigaction_safe(SIGABRT,&synchronous_sigaction,NULL);

	memset(&next_safepoint_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&next_safepoint_sigaction.sa_mask);
	next_safepoint_sigaction.sa_sigaction = next_safepoint_signal_handler;
	next_safepoint_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;
	sigaction_safe(SIGALRM,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGVTALRM,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGPROF,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGQUIT,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGINT,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGUSR1,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGUSR2,&next_safepoint_sigaction,NULL);

	/* We don't use SA_IGN here because then the ignore action is inherited
	by subprocesses, which we don't want. There is a unit test in
	io.launcher.unix for this. */
	memset(&ignore_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&ignore_sigaction.sa_mask);
	ignore_sigaction.sa_sigaction = ignore_signal_handler;
	ignore_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;
	sigaction_safe(SIGPIPE,&ignore_sigaction,NULL);
}

/* On Unix, shared fds such as stdin cannot be set to non-blocking mode
(http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
so we kludge around this by spawning a thread, which waits on a control pipe
for a signal, upon receiving this signal it reads one block of data from stdin
and writes it to a data pipe. Upon completion, it writes a 4-byte integer to
the size pipe, indicating how much data was written to the data pipe.

The read end of the size pipe can be set to non-blocking. */
extern "C" {
	int stdin_read;
	int stdin_write;

	int control_read;
	int control_write;

	int size_read;
	int size_write;
}

void safe_close(int fd)
{
	if(close(fd) < 0)
		fatal_error("error closing fd",errno);
}

bool check_write(int fd, void *data, ssize_t size)
{
	if(write(fd,data,size) == size)
		return true;
	else
	{
		if(errno == EINTR)
			return check_write(fd,data,size);
		else
			return false;
	}
}

void safe_write(int fd, void *data, ssize_t size)
{
	if(!check_write(fd,data,size))
		fatal_error("error writing fd",errno);
}

bool safe_read(int fd, void *data, ssize_t size)
{
	ssize_t bytes = read(fd,data,size);
	if(bytes < 0)
	{
		if(errno == EINTR)
			return safe_read(fd,data,size);
		else
		{
			fatal_error("error reading fd",errno);
			return false;
		}
	}
	else
		return (bytes == size);
}

void *stdin_loop(void *arg)
{
	unsigned char buf[4096];
	bool loop_running = true;

	while(loop_running)
	{
		if(!safe_read(control_read,buf,1))
			break;

		if(buf[0] != 'X')
			fatal_error("stdin_loop: bad data on control fd",buf[0]);

		for(;;)
		{
			ssize_t bytes = read(0,buf,sizeof(buf));
			if(bytes < 0)
			{
				if(errno == EINTR)
					continue;
				else
				{
					loop_running = false;
					break;
				}
			}
			else if(bytes >= 0)
			{
				safe_write(size_write,&bytes,sizeof(bytes));

				if(!check_write(stdin_write,buf,bytes))
					loop_running = false;
				break;
			}
		}
	}

	safe_close(stdin_write);
	safe_close(control_read);

	return NULL;
}

void safe_pipe(int *in, int *out)
{
	int filedes[2];

	if(pipe(filedes) < 0)
		fatal_error("Error opening pipe",errno);

	*in = filedes[0];
	*out = filedes[1];

	if(fcntl(*in,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);

	if(fcntl(*out,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);
}

void open_console()
{
	safe_pipe(&control_read,&control_write);
	safe_pipe(&size_read,&size_write);
	safe_pipe(&stdin_read,&stdin_write);
	start_thread(stdin_loop,NULL);
}

}
<commit_msg>vm: block all signals from unix stdin_loop thread<commit_after>#include "master.hpp"

namespace factor
{

THREADHANDLE start_thread(void *(*start_routine)(void *),void *args)
{
	pthread_attr_t attr;
	pthread_t thread;
	if (pthread_attr_init (&attr) != 0)
		fatal_error("pthread_attr_init() failed",0);
	if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)
		fatal_error("pthread_attr_setdetachstate() failed",0);
	if (pthread_create (&thread, &attr, start_routine, args) != 0)
		fatal_error("pthread_create() failed",0);
	pthread_attr_destroy(&attr);
	return thread;
}

static void *null_dll;

void sleep_nanos(u64 nsec)
{
	timespec ts;
	timespec ts_rem;
	int ret;
	ts.tv_sec = nsec / 1000000000;
	ts.tv_nsec = nsec % 1000000000;
	ret = nanosleep(&ts,&ts_rem);
	while(ret == -1 && errno == EINTR)
	{
		memcpy(&ts, &ts_rem, sizeof(ts));
		ret = nanosleep(&ts, &ts_rem);
	}

	if(ret == -1)
		fatal_error("nanosleep failed", 0);
}

void factor_vm::init_ffi()
{
	null_dll = dlopen(NULL,RTLD_LAZY);
}

void factor_vm::ffi_dlopen(dll *dll)
{
	dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);
}

void *factor_vm::ffi_dlsym_raw(dll *dll, symbol_char *symbol)
{
	return dlsym(dll ? dll->handle : null_dll, symbol);
}

void *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)
{
	return FUNCTION_CODE_POINTER(ffi_dlsym_raw(dll, symbol));
}

#ifdef FACTOR_PPC
void *factor_vm::ffi_dlsym_toc(dll *dll, symbol_char *symbol)
{
	return FUNCTION_TOC_POINTER(ffi_dlsym_raw(dll, symbol));
}
#endif

void factor_vm::ffi_dlclose(dll *dll)
{
	if(dlclose(dll->handle))
		general_error(ERROR_FFI,false_object,false_object);
	dll->handle = NULL;
}

void factor_vm::primitive_existsp()
{
	struct stat sb;
	char *path = (char *)(untag_check<byte_array>(ctx->pop()) + 1);
	ctx->push(tag_boolean(stat(path,&sb) >= 0));
}

void factor_vm::move_file(const vm_char *path1, const vm_char *path2)
{
	int ret = 0;
	do
	{
		ret = rename((path1),(path2));
	}
	while(ret < 0 && errno == EINTR);

	if(ret < 0)
		general_error(ERROR_IO,tag_fixnum(errno),false_object);
}

segment::segment(cell size_, bool executable_p)
{
	size = size_;

	int pagesize = getpagesize();

	int prot;
	if(executable_p)
		prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
	else
		prot = (PROT_READ | PROT_WRITE);

	char *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);
	if(array == (char*)-1) out_of_memory();

	if(mprotect(array,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect low guard page",(cell)array);

	if(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect high guard page",(cell)array);

	start = (cell)(array + pagesize);
	end = start + size;
}

segment::~segment()
{
	int pagesize = getpagesize();
	int retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);
	if(retval)
		fatal_error("Segment deallocation failed",0);
}

void code_heap::guard_safepoint()
{
	if(mprotect(safepoint_page,getpagesize(),PROT_NONE) == -1)
		fatal_error("Cannot protect safepoint guard page",(cell)safepoint_page);
}

void code_heap::unguard_safepoint()
{
	if(mprotect(safepoint_page,getpagesize(),PROT_WRITE) == -1)
		fatal_error("Cannot unprotect safepoint guard page",(cell)safepoint_page);
}

void factor_vm::dispatch_signal(void *uap, void (handler)())
{
	UAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));
	UAP_PROGRAM_COUNTER(uap) = (cell)FUNCTION_CODE_POINTER(handler);
	UAP_SET_TOC_POINTER(uap, (cell)FUNCTION_TOC_POINTER(handler));
	ctx->callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);
}

void memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_fault_addr = (cell)siginfo->si_addr;
	vm->dispatch_signal(uap,factor::memory_signal_handler_impl);
}

void synchronous_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->dispatch_signal(uap,factor::synchronous_signal_handler_impl);
}

void next_safepoint_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm_p();
	if (vm)
		vm->enqueue_safepoint_signal(signal);
}

void ignore_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
}

void fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
	uap_clear_fpu_status(uap);

	vm->dispatch_signal(uap,
		(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
		? factor::synchronous_signal_handler_impl
		: factor::fp_signal_handler_impl);
}

static void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)
{
	int ret;
	do
	{
		ret = sigaction(signum, act, oldact);
	}
	while(ret == -1 && errno == EINTR);

	if(ret == -1)
		fatal_error("sigaction failed", 0);
}

void factor_vm::unix_init_signals()
{
	/* OpenBSD doesn't support sigaltstack() if we link against
	libpthread. See http://redmine.ruby-lang.org/issues/show/1239 */

#ifndef __OpenBSD__
	signal_callstack_seg = new segment(callstack_size,false);

	stack_t signal_callstack;
	signal_callstack.ss_sp = (char *)signal_callstack_seg->start;
	signal_callstack.ss_size = signal_callstack_seg->size;
	signal_callstack.ss_flags = 0;

	if(sigaltstack(&signal_callstack,(stack_t *)NULL) < 0)
		fatal_error("sigaltstack() failed",0);
#endif

	struct sigaction memory_sigaction;
	struct sigaction synchronous_sigaction;
	struct sigaction next_safepoint_sigaction;
	struct sigaction fpe_sigaction;
	struct sigaction ignore_sigaction;

	memset(&memory_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&memory_sigaction.sa_mask);
	memory_sigaction.sa_sigaction = memory_signal_handler;
	memory_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGBUS,&memory_sigaction,NULL);
	sigaction_safe(SIGSEGV,&memory_sigaction,NULL);
	sigaction_safe(SIGTRAP,&memory_sigaction,NULL);

	memset(&fpe_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&fpe_sigaction.sa_mask);
	fpe_sigaction.sa_sigaction = fpe_signal_handler;
	fpe_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGFPE,&fpe_sigaction,NULL);

	memset(&synchronous_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&synchronous_sigaction.sa_mask);
	synchronous_sigaction.sa_sigaction = synchronous_signal_handler;
	synchronous_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGILL,&synchronous_sigaction,NULL);
	sigaction_safe(SIGABRT,&synchronous_sigaction,NULL);

	memset(&next_safepoint_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&next_safepoint_sigaction.sa_mask);
	next_safepoint_sigaction.sa_sigaction = next_safepoint_signal_handler;
	next_safepoint_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;
	sigaction_safe(SIGALRM,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGVTALRM,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGPROF,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGQUIT,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGINT,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGUSR1,&next_safepoint_sigaction,NULL);
	sigaction_safe(SIGUSR2,&next_safepoint_sigaction,NULL);

	/* We don't use SA_IGN here because then the ignore action is inherited
	by subprocesses, which we don't want. There is a unit test in
	io.launcher.unix for this. */
	memset(&ignore_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&ignore_sigaction.sa_mask);
	ignore_sigaction.sa_sigaction = ignore_signal_handler;
	ignore_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;
	sigaction_safe(SIGPIPE,&ignore_sigaction,NULL);
}

/* On Unix, shared fds such as stdin cannot be set to non-blocking mode
(http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
so we kludge around this by spawning a thread, which waits on a control pipe
for a signal, upon receiving this signal it reads one block of data from stdin
and writes it to a data pipe. Upon completion, it writes a 4-byte integer to
the size pipe, indicating how much data was written to the data pipe.

The read end of the size pipe can be set to non-blocking. */
extern "C" {
	int stdin_read;
	int stdin_write;

	int control_read;
	int control_write;

	int size_read;
	int size_write;
}

void safe_close(int fd)
{
	if(close(fd) < 0)
		fatal_error("error closing fd",errno);
}

bool check_write(int fd, void *data, ssize_t size)
{
	if(write(fd,data,size) == size)
		return true;
	else
	{
		if(errno == EINTR)
			return check_write(fd,data,size);
		else
			return false;
	}
}

void safe_write(int fd, void *data, ssize_t size)
{
	if(!check_write(fd,data,size))
		fatal_error("error writing fd",errno);
}

bool safe_read(int fd, void *data, ssize_t size)
{
	ssize_t bytes = read(fd,data,size);
	if(bytes < 0)
	{
		if(errno == EINTR)
			return safe_read(fd,data,size);
		else
		{
			fatal_error("error reading fd",errno);
			return false;
		}
	}
	else
		return (bytes == size);
}

void *stdin_loop(void *arg)
{
	unsigned char buf[4096];
	bool loop_running = true;

	sigset_t mask;
	sigfillset(&mask);
	pthread_sigmask(SIG_BLOCK, &mask, NULL);

	while(loop_running)
	{
		if(!safe_read(control_read,buf,1))
			break;

		if(buf[0] != 'X')
			fatal_error("stdin_loop: bad data on control fd",buf[0]);

		for(;;)
		{
			ssize_t bytes = read(0,buf,sizeof(buf));
			if(bytes < 0)
			{
				if(errno == EINTR)
					continue;
				else
				{
					loop_running = false;
					break;
				}
			}
			else if(bytes >= 0)
			{
				safe_write(size_write,&bytes,sizeof(bytes));

				if(!check_write(stdin_write,buf,bytes))
					loop_running = false;
				break;
			}
		}
	}

	safe_close(stdin_write);
	safe_close(control_read);

	return NULL;
}

void safe_pipe(int *in, int *out)
{
	int filedes[2];

	if(pipe(filedes) < 0)
		fatal_error("Error opening pipe",errno);

	*in = filedes[0];
	*out = filedes[1];

	if(fcntl(*in,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);

	if(fcntl(*out,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);
}

void open_console()
{
	safe_pipe(&control_read,&control_write);
	safe_pipe(&size_read,&size_write);
	safe_pipe(&stdin_read,&stdin_write);
	start_thread(stdin_loop,NULL);
}

}
<|endoftext|>


<commit_before>#include <unistd.h>
#include <sys/param.h>
#include <dirent.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/time.h>
#include <dlfcn.h>
#include <signal.h>
#include <pthread.h>
#include <sched.h>

#include "atomic-gcc.hpp"

namespace factor {

typedef char vm_char;
typedef char symbol_char;

#define STRING_LITERAL(string) string

#define SSCANF sscanf
#define STRCMP strcmp
#define STRNCMP strncmp
#define STRDUP strdup
#define SNPRINTF snprintf

#define FTELL ftello
#define FSEEK fseeko

#define OPEN_READ(path) fopen(path, "rb")
#define OPEN_WRITE(path) fopen(path, "wb")
#define THREADSAFE_STRERROR(errnum, buf, buflen) strerror_r(errnum, buf, buflen)

#define print_native_string(string) print_string(string)

typedef pthread_t THREADHANDLE;

THREADHANDLE start_thread(void* (*start_routine)(void*), void* args);
inline static THREADHANDLE thread_id() { return pthread_self(); }

uint64_t nano_count();
void sleep_nanos(uint64_t nsec);

void move_file(const vm_char* path1, const vm_char* path2);

static inline void breakpoint() { __builtin_trap(); }

}
<commit_msg>os-unix.hpp: Use the old strerror_r insetad of the newfangled one.<commit_after>#include <unistd.h>
#include <sys/param.h>
#include <dirent.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/time.h>
#include <dlfcn.h>
#include <signal.h>
#include <pthread.h>
#include <sched.h>

#include "atomic-gcc.hpp"

namespace factor {

typedef char vm_char;
typedef char symbol_char;

#define STRING_LITERAL(string) string

#define SSCANF sscanf
#define STRCMP strcmp
#define STRNCMP strncmp
#define STRDUP strdup
#define SNPRINTF snprintf

#define FTELL ftello
#define FSEEK fseeko

#define OPEN_READ(path) fopen(path, "rb")
#define OPEN_WRITE(path) fopen(path, "wb")

#ifdef _GNU_SOURCE
extern "C" {
  extern int __xpg_strerror_r (int __errnum, char *__buf, size_t __buflen) __THROW __nonnull ((2));
}
#define strerror_r __xpg_strerror_r
#endif

#define THREADSAFE_STRERROR(errnum, buf, buflen) strerror_r(errnum, buf, buflen)

#define print_native_string(string) print_string(string)

typedef pthread_t THREADHANDLE;

THREADHANDLE start_thread(void* (*start_routine)(void*), void* args);
inline static THREADHANDLE thread_id() { return pthread_self(); }

uint64_t nano_count();
void sleep_nanos(uint64_t nsec);

void move_file(const vm_char* path1, const vm_char* path2);

static inline void breakpoint() { __builtin_trap(); }

}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "DashpotBC.h"

template<>
InputParameters validParams<DashpotBC>()
{
  InputParameters params = validParams<IntegratedBC>();
  params.addRequiredParam<unsigned int>("component", "The displacement component corresponding the variable this BC acts on.");
  params.addRequiredCoupledVar("disp_x", "Displacement in the x direction");
  params.addCoupledVar("disp_y", "Displacement in the y direction");
  params.addCoupledVar("disp_z", "Displacement in the z direction");

  params.addParam<Real>("coefficient", 1.0, "The viscocity coefficient");

  return params;
}

DashpotBC::DashpotBC(const std::string & name, InputParameters parameters) :
    IntegratedBC(name, parameters),
    _component(getParam<unsigned int>("component")),
    _coefficient(getParam<Real>("coefficient")),
    _disp_x_var(coupled("disp_x")),
    _disp_y_var(isCoupled("disp_y") ? coupled("disp_y") : 0),
    _disp_z_var(isCoupled("disp_z") ? coupled("disp_z") : 0),

    _disp_x_dot(coupledValue("disp_x")),
    _disp_y_dot(isCoupled("disp_y") ? coupledDot("disp_y") : _zero),
    _disp_z_dot(isCoupled("disp_z") ? coupledDot("disp_z") : _zero)
{}

Real
DashpotBC::computeQpResidual()
{
  RealVectorValue velocity(_disp_x_dot[_qp], _disp_y_dot[_qp], _disp_z_dot[_qp]);

  return _test[_i][_qp]*_coefficient*_normals[_qp]*velocity;
}

Real
DashpotBC::computeQpJacobian()
{
  RealVectorValue velocity;
  velocity(_component) = _phi[_j][_qp]/_dt;

  return _test[_i][_qp]*_coefficient*_normals[_qp]*velocity;
}

Real
DashpotBC::computeQpOffDiagJacobian(unsigned int jvar)
{
  RealVectorValue velocity;
  unsigned int component = 0;

  if(jvar == _disp_x_var)
    component = 0;
  else if(jvar == _disp_y_var)
    component = 1;
  else if(jvar == _disp_z_var)
    component = 2;

  velocity(component) = _phi[_j][_qp]/_dt;

  return -_test[_i][_qp]*_normals[_qp]*velocity;
}

<commit_msg>Fixing bug in DashpotBC: use coupledDot for time derivative, not coupledValue (#000)<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "DashpotBC.h"

template<>
InputParameters validParams<DashpotBC>()
{
  InputParameters params = validParams<IntegratedBC>();
  params.addRequiredParam<unsigned int>("component", "The displacement component corresponding the variable this BC acts on.");
  params.addRequiredCoupledVar("disp_x", "Displacement in the x direction");
  params.addCoupledVar("disp_y", "Displacement in the y direction");
  params.addCoupledVar("disp_z", "Displacement in the z direction");

  params.addParam<Real>("coefficient", 1.0, "The viscosity coefficient");

  return params;
}

DashpotBC::DashpotBC(const std::string & name, InputParameters parameters) :
    IntegratedBC(name, parameters),
    _component(getParam<unsigned int>("component")),
    _coefficient(getParam<Real>("coefficient")),
    _disp_x_var(coupled("disp_x")),
    _disp_y_var(isCoupled("disp_y") ? coupled("disp_y") : 0),
    _disp_z_var(isCoupled("disp_z") ? coupled("disp_z") : 0),

    _disp_x_dot(coupledDot("disp_x")),
    _disp_y_dot(isCoupled("disp_y") ? coupledDot("disp_y") : _zero),
    _disp_z_dot(isCoupled("disp_z") ? coupledDot("disp_z") : _zero)
{}

Real
DashpotBC::computeQpResidual()
{
  RealVectorValue velocity(_disp_x_dot[_qp], _disp_y_dot[_qp], _disp_z_dot[_qp]);

  return _test[_i][_qp]*_coefficient*_normals[_qp]*velocity;
}

Real
DashpotBC::computeQpJacobian()
{
  RealVectorValue velocity;
  velocity(_component) = _phi[_j][_qp]/_dt;

  return _test[_i][_qp]*_coefficient*_normals[_qp]*velocity;
}

Real
DashpotBC::computeQpOffDiagJacobian(unsigned int jvar)
{
  RealVectorValue velocity;
  unsigned int component = 0;

  if(jvar == _disp_x_var)
    component = 0;
  else if(jvar == _disp_y_var)
    component = 1;
  else if(jvar == _disp_z_var)
    component = 2;

  velocity(component) = _phi[_j][_qp]/_dt;

  return -_test[_i][_qp]*_normals[_qp]*velocity;
}

<|endoftext|>


<commit_before>#include "console_printer.h"
#include "console_inputter.h"
#include "framework.h"

void setup(void);
void testBringup(lc3::sim & sim);
void testTeardown(lc3::sim & sim);

std::vector<TestCase> tests;
uint32_t verify_count;
uint32_t verify_valid;

void BufferedPrinter::print(std::string const & string)
{
    std::copy(string.begin(), string.end(), std::back_inserter(display_buffer));
}

void BufferedPrinter::newline(void) { display_buffer.push_back('\n'); }

bool FileInputter::getChar(char & c)
{
    return false;
}

StringInputter::StringInputter(std::string const & source)
{
    this->source = source;
    this->pos = 0;
}

bool StringInputter::getChar(char & c)
{
    if(pos == source.size()) {
        return false;
    }

    c = source[pos];
    pos += 1;
    return true;
}

int main(int argc, char ** argv)
{
    lc3::ConsolePrinter asm_printer;
    lc3::as assembler(asm_printer);

    std::vector<std::string> obj_filenames;
    bool valid_assembly = true;
    for(int i = 1; i < argc; i += 1) {
        std::string asm_filename(argv[i]);

        auto result = assembler.assemble(asm_filename);
        if(! result.first) { valid_assembly = false; }
        obj_filenames.push_back(result.second);
    }

    setup();

    uint32_t total_points_earned = 0;
    uint32_t total_possible_points = 0;

    if(valid_assembly) {
        for(TestCase const & test : tests) {
            lc3::utils::NullPrinter sim_printer;
            FileInputter sim_inputter;
            lc3::sim simulator(sim_printer, sim_inputter, 0);

            testBringup(simulator);

            verify_count = 0;
            verify_valid = 0;

            total_possible_points += test.points;

            std::cout << "Test: " << test.name;
            if(test.randomize) {
                simulator.randomize();
                std::cout << " (Randomized Machine)";
            }
            std::cout << std::endl;
            for(std::string const & obj_filename : obj_filenames) {
                if(! simulator.loadObjectFile(obj_filename)) {
                    std::cout << "could not init simulator\n";
                    return 2;
                }
            }

            try {
                test.test_func(simulator);
            } catch(lc3::utils::exception const & e) {
                continue;
            }

            testTeardown(simulator);

            float percent_points_earned = ((float) verify_valid) / verify_count;
            uint32_t points_earned = (uint32_t) ( percent_points_earned * test.points);
            std::cout << "test points earned: " << points_earned << "/" << test.points << " ("
                      << (percent_points_earned * 100) << "%)\n";
            std::cout << "==========\n";

            total_points_earned += points_earned;
        }
    }

    std::cout << "==========\n";
    float percent_points_earned = ((float) total_points_earned) / total_possible_points;
    std::cout << "total points earned: " << total_points_earned << "/" << total_possible_points << " ("
              << (percent_points_earned * 100) << "%)\n";

    return 0;
}
<commit_msg>[grader] Allow bin files in grading framework<commit_after>#include "console_printer.h"
#include "console_inputter.h"
#include "framework.h"

void setup(void);
void testBringup(lc3::sim & sim);
void testTeardown(lc3::sim & sim);

std::vector<TestCase> tests;
uint32_t verify_count;
uint32_t verify_valid;

bool endsWith(std::string const & search, std::string const & suffix)
{
    if(suffix.size() > search.size()) { return false; }
    return std::equal(suffix.rbegin(), suffix.rend(), search.rbegin());
}

void BufferedPrinter::print(std::string const & string)
{
    std::copy(string.begin(), string.end(), std::back_inserter(display_buffer));
}

void BufferedPrinter::newline(void) { display_buffer.push_back('\n'); }

bool FileInputter::getChar(char & c)
{
    return false;
}

StringInputter::StringInputter(std::string const & source)
{
    this->source = source;
    this->pos = 0;
}

bool StringInputter::getChar(char & c)
{
    if(pos == source.size()) {
        return false;
    }

    c = source[pos];
    pos += 1;
    return true;
}

int main(int argc, char ** argv)
{
    lc3::ConsolePrinter asm_printer;
    lc3::as assembler(asm_printer);

    std::vector<std::string> obj_filenames;
    bool valid_assembly = true;
    for(int i = 1; i < argc; i += 1) {
        std::string filename(argv[i]);

	if(endsWith(filename, ".bin")) {
	    assembler.convertBin(filename);
	} else {
            auto result = assembler.assemble(filename);
            if(! result.first) { valid_assembly = false; }
            obj_filenames.push_back(result.second);
	}

    }

    setup();

    uint32_t total_points_earned = 0;
    uint32_t total_possible_points = 0;

    if(valid_assembly) {
        for(TestCase const & test : tests) {
            lc3::utils::NullPrinter sim_printer;
            FileInputter sim_inputter;
            lc3::sim simulator(sim_printer, sim_inputter, 0);

            testBringup(simulator);

            verify_count = 0;
            verify_valid = 0;

            total_possible_points += test.points;

            std::cout << "Test: " << test.name;
            if(test.randomize) {
                simulator.randomize();
                std::cout << " (Randomized Machine)";
            }
            std::cout << std::endl;
            for(std::string const & obj_filename : obj_filenames) {
                if(! simulator.loadObjectFile(obj_filename)) {
                    std::cout << "could not init simulator\n";
                    return 2;
                }
            }

            try {
                test.test_func(simulator);
            } catch(lc3::utils::exception const & e) {
                continue;
            }

            testTeardown(simulator);

            float percent_points_earned = ((float) verify_valid) / verify_count;
            uint32_t points_earned = (uint32_t) ( percent_points_earned * test.points);
            std::cout << "test points earned: " << points_earned << "/" << test.points << " ("
                      << (percent_points_earned * 100) << "%)\n";
            std::cout << "==========\n";

            total_points_earned += points_earned;
        }
    }

    std::cout << "==========\n";
    float percent_points_earned = ((float) total_points_earned) / total_possible_points;
    std::cout << "total points earned: " << total_points_earned << "/" << total_possible_points << " ("
              << (percent_points_earned * 100) << "%)\n";

    return 0;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2012 Batis Degryll Ludo
 * @file EventStore.cpp
 * @since 2016-03-26
 * @date 2016-03-26
 * @author Ludo
 * @brief A container to store events. It will store only the sooner event (or events) and will discard every other.
 */

#include "ZBE/core/events/EventStore.h"

namespace zbe {

void EventStore::storeEvent(Event* e) {
  if(e->getTime() == bettertime){
    store.push_front(e);
  } else if (e->getTime() < bettertime){
    bettertime = e->getTime();
    store.clear();
    store.push_front(e);
  }
}

}
<commit_msg>Some work on the #27<commit_after>/**
 * Copyright 2012 Batis Degryll Ludo
 * @file EventStore.cpp
 * @since 2016-03-26
 * @date 2016-03-26
 * @author Ludo
 * @brief A container to store events. It will store only the sooner event (or events) and will discard every other.
 */

#include "ZBE/core/events/EventStore.h"

namespace zbe {

static bool deleteAll(Event* e) {
  delete e;
  return true;
}

void EventStore::storeEvent(Event* e) {
  if(e->getTime() == bettertime){
    store.push_front(e);
  } else if (e->getTime() < bettertime){
    bettertime = e->getTime();
    store.remove_if(deleteAll());
    store.push_front(e);
  }
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CategoryPositionHelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:33:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#ifndef _CHART2_CATEGORYPOSITIONHELPER_HXX
#include "CategoryPositionHelper.hxx"
#endif

//.............................................................................
namespace chart
{
//.............................................................................
//using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;

CategoryPositionHelper::CategoryPositionHelper( double fSeriesCount, double fCategoryWidth )
    : m_fSeriesCount(fSeriesCount)
    , m_fCategoryWidth(fCategoryWidth)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(1.0)
{
}

CategoryPositionHelper::CategoryPositionHelper()
    : m_fSeriesCount(1.0)
    , m_fCategoryWidth(1.0)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(0.0)
{
}

CategoryPositionHelper::~CategoryPositionHelper()
{
}

double CategoryPositionHelper::getSlotWidth() const
{
    double fWidth = m_fCategoryWidth /
                (  m_fSeriesCount
                 + m_fOuterDistance
                 + m_fInnerDistance*( m_fSeriesCount - 1.0) );
    return fWidth;
}

double CategoryPositionHelper::getSlotPos( double fCategoryX, double fSeriesNumber ) const
{
    //the returned position is in the middle of the rect
    //fSeriesNumber 0...n-1
    double fPos = fCategoryX - (m_fCategoryWidth/2.0)
           + (m_fOuterDistance/2.0 + fSeriesNumber*(1.0+m_fInnerDistance)) * getSlotWidth()
           + getSlotWidth()/2.0;

    return fPos;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2006/10/18 17:22:02 bm 1.2.4.4: RESYNC: (1.2-1.3); FILE MERGED 2006/03/09 17:41:17 iha 1.2.4.3: added header 2005/11/22 14:09:45 iha 1.2.4.2: support BarOverlap and GapWidth 2005/10/24 11:07:06 iha 1.2.4.1: coordinate system restructure<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CategoryPositionHelper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:15:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"

#ifndef _CHART2_CATEGORYPOSITIONHELPER_HXX
#include "CategoryPositionHelper.hxx"
#endif

//.............................................................................
namespace chart
{
//.............................................................................
//using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;

CategoryPositionHelper::CategoryPositionHelper( double fSeriesCount, double fCategoryWidth )
    : m_fSeriesCount(fSeriesCount)
    , m_fCategoryWidth(fCategoryWidth)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(1.0)
{
}

CategoryPositionHelper::CategoryPositionHelper( const CategoryPositionHelper& rSource )
    : m_fSeriesCount( rSource.m_fSeriesCount )
    , m_fCategoryWidth( rSource.m_fCategoryWidth )
    , m_fInnerDistance( rSource.m_fInnerDistance )
    , m_fOuterDistance( rSource.m_fOuterDistance )
{
}

CategoryPositionHelper::CategoryPositionHelper()
    : m_fSeriesCount(1.0)
    , m_fCategoryWidth(1.0)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(0.0)
{
}

CategoryPositionHelper::~CategoryPositionHelper()
{
}

double CategoryPositionHelper::getSlotWidth() const
{
    double fWidth = m_fCategoryWidth /
                (  m_fSeriesCount
                 + m_fOuterDistance
                 + m_fInnerDistance*( m_fSeriesCount - 1.0) );
    return fWidth;
}

double CategoryPositionHelper::getSlotPos( double fCategoryX, double fSeriesNumber ) const
{
    //the returned position is in the middle of the rect
    //fSeriesNumber 0...n-1
    double fPos = fCategoryX - (m_fCategoryWidth/2.0)
           + (m_fOuterDistance/2.0 + fSeriesNumber*(1.0+m_fInnerDistance)) * getSlotWidth()
           + getSlotWidth()/2.0;

    return fPos;
}

void CategoryPositionHelper::setInnerDistance( double fInnerDistance )
{
    if( fInnerDistance < -1.0 )
        fInnerDistance = -1.0;
    if( fInnerDistance > 1.0 )
        fInnerDistance = 1.0;
    m_fInnerDistance = fInnerDistance;
}

void CategoryPositionHelper::setOuterDistance( double fOuterDistance )
{
    if( fOuterDistance < 0.0 )
        fOuterDistance = 0.0;
    if( fOuterDistance > 6.0 )
        fOuterDistance = 6.0;
    m_fOuterDistance = fOuterDistance;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/android/compositor/tab_content_manager.h"

#include <android/bitmap.h>

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "cc/layers/layer.h"
#include "chrome/browser/android/compositor/layer/thumbnail_layer.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/android/thumbnail/thumbnail.h"
#include "content/public/browser/android/content_view_core.h"
#include "content/public/browser/readback_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "jni/TabContentManager_jni.h"
#include "ui/android/resources/ui_resource_provider.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/geometry/rect.h"
#include "url/gurl.h"

namespace {

const size_t kMaxReadbacks = 1;
typedef base::Callback<void(float, const SkBitmap&)> TabReadbackCallback;

}  // namespace

namespace chrome {
namespace android {

class TabContentManager::TabReadbackRequest {
 public:
  TabReadbackRequest(jobject content_view_core,
                     float thumbnail_scale,
                     const TabReadbackCallback& end_callback)
      : thumbnail_scale_(thumbnail_scale),
        end_callback_(end_callback),
        drop_after_readback_(false),
        weak_factory_(this) {
    JNIEnv* env = base::android::AttachCurrentThread();
    j_content_view_core_.Reset(env, content_view_core);
  }

  virtual ~TabReadbackRequest() {}

  void Run() {
    JNIEnv* env = base::android::AttachCurrentThread();
    content::ReadbackRequestCallback result_callback =
        base::Bind(&TabReadbackRequest::OnFinishGetTabThumbnailBitmap,
                   weak_factory_.GetWeakPtr());

    if (j_content_view_core_.is_null()) {
      result_callback.Run(SkBitmap(), content::READBACK_FAILED);
      return;
    }

    content::ContentViewCore* view =
        content::ContentViewCore::GetNativeContentViewCore(
            env, j_content_view_core_.obj());

    if (!view) {
      result_callback.Run(SkBitmap(), content::READBACK_FAILED);
      return;
    }

    DCHECK(view->GetWebContents());
    view->GetWebContents()->GetRenderViewHost()->LockBackingStore();

    SkColorType color_type = kN32_SkColorType;

    // Calling this method with an empty rect will return a bitmap of the size
    // of the content.
    view->GetScaledContentBitmap(thumbnail_scale_, color_type, gfx::Rect(),
                                 result_callback);
  }

  void OnFinishGetTabThumbnailBitmap(const SkBitmap& bitmap,
                                     content::ReadbackResponse response) {
    DCHECK(!j_content_view_core_.is_null());
    JNIEnv* env = base::android::AttachCurrentThread();
    content::ContentViewCore* view =
        content::ContentViewCore::GetNativeContentViewCore(
            env, j_content_view_core_.obj());

    if (view) {
      DCHECK(view->GetWebContents());
      view->GetWebContents()->GetRenderViewHost()->UnlockBackingStore();
    }

    // TODO(jdduke): Tailor response to different failure values appropriately.
    if (response != content::READBACK_SUCCESS || drop_after_readback_) {
      end_callback_.Run(0.f, SkBitmap());
      return;
    }

    SkBitmap result_bitmap = bitmap;
    result_bitmap.setImmutable();
    end_callback_.Run(thumbnail_scale_, bitmap);
  }

  void SetToDropAfterReadback() { drop_after_readback_ = true; }

 private:
  base::android::ScopedJavaGlobalRef<jobject> j_content_view_core_;
  const float thumbnail_scale_;
  TabReadbackCallback end_callback_;
  bool drop_after_readback_;

  base::WeakPtrFactory<TabReadbackRequest> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(TabReadbackRequest);
};

// static
TabContentManager* TabContentManager::FromJavaObject(jobject jobj) {
  if (!jobj)
    return NULL;
  return reinterpret_cast<TabContentManager*>(
      Java_TabContentManager_getNativePtr(base::android::AttachCurrentThread(),
                                          jobj));
}

TabContentManager::TabContentManager(JNIEnv* env,
                                     jobject obj,
                                     jstring disk_cache_path,
                                     jint default_cache_size,
                                     jint approximation_cache_size,
                                     jint compression_queue_max_size,
                                     jint write_queue_max_size,
                                     jboolean use_approximation_thumbnail)
    : weak_java_tab_content_manager_(env, obj), weak_factory_(this) {
  std::string disk_cache_path_str =
      base::android::ConvertJavaStringToUTF8(env, disk_cache_path);
  thumbnail_cache_ = make_scoped_ptr(new ThumbnailCache(
      disk_cache_path_str, (size_t)default_cache_size,
      (size_t)approximation_cache_size, (size_t)compression_queue_max_size,
      (size_t)write_queue_max_size, use_approximation_thumbnail));
  thumbnail_cache_->AddThumbnailStoreObserver(this);
}

TabContentManager::~TabContentManager() {
}

void TabContentManager::Destroy(JNIEnv* env, jobject obj) {
  thumbnail_cache_->RemoveThumbnailStoreObserver(this);
  delete this;
}

void TabContentManager::SetUIResourceProvider(JNIEnv* env,
                                              jobject obj,
                                              jlong ui_resource_provider_ptr) {
  ui::UIResourceProvider* ui_resource_provider =
      reinterpret_cast<ui::UIResourceProvider*>(ui_resource_provider_ptr);
  SetUIResourceProvider(ui_resource_provider);
}

void TabContentManager::SetUIResourceProvider(
    ui::UIResourceProvider* ui_resource_provider) {
  thumbnail_cache_->SetUIResourceProvider(ui_resource_provider);
}

scoped_refptr<cc::Layer> TabContentManager::GetLiveLayer(int tab_id) {
  scoped_refptr<cc::Layer> layer = live_layer_list_[tab_id];
  if (!layer.get())
    return NULL;

  return layer;
}

scoped_refptr<ThumbnailLayer> TabContentManager::GetStaticLayer(
    int tab_id,
    bool force_disk_read) {
  Thumbnail* thumbnail = thumbnail_cache_->Get(tab_id, force_disk_read, true);
  scoped_refptr<ThumbnailLayer> static_layer = static_layer_cache_[tab_id];

  if (!thumbnail || !thumbnail->ui_resource_id()) {
    if (static_layer.get()) {
      static_layer->layer()->RemoveFromParent();
      static_layer_cache_.erase(tab_id);
    }
    return NULL;
  }

  if (!static_layer.get()) {
    static_layer = ThumbnailLayer::Create();
    static_layer_cache_[tab_id] = static_layer;
  }

  static_layer->SetThumbnail(thumbnail);
  return static_layer;
}

void TabContentManager::AttachLiveLayer(int tab_id,
                                        scoped_refptr<cc::Layer> layer) {
  if (!layer.get())
    return;

  scoped_refptr<cc::Layer> cached_layer = live_layer_list_[tab_id];
  if (cached_layer != layer)
    live_layer_list_[tab_id] = layer;
}

void TabContentManager::DetachLiveLayer(int tab_id,
                                        scoped_refptr<cc::Layer> layer) {
  scoped_refptr<cc::Layer> current_layer = live_layer_list_[tab_id];
  if (!current_layer.get()) {
    // Empty cached layer should not exist but it is ok if it happens.
    return;
  }

  // We need to remove if we're getting a detach for our current layer or we're
  // getting a detach with NULL and we have a current layer, which means remove
  //  all layers.
  if (current_layer.get() &&
      (layer.get() == current_layer.get() || !layer.get())) {
    live_layer_list_.erase(tab_id);
  }
}

void TabContentManager::OnFinishDecompressThumbnail(int tab_id,
                                                    bool success,
                                                    SkBitmap bitmap) {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jobject> java_bitmap;
  if (success)
    java_bitmap = gfx::ConvertToJavaBitmap(&bitmap);

  Java_TabContentManager_notifyDecompressBitmapFinished(
      env, weak_java_tab_content_manager_.get(env).obj(), tab_id,
      java_bitmap.obj());
}

jboolean TabContentManager::HasFullCachedThumbnail(JNIEnv* env,
                                                   jobject obj,
                                                   jint tab_id) {
  return thumbnail_cache_->Get(tab_id, false, false) != nullptr;
}

void TabContentManager::CacheTab(JNIEnv* env,
                                 jobject obj,
                                 jobject tab,
                                 jobject content_view_core,
                                 jfloat thumbnail_scale) {
  TabAndroid* tab_android =
      static_cast<TabAndroid*>(TabAndroid::GetNativeTab(env, tab));
  DCHECK(tab_android);
  int tab_id = tab_android->GetAndroidId();
  GURL url = tab_android->GetURL();

  content::ContentViewCore* view =
      content::ContentViewCore::GetNativeContentViewCore(env,
                                                         content_view_core);

  if (thumbnail_cache_->CheckAndUpdateThumbnailMetaData(tab_id, url)) {
    if (!view ||
        !view->GetWebContents()
             ->GetRenderViewHost()
             ->CanCopyFromBackingStore() ||
        pending_tab_readbacks_.find(tab_id) != pending_tab_readbacks_.end() ||
        pending_tab_readbacks_.size() >= kMaxReadbacks) {
      thumbnail_cache_->Remove(tab_id);
      return;
    }

    TabReadbackCallback readback_done_callback =
        base::Bind(&TabContentManager::PutThumbnailIntoCache,
                   weak_factory_.GetWeakPtr(), tab_id);
    scoped_ptr<TabReadbackRequest> readback_request =
        make_scoped_ptr(new TabReadbackRequest(
            content_view_core, thumbnail_scale, readback_done_callback));
    pending_tab_readbacks_.set(tab_id, readback_request.Pass());
    pending_tab_readbacks_.get(tab_id)->Run();
  }
}

void TabContentManager::CacheTabWithBitmap(JNIEnv* env,
                                           jobject obj,
                                           jobject tab,
                                           jobject bitmap,
                                           jfloat thumbnail_scale) {
  TabAndroid* tab_android =
      static_cast<TabAndroid*>(TabAndroid::GetNativeTab(env, tab));
  DCHECK(tab_android);
  int tab_id = tab_android->GetAndroidId();
  GURL url = tab_android->GetURL();

  gfx::JavaBitmap java_bitmap_lock(bitmap);
  SkBitmap skbitmap = gfx::CreateSkBitmapFromJavaBitmap(java_bitmap_lock);
  skbitmap.setImmutable();

  if (thumbnail_cache_->CheckAndUpdateThumbnailMetaData(tab_id, url))
    PutThumbnailIntoCache(tab_id, thumbnail_scale, skbitmap);
}

void TabContentManager::InvalidateIfChanged(JNIEnv* env,
                                            jobject obj,
                                            jint tab_id,
                                            jstring jurl) {
  thumbnail_cache_->InvalidateThumbnailIfChanged(
      tab_id, GURL(base::android::ConvertJavaStringToUTF8(env, jurl)));
}

void TabContentManager::UpdateVisibleIds(JNIEnv* env,
                                         jobject obj,
                                         jintArray priority) {
  std::list<int> priority_ids;
  jsize length = env->GetArrayLength(priority);
  jint* ints = env->GetIntArrayElements(priority, NULL);
  for (jsize i = 0; i < length; ++i)
    priority_ids.push_back(static_cast<int>(ints[i]));

  env->ReleaseIntArrayElements(priority, ints, JNI_ABORT);
  thumbnail_cache_->UpdateVisibleIds(priority_ids);
}

void TabContentManager::RemoveTabThumbnail(JNIEnv* env,
                                           jobject obj,
                                           jint tab_id) {
  TabReadbackRequestMap::iterator readback_iter =
      pending_tab_readbacks_.find(tab_id);
  if (readback_iter != pending_tab_readbacks_.end())
    readback_iter->second->SetToDropAfterReadback();
  thumbnail_cache_->Remove(tab_id);
}

void TabContentManager::RemoveTabThumbnailFromDiskAtAndAboveId(
    JNIEnv* env,
    jobject obj,
    jint min_forbidden_id) {
  thumbnail_cache_->RemoveFromDiskAtAndAboveId(min_forbidden_id);
}

void TabContentManager::GetDecompressedThumbnail(JNIEnv* env,
                                                 jobject obj,
                                                 jint tab_id) {
  base::Callback<void(bool, SkBitmap)> decompress_done_callback =
      base::Bind(&TabContentManager::OnFinishDecompressThumbnail,
                 weak_factory_.GetWeakPtr(), reinterpret_cast<int>(tab_id));
  thumbnail_cache_->DecompressThumbnailFromFile(reinterpret_cast<int>(tab_id),
                                                decompress_done_callback);
}

void TabContentManager::OnFinishedThumbnailRead(int tab_id) {
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_TabContentManager_notifyListenersOfThumbnailChange(
      env, weak_java_tab_content_manager_.get(env).obj(), tab_id);
}

void TabContentManager::PutThumbnailIntoCache(int tab_id,
                                              float thumbnail_scale,
                                              const SkBitmap& bitmap) {
  TabReadbackRequestMap::iterator readback_iter =
      pending_tab_readbacks_.find(tab_id);

  if (readback_iter != pending_tab_readbacks_.end())
    pending_tab_readbacks_.erase(tab_id);

  if (thumbnail_scale > 0 && !bitmap.empty())
    thumbnail_cache_->Put(tab_id, bitmap, thumbnail_scale);
}

bool RegisterTabContentManager(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

// ----------------------------------------------------------------------------
// Native JNI methods
// ----------------------------------------------------------------------------

jlong Init(JNIEnv* env,
           jobject obj,
           jstring disk_cache_path,
           jint default_cache_size,
           jint approximation_cache_size,
           jint compression_queue_max_size,
           jint write_queue_max_size,
           jboolean use_approximation_thumbnail) {
  TabContentManager* manager = new TabContentManager(
      env, obj, disk_cache_path, default_cache_size, approximation_cache_size,
      compression_queue_max_size, write_queue_max_size,
      use_approximation_thumbnail);
  return reinterpret_cast<intptr_t>(manager);
}

}  // namespace android
}  // namespace chrome
<commit_msg>Remove unncessary type cast<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/android/compositor/tab_content_manager.h"

#include <android/bitmap.h>

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "cc/layers/layer.h"
#include "chrome/browser/android/compositor/layer/thumbnail_layer.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/android/thumbnail/thumbnail.h"
#include "content/public/browser/android/content_view_core.h"
#include "content/public/browser/readback_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "jni/TabContentManager_jni.h"
#include "ui/android/resources/ui_resource_provider.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/geometry/rect.h"
#include "url/gurl.h"

namespace {

const size_t kMaxReadbacks = 1;
typedef base::Callback<void(float, const SkBitmap&)> TabReadbackCallback;

}  // namespace

namespace chrome {
namespace android {

class TabContentManager::TabReadbackRequest {
 public:
  TabReadbackRequest(jobject content_view_core,
                     float thumbnail_scale,
                     const TabReadbackCallback& end_callback)
      : thumbnail_scale_(thumbnail_scale),
        end_callback_(end_callback),
        drop_after_readback_(false),
        weak_factory_(this) {
    JNIEnv* env = base::android::AttachCurrentThread();
    j_content_view_core_.Reset(env, content_view_core);
  }

  virtual ~TabReadbackRequest() {}

  void Run() {
    JNIEnv* env = base::android::AttachCurrentThread();
    content::ReadbackRequestCallback result_callback =
        base::Bind(&TabReadbackRequest::OnFinishGetTabThumbnailBitmap,
                   weak_factory_.GetWeakPtr());

    if (j_content_view_core_.is_null()) {
      result_callback.Run(SkBitmap(), content::READBACK_FAILED);
      return;
    }

    content::ContentViewCore* view =
        content::ContentViewCore::GetNativeContentViewCore(
            env, j_content_view_core_.obj());

    if (!view) {
      result_callback.Run(SkBitmap(), content::READBACK_FAILED);
      return;
    }

    DCHECK(view->GetWebContents());
    view->GetWebContents()->GetRenderViewHost()->LockBackingStore();

    SkColorType color_type = kN32_SkColorType;

    // Calling this method with an empty rect will return a bitmap of the size
    // of the content.
    view->GetScaledContentBitmap(thumbnail_scale_, color_type, gfx::Rect(),
                                 result_callback);
  }

  void OnFinishGetTabThumbnailBitmap(const SkBitmap& bitmap,
                                     content::ReadbackResponse response) {
    DCHECK(!j_content_view_core_.is_null());
    JNIEnv* env = base::android::AttachCurrentThread();
    content::ContentViewCore* view =
        content::ContentViewCore::GetNativeContentViewCore(
            env, j_content_view_core_.obj());

    if (view) {
      DCHECK(view->GetWebContents());
      view->GetWebContents()->GetRenderViewHost()->UnlockBackingStore();
    }

    // TODO(jdduke): Tailor response to different failure values appropriately.
    if (response != content::READBACK_SUCCESS || drop_after_readback_) {
      end_callback_.Run(0.f, SkBitmap());
      return;
    }

    SkBitmap result_bitmap = bitmap;
    result_bitmap.setImmutable();
    end_callback_.Run(thumbnail_scale_, bitmap);
  }

  void SetToDropAfterReadback() { drop_after_readback_ = true; }

 private:
  base::android::ScopedJavaGlobalRef<jobject> j_content_view_core_;
  const float thumbnail_scale_;
  TabReadbackCallback end_callback_;
  bool drop_after_readback_;

  base::WeakPtrFactory<TabReadbackRequest> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(TabReadbackRequest);
};

// static
TabContentManager* TabContentManager::FromJavaObject(jobject jobj) {
  if (!jobj)
    return NULL;
  return reinterpret_cast<TabContentManager*>(
      Java_TabContentManager_getNativePtr(base::android::AttachCurrentThread(),
                                          jobj));
}

TabContentManager::TabContentManager(JNIEnv* env,
                                     jobject obj,
                                     jstring disk_cache_path,
                                     jint default_cache_size,
                                     jint approximation_cache_size,
                                     jint compression_queue_max_size,
                                     jint write_queue_max_size,
                                     jboolean use_approximation_thumbnail)
    : weak_java_tab_content_manager_(env, obj), weak_factory_(this) {
  std::string disk_cache_path_str =
      base::android::ConvertJavaStringToUTF8(env, disk_cache_path);
  thumbnail_cache_ = make_scoped_ptr(new ThumbnailCache(
      disk_cache_path_str, (size_t)default_cache_size,
      (size_t)approximation_cache_size, (size_t)compression_queue_max_size,
      (size_t)write_queue_max_size, use_approximation_thumbnail));
  thumbnail_cache_->AddThumbnailStoreObserver(this);
}

TabContentManager::~TabContentManager() {
}

void TabContentManager::Destroy(JNIEnv* env, jobject obj) {
  thumbnail_cache_->RemoveThumbnailStoreObserver(this);
  delete this;
}

void TabContentManager::SetUIResourceProvider(JNIEnv* env,
                                              jobject obj,
                                              jlong ui_resource_provider_ptr) {
  ui::UIResourceProvider* ui_resource_provider =
      reinterpret_cast<ui::UIResourceProvider*>(ui_resource_provider_ptr);
  SetUIResourceProvider(ui_resource_provider);
}

void TabContentManager::SetUIResourceProvider(
    ui::UIResourceProvider* ui_resource_provider) {
  thumbnail_cache_->SetUIResourceProvider(ui_resource_provider);
}

scoped_refptr<cc::Layer> TabContentManager::GetLiveLayer(int tab_id) {
  scoped_refptr<cc::Layer> layer = live_layer_list_[tab_id];
  if (!layer.get())
    return NULL;

  return layer;
}

scoped_refptr<ThumbnailLayer> TabContentManager::GetStaticLayer(
    int tab_id,
    bool force_disk_read) {
  Thumbnail* thumbnail = thumbnail_cache_->Get(tab_id, force_disk_read, true);
  scoped_refptr<ThumbnailLayer> static_layer = static_layer_cache_[tab_id];

  if (!thumbnail || !thumbnail->ui_resource_id()) {
    if (static_layer.get()) {
      static_layer->layer()->RemoveFromParent();
      static_layer_cache_.erase(tab_id);
    }
    return NULL;
  }

  if (!static_layer.get()) {
    static_layer = ThumbnailLayer::Create();
    static_layer_cache_[tab_id] = static_layer;
  }

  static_layer->SetThumbnail(thumbnail);
  return static_layer;
}

void TabContentManager::AttachLiveLayer(int tab_id,
                                        scoped_refptr<cc::Layer> layer) {
  if (!layer.get())
    return;

  scoped_refptr<cc::Layer> cached_layer = live_layer_list_[tab_id];
  if (cached_layer != layer)
    live_layer_list_[tab_id] = layer;
}

void TabContentManager::DetachLiveLayer(int tab_id,
                                        scoped_refptr<cc::Layer> layer) {
  scoped_refptr<cc::Layer> current_layer = live_layer_list_[tab_id];
  if (!current_layer.get()) {
    // Empty cached layer should not exist but it is ok if it happens.
    return;
  }

  // We need to remove if we're getting a detach for our current layer or we're
  // getting a detach with NULL and we have a current layer, which means remove
  //  all layers.
  if (current_layer.get() &&
      (layer.get() == current_layer.get() || !layer.get())) {
    live_layer_list_.erase(tab_id);
  }
}

void TabContentManager::OnFinishDecompressThumbnail(int tab_id,
                                                    bool success,
                                                    SkBitmap bitmap) {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jobject> java_bitmap;
  if (success)
    java_bitmap = gfx::ConvertToJavaBitmap(&bitmap);

  Java_TabContentManager_notifyDecompressBitmapFinished(
      env, weak_java_tab_content_manager_.get(env).obj(), tab_id,
      java_bitmap.obj());
}

jboolean TabContentManager::HasFullCachedThumbnail(JNIEnv* env,
                                                   jobject obj,
                                                   jint tab_id) {
  return thumbnail_cache_->Get(tab_id, false, false) != nullptr;
}

void TabContentManager::CacheTab(JNIEnv* env,
                                 jobject obj,
                                 jobject tab,
                                 jobject content_view_core,
                                 jfloat thumbnail_scale) {
  TabAndroid* tab_android = TabAndroid::GetNativeTab(env, tab);
  DCHECK(tab_android);
  int tab_id = tab_android->GetAndroidId();
  GURL url = tab_android->GetURL();

  content::ContentViewCore* view =
      content::ContentViewCore::GetNativeContentViewCore(env,
                                                         content_view_core);

  if (thumbnail_cache_->CheckAndUpdateThumbnailMetaData(tab_id, url)) {
    if (!view ||
        !view->GetWebContents()
             ->GetRenderViewHost()
             ->CanCopyFromBackingStore() ||
        pending_tab_readbacks_.find(tab_id) != pending_tab_readbacks_.end() ||
        pending_tab_readbacks_.size() >= kMaxReadbacks) {
      thumbnail_cache_->Remove(tab_id);
      return;
    }

    TabReadbackCallback readback_done_callback =
        base::Bind(&TabContentManager::PutThumbnailIntoCache,
                   weak_factory_.GetWeakPtr(), tab_id);
    scoped_ptr<TabReadbackRequest> readback_request =
        make_scoped_ptr(new TabReadbackRequest(
            content_view_core, thumbnail_scale, readback_done_callback));
    pending_tab_readbacks_.set(tab_id, readback_request.Pass());
    pending_tab_readbacks_.get(tab_id)->Run();
  }
}

void TabContentManager::CacheTabWithBitmap(JNIEnv* env,
                                           jobject obj,
                                           jobject tab,
                                           jobject bitmap,
                                           jfloat thumbnail_scale) {
  TabAndroid* tab_android = TabAndroid::GetNativeTab(env, tab);
  DCHECK(tab_android);
  int tab_id = tab_android->GetAndroidId();
  GURL url = tab_android->GetURL();

  gfx::JavaBitmap java_bitmap_lock(bitmap);
  SkBitmap skbitmap = gfx::CreateSkBitmapFromJavaBitmap(java_bitmap_lock);
  skbitmap.setImmutable();

  if (thumbnail_cache_->CheckAndUpdateThumbnailMetaData(tab_id, url))
    PutThumbnailIntoCache(tab_id, thumbnail_scale, skbitmap);
}

void TabContentManager::InvalidateIfChanged(JNIEnv* env,
                                            jobject obj,
                                            jint tab_id,
                                            jstring jurl) {
  thumbnail_cache_->InvalidateThumbnailIfChanged(
      tab_id, GURL(base::android::ConvertJavaStringToUTF8(env, jurl)));
}

void TabContentManager::UpdateVisibleIds(JNIEnv* env,
                                         jobject obj,
                                         jintArray priority) {
  std::list<int> priority_ids;
  jsize length = env->GetArrayLength(priority);
  jint* ints = env->GetIntArrayElements(priority, NULL);
  for (jsize i = 0; i < length; ++i)
    priority_ids.push_back(static_cast<int>(ints[i]));

  env->ReleaseIntArrayElements(priority, ints, JNI_ABORT);
  thumbnail_cache_->UpdateVisibleIds(priority_ids);
}

void TabContentManager::RemoveTabThumbnail(JNIEnv* env,
                                           jobject obj,
                                           jint tab_id) {
  TabReadbackRequestMap::iterator readback_iter =
      pending_tab_readbacks_.find(tab_id);
  if (readback_iter != pending_tab_readbacks_.end())
    readback_iter->second->SetToDropAfterReadback();
  thumbnail_cache_->Remove(tab_id);
}

void TabContentManager::RemoveTabThumbnailFromDiskAtAndAboveId(
    JNIEnv* env,
    jobject obj,
    jint min_forbidden_id) {
  thumbnail_cache_->RemoveFromDiskAtAndAboveId(min_forbidden_id);
}

void TabContentManager::GetDecompressedThumbnail(JNIEnv* env,
                                                 jobject obj,
                                                 jint tab_id) {
  base::Callback<void(bool, SkBitmap)> decompress_done_callback =
      base::Bind(&TabContentManager::OnFinishDecompressThumbnail,
                 weak_factory_.GetWeakPtr(), reinterpret_cast<int>(tab_id));
  thumbnail_cache_->DecompressThumbnailFromFile(reinterpret_cast<int>(tab_id),
                                                decompress_done_callback);
}

void TabContentManager::OnFinishedThumbnailRead(int tab_id) {
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_TabContentManager_notifyListenersOfThumbnailChange(
      env, weak_java_tab_content_manager_.get(env).obj(), tab_id);
}

void TabContentManager::PutThumbnailIntoCache(int tab_id,
                                              float thumbnail_scale,
                                              const SkBitmap& bitmap) {
  TabReadbackRequestMap::iterator readback_iter =
      pending_tab_readbacks_.find(tab_id);

  if (readback_iter != pending_tab_readbacks_.end())
    pending_tab_readbacks_.erase(tab_id);

  if (thumbnail_scale > 0 && !bitmap.empty())
    thumbnail_cache_->Put(tab_id, bitmap, thumbnail_scale);
}

bool RegisterTabContentManager(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

// ----------------------------------------------------------------------------
// Native JNI methods
// ----------------------------------------------------------------------------

jlong Init(JNIEnv* env,
           jobject obj,
           jstring disk_cache_path,
           jint default_cache_size,
           jint approximation_cache_size,
           jint compression_queue_max_size,
           jint write_queue_max_size,
           jboolean use_approximation_thumbnail) {
  TabContentManager* manager = new TabContentManager(
      env, obj, disk_cache_path, default_cache_size, approximation_cache_size,
      compression_queue_max_size, write_queue_max_size,
      use_approximation_thumbnail);
  return reinterpret_cast<intptr_t>(manager);
}

}  // namespace android
}  // namespace chrome
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "ClientSession.h"
#include "GameManager.h"
#include "Player.h"
#include "Unit.h"
#include "GameRoom.h"
#include "Game.h"
//#include "DatabaseJobContext.h"
//#include "DatabaseJobManager.h"

//@{ Handler Helper

typedef void(*HandlerFunc)(ClientSession* session);

static HandlerFunc HandlerTable[PKT_MAX];

static void DefaultHandler(ClientSession* session)
{
	printf("[DEBUG] Invalid packet handler \n", session->GetPlayerId());
	session->Disconnect();
}

struct InitializeHandlers
{
	InitializeHandlers()
	{
		for (int i = 0; i < PKT_MAX; ++i)
			HandlerTable[i] = DefaultHandler;
	}
} _init_handlers_;

struct RegisterHandler
{
	RegisterHandler(int pktType, HandlerFunc handler)
	{
		HandlerTable[pktType] = handler;
	}
};

#define REGISTER_HANDLER(PKT_TYPE)	\
	static void Handler_##PKT_TYPE(ClientSession* session); \
	static RegisterHandler _register_##PKT_TYPE(PKT_TYPE, Handler_##PKT_TYPE); \
	static void Handler_##PKT_TYPE(ClientSession* session)

//@}

///////////////////////////////////////////////////////////////////////////
/*
	 Ŭ̾Ʈ Ŷ ް  ۾ Ϸϴ ݹ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void CALLBACK RecvCompletion(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
	ClientSession* fromClient = static_cast<OverlappedIO*>(lpOverlapped)->mObject;

	fromClient->DecRefCount();

	if (!fromClient->IsConnected())
		return;

	///  ߻ ش
	if (dwError || cbTransferred == 0)
	{
		fromClient->Disconnect();
		return;
	}

	///   ó
	fromClient->OnRead(cbTransferred);

	/// ٽ ޱ
	if (false == fromClient->PostRecv())
	{
		fromClient->Disconnect();
		return;
	}
}
void CALLBACK SendCompletion(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
	ClientSession* fromClient = static_cast<OverlappedIO*>(lpOverlapped)->mObject;

	fromClient->DecRefCount();

	if (!fromClient->IsConnected())
		return;

	///  ߻ ش
	if (dwError || cbTransferred == 0)
	{
		fromClient->Disconnect();
		return;
	}

	fromClient->OnWriteComplete(cbTransferred);

}

///////////////////////////////////////////////////////////////////////////
/*
	 Ϸ Ŷ ¹ۿ ϴ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void ClientSession::OnWriteComplete(size_t len)
{
	mSendBuffer.Remove(len);
}

///////////////////////////////////////////////////////////////////////////
/*
	 Ŷ ĽϿ óϴ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void ClientSession::OnRead(size_t len)
{
	mRecvBuffer.Commit(len);

	/// Ŷ Ľϰ ó
	while (true)
	{
		/// Ŷ  ũ ŭ оͺ
		PacketHeader header;
		if (false == mRecvBuffer.Peek((char*)&header, sizeof(PacketHeader)))
			return;

		/// Ŷ ϼ Ǵ°?
		if (mRecvBuffer.GetStoredSize() < (size_t)header.mSize)
			return;

		if (header.mType >= PKT_MAX || header.mType <= PKT_NONE)
		{
			printf("[DEBUG] Invalid packet type \n", GetPlayerId());
			Disconnect();
			return;
		}

		/// packet dispatch...
		HandlerTable[header.mType](this);
	}
}

///////////////////////////////////////////////////////////////////////////
/*
	Ŷ ŸԿ  Ľ Ϸϰ ۾ óϴ ڵ鷯
	*/
///////////////////////////////////////////////////////////////////////////
REGISTER_HANDLER(PKT_CS_LOGIN)
{
	LoginRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	printf(" Request Login ID: %d \n", inPacket.mPlayerId);
	session->LoginSuccessInform(inPacket.mPlayerId);

	// 	LoadPlayerDataContext* newDbJob = new LoadPlayerDataContext(session->GetSocketKey(), inPacket.mPlayerId);
	// 	GDatabaseJobManager->PushDatabaseJobRequest(newDbJob);
}

REGISTER_HANDLER(PKT_CS_MAKE_ROOM)
{
	MakeRoomRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	session->MakeGameRoom(inPacket.mPlayerId);
}

REGISTER_HANDLER(PKT_CS_INOUT_ROOM)
{
	InOutRoomRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	if (session->GetPlayerId() != inPacket.mPlayerId)
	{
		printf("[DEBUG] Player Info error! \n");
		return;
	}

	if (inPacket.mIsIn)
		session->JoinGameRoom();
	else
		session->OutGameRoom();
}

REGISTER_HANDLER(PKT_CS_GAME_READY)
{
	GameReadyNotify inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	if (session->GetPlayerId() != inPacket.mPlayerId)
	{
		printf("[DEBUG] Player Info error! \n");
		return;
	}

	printf(" - Player %d is Ready ! \n", inPacket.mPlayerId);

	auto room = GGameManager->SearchRoom(session->GetRoomId());
	if (room != nullptr)
	{
		session->SetReady();
		room->ReadySign();

		if (room->IsAllReady())
		{
			session->AllReadyNotify();
		}
	}
	else
	{
		printf("[DEBUG] Room Info error! \n");
		return;
	}
}

//
//
// REGISTER_HANDLER(PKT_CS_CREATE_HERO)
// {
// 	CreateHeroRequest inPacket;
// 	if (false == session->ParsePacket(inPacket))
// 	{
// 		printf("[DEBUG] packet parsing error: %d", inPacket.mType);
// 		return;
// 	}
//
// 	printf("\n haveID: %d \n recvID: %d \n", session->GetPlayerId(), inPacket.mPlayerId);
//
// 	if (inPacket.mPlayerId != session->GetPlayerId())
// 	{
// 		printf("[DEBUG] PKT_CS_CREATE_HERO: invalid player ID", session->GetPlayerId());
// 		return;
// 	}
//
// 	CreateHeroResult outPacket;
// 	outPacket.mPlayerId = inPacket.mPlayerId;
// 	outPacket.mUnitId = inPacket.mUnitId;
// 	outPacket.mPosX = inPacket.mPosX;
// 	outPacket.mPosY = inPacket.mPosY;
//
// 	if (!session->Broadcast(&outPacket))
// 	{
// 		session->Disconnect();
// 	}
// }
//
//

REGISTER_HANDLER(PKT_CS_CHAT)
{
	ChatBroadcastRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}

	if (inPacket.mPlayerId != session->GetPlayerId())
	{
		printf("[DEBUG] PKT_CS_CHAT: invalid player ID: %d \n", session->GetPlayerId());
		return;
	}

	/// chatting  ⼭ ٷ

	ChatBroadcastResult outPacket;
	outPacket.mPlayerId = inPacket.mPlayerId;
	strcpy_s(outPacket.mName, session->GetPlayerName());
	strcpy_s(outPacket.mChat, inPacket.mChat);

	/// ä ٷ  ϸ
	if (!session->Broadcast(&outPacket))
	{
		session->Disconnect();
	}
}

REGISTER_HANDLER(PKT_CS_MOVE)
{
	MoveRequest inPacket;
	b2Vec2 targetPos;
	b2Vec2 currentPos;

	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}

	if (inPacket.mPlayerId != session->GetPlayerId())
	{
		printf("[DEBUG] PKT_CS_MOVE: invalid player ID: %d \n", session->GetPlayerId());
		return;
	}

	targetPos.x = inPacket.mTargetPosX;
	targetPos.y = inPacket.mTargetPosY;
	currentPos.x = inPacket.mCurrentPosX;
	currentPos.y = inPacket.mCurrentPosY;

	GGameManager->UnitMove(targetPos, currentPos, session->GetPlayerId());

	printf(" Send:   Login ID: %d, x: %3f, y: %3f \n", session->GetPlayerId(), inPacket.mTargetPosX, inPacket.mTargetPosY);

	auto unit = GGameManager->SearchGame(session->GetPlayerId())->GetPlayer(session->GetPlayerId())->GetMyHero();

	session->SendUnitInfo(unit->GetUnitID(), unit->GetUnitType(), unit->GetCurrentPos(), unit->GetTargetPos());

	unit->TryMove();
}

REGISTER_HANDLER(PKT_CS_RUN_COMPLETE)
{
	ClientRunCompleteNotify inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}

	if (inPacket.mPlayerId != session->GetPlayerId())
	{
		printf("[DEBUG] PKT_CS_CHAT: invalid player ID: %d \n", session->GetPlayerId());
		return;
	}

	GGameManager->SearchGame(session->GetPlayerId())->SetLoadedPlayerNum();
}

///////////////////////////////////////////////////////////////////////////
/*
	 Ŷ Ľϴ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void ClientSession::LoginSuccessInform(int id)
{
	LoginResult outPacket;

	outPacket.mPlayerId = mPlayerId = id;

	// ⼭ ϴ ID г µ,
	// ߿ DB ̿ ID г ؾ ҵ. -
	itoa(mPlayerId, mPlayerName, 10);
	strcpy_s(outPacket.mName, mPlayerName);

	SendRequest(&outPacket);

	mLogon = true;

	printf(" Send:   Login ID: %d \n", outPacket.mPlayerId);
}

void ClientSession::MakeGameRoom(int id)
{
	GameRoom* gameRoom = GGameManager->CreateRoom();
	GGameManager->JoinRoom(id, gameRoom->GetRoomID());

	MakeRoomResult outPacket;

	outPacket.mPlayerId = mPlayerId = id;
	outPacket.mRoomId = mRoomId = gameRoom->GetRoomID();

	SendRequest(&outPacket);

	printf(" Send: Make Room ID: %d, Player ID: %d \n", outPacket.mRoomId, outPacket.mPlayerId);
}

void ClientSession::JoinGameRoom()
{
	auto roomNum = GGameManager->SearchEmptyRoom();

	if (roomNum == -1)
		return;

	GGameManager->JoinRoom(mPlayerId, roomNum);

	InOutRoomResult outPacket;

	outPacket.mPlayerId = mPlayerId;
	outPacket.mRoomId = mRoomId = roomNum;

	SendRequest(&outPacket);

	printf(" Send: Join Room ID: %d, Player ID: %d \n", outPacket.mRoomId, outPacket.mPlayerId);
}

void ClientSession::OutGameRoom()
{
	if (mRoomId == -1 || mPlayerId == -1)
		return;

	GGameManager->OutRoom(mPlayerId, mRoomId);

	printf(" Send:  Out Room ID: %d, Player ID: %d \n", mRoomId, mPlayerId);
	mRoomId = -1;
	mIsReady = false;
}

void ClientSession::OutGame()
{
	if (mRoomId == -1 || mPlayerId == -1)
		return;

	GGameManager->OutRoom(mPlayerId, mRoomId);

	printf(" Send:  Out Room ID: %d, Player ID: %d \n", mRoomId, mPlayerId);
	mRoomId = -1;
	mIsReady = false;
}

void ClientSession::ServerRunComplete()
{
	ServerRunCompleteNotify outPacket;

	outPacket.mPlayerId = mPlayerId;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}

	printf(" Send: ServerRunCompleteNotify ");
}

void ClientSession::AllReadyNotify()
{
	GameRunNotify outPacket;

	outPacket.mPlayerId = mPlayerId;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}

	printf(" Send: GameRunNotify Room ID: %d \n", mRoomId);
}

void ClientSession::StartGame()
{
	StartGameNotify outPacket;

	outPacket.mPlayerId = mPlayerId;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}

	printf(" Send: StartGameNotify Room ID: %d \n", mRoomId);
}

void ClientSession::SendCreateHeroResult(int unitId, UnitType unitType, b2Vec2 pos)
{
	CreateHeroResult outPacket;

	outPacket.mPlayerId = mPlayerId;
	outPacket.mUnitId = unitId;
	outPacket.mUnitType = unitType;
	outPacket.mPosX = pos.x;
	outPacket.mPosY = pos.y;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}
}

void ClientSession::SendUnitInfo(int unitId, UnitType unitType, b2Vec2 currentPos, b2Vec2 targetPos)
{
	MoveBroadcastResult outPacket;

	outPacket.mPlayerId = mPlayerId;
	outPacket.mUnitId = unitId;
	outPacket.mUnitType = unitType;
	outPacket.mCurrentPosX = currentPos.x;
	outPacket.mCurrentPosY = currentPos.y;
	outPacket.mTargetPosX = targetPos.x;
	outPacket.mTargetPosY = targetPos.y;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}
}
<commit_msg>[S]공백 커밋<commit_after>#include "stdafx.h"
#include "ClientSession.h"
#include "GameManager.h"
#include "Player.h"
#include "Unit.h"
#include "GameRoom.h"
#include "Game.h"
//#include "DatabaseJobContext.h"
//#include "DatabaseJobManager.h"

//@{ Handler Helper

typedef void(*HandlerFunc)(ClientSession* session);

static HandlerFunc HandlerTable[PKT_MAX];

static void DefaultHandler(ClientSession* session)
{
	printf("[DEBUG] Invalid packet handler \n", session->GetPlayerId());
	session->Disconnect();
}

struct InitializeHandlers
{
	InitializeHandlers()
	{
		for (int i = 0; i < PKT_MAX; ++i)
			HandlerTable[i] = DefaultHandler;
	}
} _init_handlers_;

struct RegisterHandler
{
	RegisterHandler(int pktType, HandlerFunc handler)
	{
		HandlerTable[pktType] = handler;
	}
};

#define REGISTER_HANDLER(PKT_TYPE)	\
	static void Handler_##PKT_TYPE(ClientSession* session); \
	static RegisterHandler _register_##PKT_TYPE(PKT_TYPE, Handler_##PKT_TYPE); \
	static void Handler_##PKT_TYPE(ClientSession* session)

//@}

///////////////////////////////////////////////////////////////////////////
/*
	 Ŭ̾Ʈ Ŷ ް  ۾ Ϸϴ ݹ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void CALLBACK RecvCompletion(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
	ClientSession* fromClient = static_cast<OverlappedIO*>(lpOverlapped)->mObject;

	fromClient->DecRefCount();

	if (!fromClient->IsConnected())
		return;

	///  ߻ ش
	if (dwError || cbTransferred == 0)
	{
		fromClient->Disconnect();
		return;
	}

	///   ó
	fromClient->OnRead(cbTransferred);

	/// ٽ ޱ
	if (false == fromClient->PostRecv())
	{
		fromClient->Disconnect();
		return;
	}
}
void CALLBACK SendCompletion(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
	ClientSession* fromClient = static_cast<OverlappedIO*>(lpOverlapped)->mObject;

	fromClient->DecRefCount();

	if (!fromClient->IsConnected())
		return;

	///  ߻ ش
	if (dwError || cbTransferred == 0)
	{
		fromClient->Disconnect();
		return;
	}

	fromClient->OnWriteComplete(cbTransferred);

}

///////////////////////////////////////////////////////////////////////////
/*
	 Ϸ Ŷ ¹ۿ ϴ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void ClientSession::OnWriteComplete(size_t len)
{
	mSendBuffer.Remove(len);
}

///////////////////////////////////////////////////////////////////////////
/*
	 Ŷ ĽϿ óϴ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void ClientSession::OnRead(size_t len)
{
	mRecvBuffer.Commit(len);

	/// Ŷ Ľϰ ó
	while (true)
	{
		/// Ŷ  ũ ŭ оͺ
		PacketHeader header;
		if (false == mRecvBuffer.Peek((char*)&header, sizeof(PacketHeader)))
			return;

		/// Ŷ ϼ Ǵ°?
		if (mRecvBuffer.GetStoredSize() < (size_t)header.mSize)
			return;

		if (header.mType >= PKT_MAX || header.mType <= PKT_NONE)
		{
			printf("[DEBUG] Invalid packet type \n", GetPlayerId());
			Disconnect();
			return;
		}

		/// packet dispatch...
		HandlerTable[header.mType](this);
	}
}

///////////////////////////////////////////////////////////////////////////
/*
	Ŷ ŸԿ  Ľ Ϸϰ ۾ óϴ ڵ鷯
	*/
///////////////////////////////////////////////////////////////////////////
REGISTER_HANDLER(PKT_CS_LOGIN)
{
	LoginRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	printf(" Request Login ID: %d \n", inPacket.mPlayerId);
	session->LoginSuccessInform(inPacket.mPlayerId);

	// 	LoadPlayerDataContext* newDbJob = new LoadPlayerDataContext(session->GetSocketKey(), inPacket.mPlayerId);
	// 	GDatabaseJobManager->PushDatabaseJobRequest(newDbJob);
}

REGISTER_HANDLER(PKT_CS_MAKE_ROOM)
{
	MakeRoomRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	session->MakeGameRoom(inPacket.mPlayerId);
}

REGISTER_HANDLER(PKT_CS_INOUT_ROOM)
{
	InOutRoomRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	if (session->GetPlayerId() != inPacket.mPlayerId)
	{
		printf("[DEBUG] Player Info error! \n");
		return;
	}

	if (inPacket.mIsIn)
		session->JoinGameRoom();
	else
		session->OutGameRoom();
}

REGISTER_HANDLER(PKT_CS_GAME_READY)
{
	GameReadyNotify inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}
	if (session->GetPlayerId() != inPacket.mPlayerId)
	{
		printf("[DEBUG] Player Info error! \n");
		return;
	}

	printf(" - Player %d is Ready ! \n", inPacket.mPlayerId);

	auto room = GGameManager->SearchRoom(session->GetRoomId());
	if (room != nullptr)
	{
		session->SetReady();
		room->ReadySign();

		if (room->IsAllReady())
		{
			session->AllReadyNotify();
		}
	}
	else
	{
		printf("[DEBUG] Room Info error! \n");
		return;
	}
}

//
//
// REGISTER_HANDLER(PKT_CS_CREATE_HERO)
// {
// 	CreateHeroRequest inPacket;
// 	if (false == session->ParsePacket(inPacket))
// 	{
// 		printf("[DEBUG] packet parsing error: %d", inPacket.mType);
// 		return;
// 	}
//
// 	printf("\n haveID: %d \n recvID: %d \n", session->GetPlayerId(), inPacket.mPlayerId);
//
// 	if (inPacket.mPlayerId != session->GetPlayerId())
// 	{
// 		printf("[DEBUG] PKT_CS_CREATE_HERO: invalid player ID", session->GetPlayerId());
// 		return;
// 	}
//
// 	CreateHeroResult outPacket;
// 	outPacket.mPlayerId = inPacket.mPlayerId;
// 	outPacket.mUnitId = inPacket.mUnitId;
// 	outPacket.mPosX = inPacket.mPosX;
// 	outPacket.mPosY = inPacket.mPosY;
//
// 	if (!session->Broadcast(&outPacket))
// 	{
// 		session->Disconnect();
// 	}
// }
//
//

REGISTER_HANDLER(PKT_CS_CHAT)
{
	ChatBroadcastRequest inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}

	if (inPacket.mPlayerId != session->GetPlayerId())
	{
		printf("[DEBUG] PKT_CS_CHAT: invalid player ID: %d \n", session->GetPlayerId());
		return;
	}

	/// chatting  ⼭ ٷ

	ChatBroadcastResult outPacket;
	outPacket.mPlayerId = inPacket.mPlayerId;
	strcpy_s(outPacket.mName, session->GetPlayerName());
	strcpy_s(outPacket.mChat, inPacket.mChat);

	/// ä ٷ  ϸ
	if (!session->Broadcast(&outPacket))
	{
		session->Disconnect();
	}
}

REGISTER_HANDLER(PKT_CS_MOVE)
{
	MoveRequest inPacket;
	b2Vec2 targetPos;
	b2Vec2 currentPos;

	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}

	if (inPacket.mPlayerId != session->GetPlayerId())
	{
		printf("[DEBUG] PKT_CS_MOVE: invalid player ID: %d \n", session->GetPlayerId());
		return;
	}

	targetPos.x = inPacket.mTargetPosX;
	targetPos.y = inPacket.mTargetPosY;
	currentPos.x = inPacket.mCurrentPosX;
	currentPos.y = inPacket.mCurrentPosY;

	GGameManager->UnitMove(targetPos, currentPos, session->GetPlayerId());

	printf(" Send:   Login ID: %d, x: %3f, y: %3f \n", session->GetPlayerId(), inPacket.mTargetPosX, inPacket.mTargetPosY);

	auto unit = GGameManager->SearchGame(session->GetPlayerId())->GetPlayer(session->GetPlayerId())->GetMyHero();

	session->SendUnitInfo(unit->GetUnitID(), unit->GetUnitType(), unit->GetCurrentPos(), unit->GetTargetPos());

	unit->TryMove(session->GetPlayerId());
}

REGISTER_HANDLER(PKT_CS_RUN_COMPLETE)
{
	ClientRunCompleteNotify inPacket;
	if (false == session->ParsePacket(inPacket))
	{
		printf("[DEBUG] packet parsing error: %d \n", inPacket.mType);
		return;
	}

	if (inPacket.mPlayerId != session->GetPlayerId())
	{
		printf("[DEBUG] PKT_CS_CHAT: invalid player ID: %d \n", session->GetPlayerId());
		return;
	}

	GGameManager->SearchGame(session->GetPlayerId())->SetLoadedPlayerNum();
}

///////////////////////////////////////////////////////////////////////////
/*
	 Ŷ Ľϴ Լ
	*/
///////////////////////////////////////////////////////////////////////////
void ClientSession::LoginSuccessInform(int id)
{
	LoginResult outPacket;

	outPacket.mPlayerId = mPlayerId = id;

	// ⼭ ϴ ID г µ,
	// ߿ DB ̿ ID г ؾ ҵ. -
	itoa(mPlayerId, mPlayerName, 10);
	strcpy_s(outPacket.mName, mPlayerName);

	SendRequest(&outPacket);

	mLogon = true;

	printf(" Send:   Login ID: %d \n", outPacket.mPlayerId);
}

void ClientSession::MakeGameRoom(int id)
{
	GameRoom* gameRoom = GGameManager->CreateRoom();
	GGameManager->JoinRoom(id, gameRoom->GetRoomID());

	MakeRoomResult outPacket;

	outPacket.mPlayerId = mPlayerId = id;
	outPacket.mRoomId = mRoomId = gameRoom->GetRoomID();

	SendRequest(&outPacket);

	printf(" Send: Make Room ID: %d, Player ID: %d \n", outPacket.mRoomId, outPacket.mPlayerId);
}

void ClientSession::JoinGameRoom()
{
	auto roomNum = GGameManager->SearchEmptyRoom();

	if (roomNum == -1)
		return;

	GGameManager->JoinRoom(mPlayerId, roomNum);

	InOutRoomResult outPacket;

	outPacket.mPlayerId = mPlayerId;
	outPacket.mRoomId = mRoomId = roomNum;

	SendRequest(&outPacket);

	printf(" Send: Join Room ID: %d, Player ID: %d \n", outPacket.mRoomId, outPacket.mPlayerId);
}

void ClientSession::OutGameRoom()
{
	if (mRoomId == -1 || mPlayerId == -1)
		return;

	GGameManager->OutRoom(mPlayerId, mRoomId);

	printf(" Send:  Out Room ID: %d, Player ID: %d \n", mRoomId, mPlayerId);
	mRoomId = -1;
	mIsReady = false;
}

void ClientSession::OutGame()
{
	if (mRoomId == -1 || mPlayerId == -1)
		return;

	GGameManager->OutRoom(mPlayerId, mRoomId);

	printf(" Send:  Out Room ID: %d, Player ID: %d \n", mRoomId, mPlayerId);
	mRoomId = -1;
	mIsReady = false;
}

void ClientSession::ServerRunComplete()
{
	ServerRunCompleteNotify outPacket;

	outPacket.mPlayerId = mPlayerId;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}

	printf(" Send: ServerRunCompleteNotify ");
}

void ClientSession::AllReadyNotify()
{
	GameRunNotify outPacket;

	outPacket.mPlayerId = mPlayerId;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}

	printf(" Send: GameRunNotify Room ID: %d \n", mRoomId);
}

void ClientSession::StartGame()
{
	StartGameNotify outPacket;

	outPacket.mPlayerId = mPlayerId;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}

	printf(" Send: StartGameNotify Room ID: %d \n", mRoomId);
}

void ClientSession::SendCreateHeroResult(int unitId, UnitType unitType, b2Vec2 pos)
{
	CreateHeroResult outPacket;

	outPacket.mPlayerId = mPlayerId;
	outPacket.mUnitId = unitId;
	outPacket.mUnitType = unitType;
	outPacket.mPosX = pos.x;
	outPacket.mPosY = pos.y;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}
}

void ClientSession::SendUnitInfo(int unitId, UnitType unitType, b2Vec2 currentPos, b2Vec2 targetPos)
{
	MoveBroadcastResult outPacket;

	outPacket.mPlayerId = mPlayerId;
	outPacket.mUnitId = unitId;
	outPacket.mUnitType = unitType;
	outPacket.mCurrentPosX = currentPos.x;
	outPacket.mCurrentPosY = currentPos.y;
	outPacket.mTargetPosX = targetPos.x;
	outPacket.mTargetPosY = targetPos.y;

	if (!Broadcast(&outPacket))
	{
		Disconnect();
	}
}
<|endoftext|>