<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

/* Note: this code needs to have error handling overhauled */

#define _POSIX_SOURCE

#include "condor_common.h"
#include "condor_constants.h"
#include "condor_io.h"
#include "condor_debug.h"
#include "internet.h"

SafeSock::SafeSock(					/* bind on port		*/
	int		port
	)
	: Sock()
{
	bind(port);
}

SafeSock::SafeSock(					/* bind on serv		*/
	char	*serv
	)
	: Sock()
{
	bind(serv);
}

SafeSock::SafeSock(
	char	*host,
	int		port,
	int		timeout_val
	)
	: Sock()
{
	timeout(timeout_val);
	connect(host, port);
}

SafeSock::SafeSock(
	char	*host,
	char	*serv,
	int		timeout_val
	)
	: Sock()
{
	timeout(timeout_val);
	connect(host, serv);
}

SafeSock::~SafeSock()
{
	close();
}

int SafeSock::handle_incoming_packet()
{
	/* do not queue up more than one message at a time on safe sockets */
	/* but return 1, because old message can still be read.	           */
	if (rcv_msg.ready) return TRUE;

	if (!rcv_packet(_sock)) return FALSE;

	return TRUE;
}

int SafeSock::end_of_message()
{
	int ret_val = FALSE;

	switch(_coding){
		case stream_encode:
			if (!snd_msg.buf.empty()){
				return snd_packet(_sock);
			}
			break;

		case stream_decode:
			if ( rcv_msg.ready ) {
				if ( rcv_msg.buf.consumed() )
					ret_val = TRUE;
				rcv_msg.ready = FALSE;
				rcv_msg.buf.reset();
			}
			break;

		default:
			assert(0);
	}

	return ret_val;
}

int SafeSock::connect(
	char	*host,
	int		port
	)
{
	struct hostent	*hostp = NULL;
	unsigned long	inaddr = 0;

	if (!valid()) return FALSE;
	if (!host || port < 0) return FALSE;

		/* we bind here so that a sock may be	*/
		/* assigned to the stream if needed		*/
	if (_state == sock_virgin || _state == sock_assigned) bind();

	if (_state != sock_bound) return FALSE;

	memset(&_who, 0, sizeof(sockaddr_in));
	_who.sin_family = AF_INET;
	_who.sin_port = htons((u_short)port);

	/* might be in <x.x.x.x:x> notation, i.e. sinfull string */
	if (host[0] == '<') {
		string_to_sin(host, &_who);
	}
	/* try to get a decimal notation first 			*/
	else if( (inaddr=inet_addr(host)) != (unsigned int)(-1) ) {
		memcpy((char *)&_who.sin_addr, &inaddr, sizeof(inaddr));
	} else {
		/* if dotted notation fails, try host database	*/
		hostp = gethostbyname(host);
		if( hostp == (struct hostent *)0 ) {
			return FALSE;
		} else {
			memcpy(&_who.sin_addr, hostp->h_addr, sizeof(hostp->h_addr));
		}
	}

	_state = sock_connect;
	return TRUE;
}

int SafeSock::put_bytes(
	const void	*dta,
	int			sz
	)
{
	int		tw;
	int		nw;

	if (!valid()) return -1;

	for(nw=0;;){

		if (snd_msg.buf.full()){
			return FALSE;
		}

/*
		if (snd_msg.buf.empty()){
			snd_msg.buf.seek(5);
		}
*/

		if ((tw = snd_msg.buf.put_max(&((char *)dta)[nw], sz-nw)) < 0)
			return -1;
		nw += tw;
		if (nw == sz) break;
	}

	return nw;
}

int SafeSock::get_bytes(
	void		*dta,
	int			max_sz
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()){
			return FALSE;
		}
	}

	return rcv_msg.buf.get_max(dta, max_sz);
}

int SafeSock::get_ptr(
	void		*&ptr,
	char		delim
	)
{
	int nr;
	int tr;

	if (!valid()) return -1;

	while (!rcv_msg.ready){
		if (!handle_incoming_packet()) return FALSE;
	}

	if ((tr = rcv_msg.buf.find(delim)) < 0) {
		return -1;
	}
	ptr = rcv_msg.buf.get_ptr();
	nr = rcv_msg.buf.seek(0);
	rcv_msg.buf.seek(nr+tr+1);
	return tr+1;
}

int SafeSock::peek(
	char		&c
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()) return FALSE;
	}

	return rcv_msg.buf.peek(c);
}

int SafeSock::rcv_packet(
	SOCKET _sock
	)
{
	char	tmp[65536];
	int		len, fromlen;

	fromlen = sizeof(struct sockaddr_in);

	if (_timeout > 0) {
		struct timeval	timer;
		fd_set			readfds;
		int				nfds=0, nfound;
		timer.tv_sec = _timeout;
		timer.tv_usec = 0;
#if !defined(WIN32) // nfds is ignored on WIN32
		nfds = _sock + 1;
#endif
		FD_ZERO( &readfds );
		FD_SET( _sock, &readfds );

		nfound = select( nfds, &readfds, 0, 0, &timer );

		switch(nfound) {
		case 0:
			return FALSE;
			break;
		case 1:
			break;
		default:
			dprintf( D_ALWAYS, "select returns %d, recv failed\n",
				nfound );
			return FALSE;
			break;
		}
	}

	if ((len = recvfrom(_sock, tmp, 65536, 0,
						(struct sockaddr *)&_who,&fromlen)) < 0) {
		return FALSE;
	}
	dprintf( D_NETWORK, "RECV %s ", sock_to_string(_sock) );
	dprintf( D_NETWORK|D_NOHEADER, "%s\n", sin_to_string(&_who) );
	if (!rcv_msg.buf.put_max(tmp, len)) {
		dprintf(D_ALWAYS, "IO: Packet storing failed\n");
		return FALSE;
	}

	rcv_msg.ready = TRUE;

	return TRUE;
}

int SafeSock::snd_packet(
	int		_sock
	)
{
	int		ns;

	ns = snd_msg.buf.num_used();

	if (sendto(_sock, (const char *)snd_msg.buf.get_ptr(),
			   snd_msg.buf.num_used(), 0,
			   (const struct sockaddr *)&_who,
			   sizeof(struct sockaddr_in)) < 0) {
		return FALSE;
	}
	dprintf( D_NETWORK, "SEND %s ", sock_to_string(_sock) );
	dprintf( D_NETWORK|D_NOHEADER, "%s\n", sin_to_string(&_who) );
	snd_msg.buf.reset();

	return TRUE;
}

int SafeSock::get_port()
{
	sockaddr_in	addr;
	int			addr_len;

	addr_len = sizeof(sockaddr_in);

	if (getsockname(_sock, (sockaddr *)&addr, &addr_len) < 0) return -1;

	return (int) ntohs(addr.sin_port);
}

int SafeSock::get_file_desc()
{
	return _sock;
}

#ifndef WIN32
	// interface no longer supported
int SafeSock::attach_to_file_desc(
	int		fd
	)
{
	if (_state != sock_virgin) return FALSE;

	_sock = fd;
	_state = sock_connect;
	return TRUE;
}
#endif

struct sockaddr_in *SafeSock::endpoint()
{
	return &_who;
}

char *SafeSock::endpoint_IP()
{
	int             i;
	static  char    buf[24];
	char    tmp_buf[10];
	char    *cur_byte;
	unsigned char   this_byte;

	buf[0] = '\0';
	cur_byte = (char *) &(_who.sin_addr);
	for (i = 0; i < sizeof(_who.sin_addr); i++) {
		this_byte = (unsigned char) *cur_byte;
		sprintf(tmp_buf, "%u.", this_byte);
		cur_byte++;
		strcat(buf, tmp_buf);
	}
	buf[strlen(buf) - 1] = '\0';
	return buf;
}

int SafeSock::endpoint_port()
{
	return (int) ntohs(_who.sin_port);
}

char * SafeSock::serialize(char *buf)
{
	char sinful_string[28];
	char *ptmp;

	if ( buf == NULL ) {
		// here we want to save our state into a buffer

		// first, get the state from our parent class
		char * parent_state = Sock::do_serialize();
		// now concatenate our state
		char * outbuf = new char[50];
		sprintf(outbuf,"*%d*%s",_special_state,sin_to_string(&_who));
		strcat(parent_state,outbuf);
		delete []outbuf;
		return( parent_state );
	}

	// here we want to restore our state from the incoming buffer

	// first, let our parent class restore its state
	ptmp = Sock::do_serialize(buf);
	assert( ptmp );
	sscanf(ptmp,"%d*%s",&_special_state,sinful_string);
	string_to_sin(sinful_string, &_who);

	return NULL;
}
<commit_msg>Added the init() method which all constructors call.  Also, in init(), we initialize the _special_state member to "safesock_none".<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

/* Note: this code needs to have error handling overhauled */

#include "condor_common.h"
#include "condor_constants.h"
#include "condor_io.h"
#include "condor_debug.h"
#include "internet.h"

/*
   NOTE: All SafeSock constructors initialize with this, so you can
   put any shared initialization code here.  -Derek Wright 3/12/99
*/
void
SafeSock::init()
{
	_special_state = safesock_none;
}

SafeSock::SafeSock() 				/* virgin safesock	*/
	: Sock()
{
	init();
}

SafeSock::SafeSock(					/* bind on port		*/
	int		port
	)
	: Sock()
{
	init();
	bind(port);
}

SafeSock::SafeSock(					/* bind on serv		*/
	char	*serv
	)
	: Sock()
{
	init();
	bind(serv);
}

SafeSock::SafeSock(
	char	*host,
	int		port,
	int		timeout_val
	)
	: Sock()
{
	init();
	timeout(timeout_val);
	connect(host, port);
}

SafeSock::SafeSock(
	char	*host,
	char	*serv,
	int		timeout_val
	)
	: Sock()
{
	init();
	timeout(timeout_val);
	connect(host, serv);
}

SafeSock::~SafeSock()
{
	close();
}

int SafeSock::handle_incoming_packet()
{
	/* do not queue up more than one message at a time on safe sockets */
	/* but return 1, because old message can still be read.	           */
	if (rcv_msg.ready) return TRUE;

	if (!rcv_packet(_sock)) return FALSE;

	return TRUE;
}

int SafeSock::end_of_message()
{
	int ret_val = FALSE;

	switch(_coding){
		case stream_encode:
			if (!snd_msg.buf.empty()){
				return snd_packet(_sock);
			}
			break;

		case stream_decode:
			if ( rcv_msg.ready ) {
				if ( rcv_msg.buf.consumed() )
					ret_val = TRUE;
				rcv_msg.ready = FALSE;
				rcv_msg.buf.reset();
			}
			break;

		default:
			assert(0);
	}

	return ret_val;
}

int SafeSock::connect(
	char	*host,
	int		port
	)
{
	struct hostent	*hostp = NULL;
	unsigned long	inaddr = 0;

	if (!valid()) return FALSE;
	if (!host || port < 0) return FALSE;

		/* we bind here so that a sock may be	*/
		/* assigned to the stream if needed		*/
	if (_state == sock_virgin || _state == sock_assigned) bind();

	if (_state != sock_bound) return FALSE;

	memset(&_who, 0, sizeof(sockaddr_in));
	_who.sin_family = AF_INET;
	_who.sin_port = htons((u_short)port);

	/* might be in <x.x.x.x:x> notation, i.e. sinfull string */
	if (host[0] == '<') {
		string_to_sin(host, &_who);
	}
	/* try to get a decimal notation first 			*/
	else if( (inaddr=inet_addr(host)) != (unsigned int)(-1) ) {
		memcpy((char *)&_who.sin_addr, &inaddr, sizeof(inaddr));
	} else {
		/* if dotted notation fails, try host database	*/
		hostp = gethostbyname(host);
		if( hostp == (struct hostent *)0 ) {
			return FALSE;
		} else {
			memcpy(&_who.sin_addr, hostp->h_addr, sizeof(hostp->h_addr));
		}
	}

	_state = sock_connect;
	return TRUE;
}

int SafeSock::put_bytes(
	const void	*dta,
	int			sz
	)
{
	int		tw;
	int		nw;

	if (!valid()) return -1;

	for(nw=0;;){

		if (snd_msg.buf.full()){
			return FALSE;
		}

/*
		if (snd_msg.buf.empty()){
			snd_msg.buf.seek(5);
		}
*/

		if ((tw = snd_msg.buf.put_max(&((char *)dta)[nw], sz-nw)) < 0)
			return -1;
		nw += tw;
		if (nw == sz) break;
	}

	return nw;
}

int SafeSock::get_bytes(
	void		*dta,
	int			max_sz
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()){
			return FALSE;
		}
	}

	return rcv_msg.buf.get_max(dta, max_sz);
}

int SafeSock::get_ptr(
	void		*&ptr,
	char		delim
	)
{
	int nr;
	int tr;

	if (!valid()) return -1;

	while (!rcv_msg.ready){
		if (!handle_incoming_packet()) return FALSE;
	}

	if ((tr = rcv_msg.buf.find(delim)) < 0) {
		return -1;
	}
	ptr = rcv_msg.buf.get_ptr();
	nr = rcv_msg.buf.seek(0);
	rcv_msg.buf.seek(nr+tr+1);
	return tr+1;
}

int SafeSock::peek(
	char		&c
	)
{
	if (!valid()) return -1;

	while (!rcv_msg.ready) {
		if (!handle_incoming_packet()) return FALSE;
	}

	return rcv_msg.buf.peek(c);
}

int SafeSock::rcv_packet(
	SOCKET _sock
	)
{
	char	tmp[65536];
	int		len, fromlen;

	fromlen = sizeof(struct sockaddr_in);

	if (_timeout > 0) {
		struct timeval	timer;
		fd_set			readfds;
		int				nfds=0, nfound;
		timer.tv_sec = _timeout;
		timer.tv_usec = 0;
#if !defined(WIN32) // nfds is ignored on WIN32
		nfds = _sock + 1;
#endif
		FD_ZERO( &readfds );
		FD_SET( _sock, &readfds );

		nfound = select( nfds, &readfds, 0, 0, &timer );

		switch(nfound) {
		case 0:
			return FALSE;
			break;
		case 1:
			break;
		default:
			dprintf( D_ALWAYS, "select returns %d, recv failed\n",
				nfound );
			return FALSE;
			break;
		}
	}

	if ((len = recvfrom(_sock, tmp, 65536, 0,
						(struct sockaddr *)&_who,&fromlen)) < 0) {
		return FALSE;
	}
	dprintf( D_NETWORK, "RECV %s ", sock_to_string(_sock) );
	dprintf( D_NETWORK|D_NOHEADER, "%s\n", sin_to_string(&_who) );
	if (!rcv_msg.buf.put_max(tmp, len)) {
		dprintf(D_ALWAYS, "IO: Packet storing failed\n");
		return FALSE;
	}

	rcv_msg.ready = TRUE;

	return TRUE;
}

int SafeSock::snd_packet(
	int		_sock
	)
{
	int		ns;

	ns = snd_msg.buf.num_used();

	if (sendto(_sock, (const char *)snd_msg.buf.get_ptr(),
			   snd_msg.buf.num_used(), 0,
			   (const struct sockaddr *)&_who,
			   sizeof(struct sockaddr_in)) < 0) {
		return FALSE;
	}
	dprintf( D_NETWORK, "SEND %s ", sock_to_string(_sock) );
	dprintf( D_NETWORK|D_NOHEADER, "%s\n", sin_to_string(&_who) );
	snd_msg.buf.reset();

	return TRUE;
}

int SafeSock::get_port()
{
	sockaddr_in	addr;
	int			addr_len;

	addr_len = sizeof(sockaddr_in);

	if (getsockname(_sock, (sockaddr *)&addr, &addr_len) < 0) return -1;

	return (int) ntohs(addr.sin_port);
}

int SafeSock::get_file_desc()
{
	return _sock;
}

#ifndef WIN32
	// interface no longer supported
int SafeSock::attach_to_file_desc(
	int		fd
	)
{
	if (_state != sock_virgin) return FALSE;

	_sock = fd;
	_state = sock_connect;
	return TRUE;
}
#endif

struct sockaddr_in *SafeSock::endpoint()
{
	return &_who;
}

char *SafeSock::endpoint_IP()
{
	int             i;
	static  char    buf[24];
	char    tmp_buf[10];
	char    *cur_byte;
	unsigned char   this_byte;

	buf[0] = '\0';
	cur_byte = (char *) &(_who.sin_addr);
	for (i = 0; i < sizeof(_who.sin_addr); i++) {
		this_byte = (unsigned char) *cur_byte;
		sprintf(tmp_buf, "%u.", this_byte);
		cur_byte++;
		strcat(buf, tmp_buf);
	}
	buf[strlen(buf) - 1] = '\0';
	return buf;
}

int SafeSock::endpoint_port()
{
	return (int) ntohs(_who.sin_port);
}

char * SafeSock::serialize(char *buf)
{
	char sinful_string[28];
	char *ptmp;

	if ( buf == NULL ) {
		// here we want to save our state into a buffer

		// first, get the state from our parent class
		char * parent_state = Sock::do_serialize();
		// now concatenate our state
		char * outbuf = new char[50];
		sprintf(outbuf,"*%d*%s",_special_state,sin_to_string(&_who));
		strcat(parent_state,outbuf);
		delete []outbuf;
		return( parent_state );
	}

	// here we want to restore our state from the incoming buffer

	// first, let our parent class restore its state
	ptmp = Sock::do_serialize(buf);
	assert( ptmp );
	sscanf(ptmp,"%d*%s",&_special_state,sinful_string);
	string_to_sin(sinful_string, &_who);

	return NULL;
}
<|endoftext|>


<commit_before>
#include <iostream>
#include <cstdlib>
#include <signal.h>

using std::cout;
using std::endl;

void my_handler(int signo) {
  cout << "NOPE!!" << endl;
} // my_handler

int main() {
  // TODO setup signal handler for SIGINT (Interrupt Signal)
  while (true);
  return EXIT_SUCCESS;
} // main

<commit_msg>prep for signal demo<commit_after>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <signal.h>

using std::cout;
using std::endl;

int main() {
  // TODO setup signal handler for SIGINT (Interrupt Signal)
  while (true) pause(); // wait for signal
  return EXIT_SUCCESS;
} // main

<|endoftext|>


<commit_before>#include "kwm.h"

const std::string KwmCurrentVersion = "Kwm Version 1.0.7";
const std::string PlistFile = "com.koekeishiya.kwm.plist";

CFMachPortRef EventTap;

kwm_path KWMPath = {};
kwm_screen KWMScreen = {};
kwm_toggles KWMToggles = {};
kwm_focus KWMFocus = {};
kwm_mode KWMMode = {};
kwm_tiling KWMTiling = {};
kwm_cache KWMCache = {};
kwm_thread KWMThread = {};
kwm_hotkeys KWMHotkeys = {};
kwm_border KWMBorder = {};

CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
    pthread_mutex_lock(&KWMThread.Lock);

    switch(Type)
    {
        case kCGEventTapDisabledByTimeout:
        case kCGEventTapDisabledByUserInput:
        {
            DEBUG("Restarting Event Tap")
            CGEventTapEnable(EventTap, true);
        } break;
        case kCGEventKeyDown:
        {
            if(KWMToggles.UseBuiltinHotkeys && KwmMainHotkeyTrigger(&Event))
            {
                    pthread_mutex_unlock(&KWMThread.Lock);
                    return NULL;
            }

            if(KWMMode.Focus == FocusModeAutofocus)
            {
                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
                CGEventPostToPSN(&KWMFocus.PSN, Event);
                pthread_mutex_unlock(&KWMThread.Lock);
                return NULL;
            }
        } break;
        case kCGEventKeyUp:
        {
            if(KWMMode.Focus == FocusModeAutofocus)
            {
                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
                CGEventPostToPSN(&KWMFocus.PSN, Event);
                pthread_mutex_unlock(&KWMThread.Lock);
                return NULL;
            }
        } break;
        case kCGEventMouseMoved:
        {
            if(KWMMode.Focus != FocusModeDisabled)
                FocusWindowBelowCursor();
        } break;
        case kCGEventLeftMouseDown:
        {
            DEBUG("Left mouse button was pressed")
            FocusWindowBelowCursor();
            if(KWMToggles.EnableDragAndDrop && IsCursorInsideFocusedWindow())
               KWMToggles.WindowDragInProgress = true;
        } break;
        case kCGEventLeftMouseUp:
        {
            DEBUG("Left mouse button was released")
            if(KWMToggles.EnableDragAndDrop && KWMToggles.WindowDragInProgress)
            {
                if(!IsCursorInsideFocusedWindow())
                    ToggleFocusedWindowFloating();

                KWMToggles.WindowDragInProgress = false;
            }
        } break;
    }

    pthread_mutex_unlock(&KWMThread.Lock);
    return Event;
}

void KwmQuit()
{
    if(KWMBorder.Handle)
        fclose(KWMBorder.Handle);

    exit(0);
}

void * KwmWindowMonitor(void*)
{
    while(1)
    {
        pthread_mutex_lock(&KWMThread.Lock);
        UpdateWindowTree();
        pthread_mutex_unlock(&KWMThread.Lock);
        usleep(200000);
    }
}

bool IsPrefixOfString(std::string &Line, std::string Prefix)
{
    bool Result = false;

    if(Line.substr(0, Prefix.size()) == Prefix)
    {
        Line = Line.substr(Prefix.size()+1);
        Result = true;
    }

    return Result;
}

void KwmReloadConfig()
{
    KwmClearSettings();
    KwmExecuteConfig();
}

void KwmClearSettings()
{
    std::map<std::string, std::vector<CFTypeRef> >::iterator It;
    for(It = KWMTiling.AllowedWindowRoles.begin(); It != KWMTiling.AllowedWindowRoles.end(); ++It)
    {
        std::vector<CFTypeRef> &WindowRoles = It->second;
        for(std::size_t RoleIndex = 0; RoleIndex < WindowRoles.size(); ++RoleIndex)
            CFRelease(WindowRoles[RoleIndex]);

        WindowRoles.clear();
    }

    KWMTiling.FloatingAppLst.clear();
    KWMHotkeys.List.clear();
    KWMHotkeys.Prefix.Enabled = false;
}

void KwmExecuteConfig()
{
    char *HomeP = std::getenv("HOME");
    if(!HomeP)
    {
        DEBUG("Failed to get environment variable 'HOME'")
        return;
    }

    KWMPath.EnvHome = HomeP;
    KWMPath.ConfigFolder = ".kwm";
    std::ifstream ConfigFD(KWMPath.EnvHome + "/" + KWMPath.ConfigFolder + "/" + KWMPath.ConfigFile);
    if(ConfigFD.fail())
    {
        DEBUG("Could not open " << KWMPath.EnvHome << "/" << KWMPath.ConfigFolder << "/" << KWMPath.ConfigFile
              << ", make sure the file exists." << std::endl)
        return;
    }

    std::string Line;
    while(std::getline(ConfigFD, Line))
    {
        if(!Line.empty() && Line[0] != '#')
        {
            if(IsPrefixOfString(Line, "kwmc"))
                KwmInterpretCommand(Line, 0);
            else if(IsPrefixOfString(Line, "sys"))
                system(Line.c_str());
        }
    }

    ConfigFD.close();
}

bool IsKwmAlreadyAddedToLaunchd()
{
    std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;

    struct stat attr;
    int Result = stat(SymlinkFullPath.c_str(), &attr);
    if(Result == -1)
        return false;

    return true;
}

void AddKwmToLaunchd()
{
    if(IsKwmAlreadyAddedToLaunchd())
        return;

    std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;

    std::ifstream TemplateFD(KWMPath.FilePath + "/kwm_template.plist");
    if(TemplateFD.fail())
        return;

    std::ofstream OutFD(SymlinkFullPath);
    if(OutFD.fail())
        return;

    std::string Line;
    std::vector<std::string> PlistContents;
    while(std::getline(TemplateFD, Line))
        PlistContents.push_back(Line);

    DEBUG("AddKwmToLaunchd() Creating file: " << SymlinkFullPath)
    for(std::size_t LineNumber = 0; LineNumber < PlistContents.size(); ++LineNumber)
    {
        if(LineNumber == 8)
            OutFD << "    <string>" + KWMPath.FilePath + "/kwm</string>" << std::endl;
        else
            OutFD << PlistContents[LineNumber] << std::endl;
    }

    TemplateFD.close();
    OutFD.close();
}

void RemoveKwmFromLaunchd()
{
    if(!IsKwmAlreadyAddedToLaunchd())
        return;

    std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
    std::string RemoveSymlink = "rm " + SymlinkFullPath;

    system(RemoveSymlink.c_str());
    DEBUG("RemoveKwmFromLaunchd() Removing file: " << SymlinkFullPath)
}

bool GetKwmFilePath()
{
    bool Result = false;
    char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
    pid_t Pid = getpid();
    int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
    if (Ret > 0)
    {
        KWMPath.FilePath = PathBuf;

        std::size_t Split = KWMPath.FilePath.find_last_of("/\\");
        KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);
        KWMPath.HotkeySOFullPath = KWMPath.FilePath + "/hotkeys.so";
        Result = true;
    }

    return Result;
}

void KwmInit()
{
    if(!CheckPrivileges())
        Fatal("Could not access OSX Accessibility!");

    if (pthread_mutex_init(&KWMThread.Lock, NULL) != 0)
        Fatal("Could not create mutex!");

    if(KwmStartDaemon())
        pthread_create(&KWMThread.Daemon, NULL, &KwmDaemonHandleConnectionBG, NULL);
    else
        Fatal("Kwm: Could not start daemon..");

    KWMScreen.SplitRatio = 0.5;
    KWMScreen.SplitMode = -1;
    KWMScreen.MarkedWindow = -1;
    KWMScreen.OldScreenID = -1;
    KWMScreen.PrevSpace = -1;
    KWMScreen.DefaultOffset = CreateDefaultScreenOffset();
    KWMScreen.MaxCount = 5;
    KWMScreen.ActiveCount = 0;
    KWMScreen.UpdateSpace = true;

    KWMToggles.EnableTilingMode = true;
    KWMToggles.UseBuiltinHotkeys = true;
    KWMToggles.EnableDragAndDrop = true;
    KWMToggles.UseContextMenuFix = true;
    KWMToggles.UseMouseFollowsFocus = true;
    KWMToggles.WindowDragInProgress = false;

    KWMMode.Space = SpaceModeBSP;
    KWMMode.Focus = FocusModeAutoraise;
    KWMMode.Cycle = CycleModeScreen;

    KWMHotkeys.Prefix.Enabled = false;
    KWMHotkeys.Prefix.Global = false;
    KWMHotkeys.Prefix.Active = false;
    KWMHotkeys.Prefix.Timeout = 0.75;

    KWMPath.ConfigFile = "kwmrc";
    GetKwmFilePath();

    KwmExecuteConfig();
    GetActiveDisplays();

    pthread_create(&KWMThread.WindowMonitor, NULL, &KwmWindowMonitor, NULL);
}

bool CheckPrivileges()
{
    bool Result = false;
    const void * Keys[] = { kAXTrustedCheckOptionPrompt };
    const void * Values[] = { kCFBooleanTrue };

    CFDictionaryRef Options;
    Options = CFDictionaryCreate(kCFAllocatorDefault,
            Keys, Values, sizeof(Keys) / sizeof(*Keys),
            &kCFCopyStringDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks);

    Result = AXIsProcessTrustedWithOptions(Options);
    CFRelease(Options);

    return Result;
}

bool CheckArguments(int argc, char **argv)
{
    bool Result = false;

    if(argc == 2)
    {
        std::string Arg = argv[1];
        if(Arg == "--version")
        {
            std::cout << KwmCurrentVersion << std::endl;
            Result = true;
        }
    }

    return Result;
}

void Fatal(const std::string &Err)
{
    std::cout << Err << std::endl;
    exit(1);
}

int main(int argc, char **argv)
{
    if(CheckArguments(argc, argv))
        return 0;

    KwmInit();
    CGEventMask EventMask;
    EventMask = ((1 << kCGEventKeyDown) |
                 (1 << kCGEventKeyUp) |
                 (1 << kCGEventMouseMoved) |
                 (1 << kCGEventLeftMouseDown) |
                 (1 << kCGEventLeftMouseUp));

    EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);
    if(!EventTap || !CGEventTapIsEnabled(EventTap))
        Fatal("ERROR: Could not create event-tap!");

    CFRunLoopSourceRef RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
    CGEventTapEnable(EventTap, true);
    NSApplicationLoad();
    CFRunLoopRun();

    return 0;
}
<commit_msg>correctly call pclose instead of fclose<commit_after>#include "kwm.h"

const std::string KwmCurrentVersion = "Kwm Version 1.0.7";
const std::string PlistFile = "com.koekeishiya.kwm.plist";

CFMachPortRef EventTap;

kwm_path KWMPath = {};
kwm_screen KWMScreen = {};
kwm_toggles KWMToggles = {};
kwm_focus KWMFocus = {};
kwm_mode KWMMode = {};
kwm_tiling KWMTiling = {};
kwm_cache KWMCache = {};
kwm_thread KWMThread = {};
kwm_hotkeys KWMHotkeys = {};
kwm_border KWMBorder = {};

CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
    pthread_mutex_lock(&KWMThread.Lock);

    switch(Type)
    {
        case kCGEventTapDisabledByTimeout:
        case kCGEventTapDisabledByUserInput:
        {
            DEBUG("Restarting Event Tap")
            CGEventTapEnable(EventTap, true);
        } break;
        case kCGEventKeyDown:
        {
            if(KWMToggles.UseBuiltinHotkeys && KwmMainHotkeyTrigger(&Event))
            {
                    pthread_mutex_unlock(&KWMThread.Lock);
                    return NULL;
            }

            if(KWMMode.Focus == FocusModeAutofocus)
            {
                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
                CGEventPostToPSN(&KWMFocus.PSN, Event);
                pthread_mutex_unlock(&KWMThread.Lock);
                return NULL;
            }
        } break;
        case kCGEventKeyUp:
        {
            if(KWMMode.Focus == FocusModeAutofocus)
            {
                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
                CGEventPostToPSN(&KWMFocus.PSN, Event);
                pthread_mutex_unlock(&KWMThread.Lock);
                return NULL;
            }
        } break;
        case kCGEventMouseMoved:
        {
            if(KWMMode.Focus != FocusModeDisabled)
                FocusWindowBelowCursor();
        } break;
        case kCGEventLeftMouseDown:
        {
            DEBUG("Left mouse button was pressed")
            FocusWindowBelowCursor();
            if(KWMToggles.EnableDragAndDrop && IsCursorInsideFocusedWindow())
               KWMToggles.WindowDragInProgress = true;
        } break;
        case kCGEventLeftMouseUp:
        {
            DEBUG("Left mouse button was released")
            if(KWMToggles.EnableDragAndDrop && KWMToggles.WindowDragInProgress)
            {
                if(!IsCursorInsideFocusedWindow())
                    ToggleFocusedWindowFloating();

                KWMToggles.WindowDragInProgress = false;
            }
        } break;
    }

    pthread_mutex_unlock(&KWMThread.Lock);
    return Event;
}

void KwmQuit()
{
    if(KWMBorder.Handle)
        pclose(KWMBorder.Handle);

    exit(0);
}

void * KwmWindowMonitor(void*)
{
    while(1)
    {
        pthread_mutex_lock(&KWMThread.Lock);
        UpdateWindowTree();
        pthread_mutex_unlock(&KWMThread.Lock);
        usleep(200000);
    }
}

bool IsPrefixOfString(std::string &Line, std::string Prefix)
{
    bool Result = false;

    if(Line.substr(0, Prefix.size()) == Prefix)
    {
        Line = Line.substr(Prefix.size()+1);
        Result = true;
    }

    return Result;
}

void KwmReloadConfig()
{
    KwmClearSettings();
    KwmExecuteConfig();
}

void KwmClearSettings()
{
    std::map<std::string, std::vector<CFTypeRef> >::iterator It;
    for(It = KWMTiling.AllowedWindowRoles.begin(); It != KWMTiling.AllowedWindowRoles.end(); ++It)
    {
        std::vector<CFTypeRef> &WindowRoles = It->second;
        for(std::size_t RoleIndex = 0; RoleIndex < WindowRoles.size(); ++RoleIndex)
            CFRelease(WindowRoles[RoleIndex]);

        WindowRoles.clear();
    }

    KWMTiling.FloatingAppLst.clear();
    KWMHotkeys.List.clear();
    KWMHotkeys.Prefix.Enabled = false;
}

void KwmExecuteConfig()
{
    char *HomeP = std::getenv("HOME");
    if(!HomeP)
    {
        DEBUG("Failed to get environment variable 'HOME'")
        return;
    }

    KWMPath.EnvHome = HomeP;
    KWMPath.ConfigFolder = ".kwm";
    std::ifstream ConfigFD(KWMPath.EnvHome + "/" + KWMPath.ConfigFolder + "/" + KWMPath.ConfigFile);
    if(ConfigFD.fail())
    {
        DEBUG("Could not open " << KWMPath.EnvHome << "/" << KWMPath.ConfigFolder << "/" << KWMPath.ConfigFile
              << ", make sure the file exists." << std::endl)
        return;
    }

    std::string Line;
    while(std::getline(ConfigFD, Line))
    {
        if(!Line.empty() && Line[0] != '#')
        {
            if(IsPrefixOfString(Line, "kwmc"))
                KwmInterpretCommand(Line, 0);
            else if(IsPrefixOfString(Line, "sys"))
                system(Line.c_str());
        }
    }

    ConfigFD.close();
}

bool IsKwmAlreadyAddedToLaunchd()
{
    std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;

    struct stat attr;
    int Result = stat(SymlinkFullPath.c_str(), &attr);
    if(Result == -1)
        return false;

    return true;
}

void AddKwmToLaunchd()
{
    if(IsKwmAlreadyAddedToLaunchd())
        return;

    std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;

    std::ifstream TemplateFD(KWMPath.FilePath + "/kwm_template.plist");
    if(TemplateFD.fail())
        return;

    std::ofstream OutFD(SymlinkFullPath);
    if(OutFD.fail())
        return;

    std::string Line;
    std::vector<std::string> PlistContents;
    while(std::getline(TemplateFD, Line))
        PlistContents.push_back(Line);

    DEBUG("AddKwmToLaunchd() Creating file: " << SymlinkFullPath)
    for(std::size_t LineNumber = 0; LineNumber < PlistContents.size(); ++LineNumber)
    {
        if(LineNumber == 8)
            OutFD << "    <string>" + KWMPath.FilePath + "/kwm</string>" << std::endl;
        else
            OutFD << PlistContents[LineNumber] << std::endl;
    }

    TemplateFD.close();
    OutFD.close();
}

void RemoveKwmFromLaunchd()
{
    if(!IsKwmAlreadyAddedToLaunchd())
        return;

    std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
    std::string RemoveSymlink = "rm " + SymlinkFullPath;

    system(RemoveSymlink.c_str());
    DEBUG("RemoveKwmFromLaunchd() Removing file: " << SymlinkFullPath)
}

bool GetKwmFilePath()
{
    bool Result = false;
    char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
    pid_t Pid = getpid();
    int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
    if (Ret > 0)
    {
        KWMPath.FilePath = PathBuf;

        std::size_t Split = KWMPath.FilePath.find_last_of("/\\");
        KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);
        KWMPath.HotkeySOFullPath = KWMPath.FilePath + "/hotkeys.so";
        Result = true;
    }

    return Result;
}

void KwmInit()
{
    if(!CheckPrivileges())
        Fatal("Could not access OSX Accessibility!");

    if (pthread_mutex_init(&KWMThread.Lock, NULL) != 0)
        Fatal("Could not create mutex!");

    if(KwmStartDaemon())
        pthread_create(&KWMThread.Daemon, NULL, &KwmDaemonHandleConnectionBG, NULL);
    else
        Fatal("Kwm: Could not start daemon..");

    KWMScreen.SplitRatio = 0.5;
    KWMScreen.SplitMode = -1;
    KWMScreen.MarkedWindow = -1;
    KWMScreen.OldScreenID = -1;
    KWMScreen.PrevSpace = -1;
    KWMScreen.DefaultOffset = CreateDefaultScreenOffset();
    KWMScreen.MaxCount = 5;
    KWMScreen.ActiveCount = 0;
    KWMScreen.UpdateSpace = true;

    KWMToggles.EnableTilingMode = true;
    KWMToggles.UseBuiltinHotkeys = true;
    KWMToggles.EnableDragAndDrop = true;
    KWMToggles.UseContextMenuFix = true;
    KWMToggles.UseMouseFollowsFocus = true;
    KWMToggles.WindowDragInProgress = false;

    KWMMode.Space = SpaceModeBSP;
    KWMMode.Focus = FocusModeAutoraise;
    KWMMode.Cycle = CycleModeScreen;

    KWMHotkeys.Prefix.Enabled = false;
    KWMHotkeys.Prefix.Global = false;
    KWMHotkeys.Prefix.Active = false;
    KWMHotkeys.Prefix.Timeout = 0.75;

    KWMPath.ConfigFile = "kwmrc";
    GetKwmFilePath();

    KwmExecuteConfig();
    GetActiveDisplays();

    pthread_create(&KWMThread.WindowMonitor, NULL, &KwmWindowMonitor, NULL);
}

bool CheckPrivileges()
{
    bool Result = false;
    const void * Keys[] = { kAXTrustedCheckOptionPrompt };
    const void * Values[] = { kCFBooleanTrue };

    CFDictionaryRef Options;
    Options = CFDictionaryCreate(kCFAllocatorDefault,
            Keys, Values, sizeof(Keys) / sizeof(*Keys),
            &kCFCopyStringDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks);

    Result = AXIsProcessTrustedWithOptions(Options);
    CFRelease(Options);

    return Result;
}

bool CheckArguments(int argc, char **argv)
{
    bool Result = false;

    if(argc == 2)
    {
        std::string Arg = argv[1];
        if(Arg == "--version")
        {
            std::cout << KwmCurrentVersion << std::endl;
            Result = true;
        }
    }

    return Result;
}

void Fatal(const std::string &Err)
{
    std::cout << Err << std::endl;
    exit(1);
}

int main(int argc, char **argv)
{
    if(CheckArguments(argc, argv))
        return 0;

    KwmInit();
    CGEventMask EventMask;
    EventMask = ((1 << kCGEventKeyDown) |
                 (1 << kCGEventKeyUp) |
                 (1 << kCGEventMouseMoved) |
                 (1 << kCGEventLeftMouseDown) |
                 (1 << kCGEventLeftMouseUp));

    EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);
    if(!EventTap || !CGEventTapIsEnabled(EventTap))
        Fatal("ERROR: Could not create event-tap!");

    CFRunLoopSourceRef RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
    CGEventTapEnable(EventTap, true);
    NSApplicationLoad();
    CFRunLoopRun();

    return 0;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
/*!
 * \file moab_transfer_1.cpp
 * \author Stuart R. Slattery
 * \brief Moab mesh transfer example.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cstdlib>

#include <DTK_MeshManager.hpp>
#include <DTK_MeshTools.hpp>
#include <DTK_SharedDomainMap.hpp>
#include <DTK_FieldEvaluator.hpp>
#include <DTK_MeshTraits.hpp>
#include <DTK_MeshTraitsFieldAdapter.hpp>

#include "MoabMesh.hpp"
#include "ArrayField.hpp"
#include "PeaksEvaluator.hpp"

#include <Teuchos_GlobalMPISession.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_DefaultMpiComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>

//---------------------------------------------------------------------------//
// Example driver.
//---------------------------------------------------------------------------//
int main(int argc, char* argv[])
{
    // Typedefs.
    typedef MoabMesh::Container MeshType;

    // Setup communication.
    Teuchos::GlobalMPISession mpiSession(&argc,&argv);
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();

    // Setup source mesh. Partitioned in x.
    int mesh_dim = 2;
    MoabMesh source_mesh( comm, "tri_peaks.vtk", moab::MBTRI, 0 );
    Teuchos::ArrayRCP<Teuchos::RCP<MeshType> >
	source_blocks( 1, source_mesh.meshContainer() );
    Teuchos::RCP<DataTransferKit::MeshManager<MeshType> >
	source_mesh_manager =
	Teuchos::rcp( new DataTransferKit::MeshManager<MeshType>(
			  source_blocks, comm, mesh_dim ) );

    // Setup target coordinate field. Partitioned in y.
    MoabMesh target_mesh( comm, "quad_mesh.vtk", moab::MBQUAD, 1 );
    Teuchos::RCP<DataTransferKit::FieldManager<MeshType> >
	target_coords_manager =
	Teuchos::rcp( new DataTransferKit::FieldManager<MeshType>(
			  target_mesh.meshContainer(), comm ) );

    // Create a peaks function evaluator.
    Teuchos::RCP<DataTransferKit::FieldEvaluator<MeshType::global_ordinal_type,
						 ArrayField> >
	peaks_evaluator = Teuchos::rcp( new PeaksEvaluator( source_mesh ) );

    // Create data target.
    int num_targets = DataTransferKit::MeshTools<MeshType>::numVertices(
	*(target_mesh.meshContainer()) );
    Teuchos::RCP<ArrayField> data_target = Teuchos::rcp(
	new ArrayField( num_targets, 1 ) );
    Teuchos::RCP<DataTransferKit::FieldManager<ArrayField> >
	target_space_manager =
	Teuchos::rcp( new DataTransferKit::FieldManager<ArrayField>(
			  data_target, comm ) );

    // Construct shared domain map.
    DataTransferKit::SharedDomainMap<MeshType,MeshType>
	shared_domain_map( comm, mesh_dim );

    // Call setup. This creates the mapping.
    shared_domain_map.setup( source_mesh_manager, target_coords_manager );

    // Apply the map. This does the field evaluation and moves the data.
    shared_domain_map.apply( peaks_evaluator, target_space_manager );

    // Set the data on the target mesh and write.
    target_mesh.tag( *data_target );
    target_mesh.write( "quad_result.vtk" );

    return 0;
}

//---------------------------------------------------------------------------//
// end scaling_study_1.cpp
//---------------------------------------------------------------------------//

<commit_msg>Adding standard try/catch in main to report errors correctly (VRI Kanban #2852, DTK #13)<commit_after>//---------------------------------------------------------------------------//
/*!
 * \file moab_transfer_1.cpp
 * \author Stuart R. Slattery
 * \brief Moab mesh transfer example.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cstdlib>

#include <DTK_MeshManager.hpp>
#include <DTK_MeshTools.hpp>
#include <DTK_SharedDomainMap.hpp>
#include <DTK_FieldEvaluator.hpp>
#include <DTK_MeshTraits.hpp>
#include <DTK_MeshTraitsFieldAdapter.hpp>

#include "MoabMesh.hpp"
#include "ArrayField.hpp"
#include "PeaksEvaluator.hpp"

#include <Teuchos_GlobalMPISession.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_DefaultMpiComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_VerboseObject.hpp>
#include <Teuchos_StandardCatchMacros.hpp>

//---------------------------------------------------------------------------//
// Example driver.
//---------------------------------------------------------------------------//
int main(int argc, char* argv[])
{
  // Typedefs.
  typedef MoabMesh::Container MeshType;

  // Setup communication.
  Teuchos::GlobalMPISession mpiSession(&argc,&argv);

  Teuchos::RCP<Teuchos::FancyOStream>
    out = Teuchos::VerboseObjectBase::getDefaultOStream();
  bool success = true;
  bool verbose = true;

  Teuchos::RCP<const Teuchos::Comm<int> > comm =
    Teuchos::DefaultComm<int>::getComm();

  try {

    // Setup source mesh. Partitioned in x.
    int mesh_dim = 2;
    MoabMesh source_mesh( comm, "tri_peaks.vtk", moab::MBTRI, 0 );
    Teuchos::ArrayRCP<Teuchos::RCP<MeshType> >
      source_blocks( 1, source_mesh.meshContainer() );
    Teuchos::RCP<DataTransferKit::MeshManager<MeshType> >
      source_mesh_manager =
      Teuchos::rcp( new DataTransferKit::MeshManager<MeshType>(
          source_blocks, comm, mesh_dim ) );

    // Setup target coordinate field. Partitioned in y.
    MoabMesh target_mesh( comm, "quad_mesh.vtk", moab::MBQUAD, 1 );
    Teuchos::RCP<DataTransferKit::FieldManager<MeshType> >
      target_coords_manager =
      Teuchos::rcp( new DataTransferKit::FieldManager<MeshType>(
          target_mesh.meshContainer(), comm ) );

    // Create a peaks function evaluator.
    Teuchos::RCP<DataTransferKit::FieldEvaluator<MeshType::global_ordinal_type,
      ArrayField> >
      peaks_evaluator = Teuchos::rcp( new PeaksEvaluator( source_mesh ) );

    // Create data target.
    int num_targets = DataTransferKit::MeshTools<MeshType>::numVertices(
      *(target_mesh.meshContainer()) );
    Teuchos::RCP<ArrayField> data_target = Teuchos::rcp(
      new ArrayField( num_targets, 1 ) );
    Teuchos::RCP<DataTransferKit::FieldManager<ArrayField> >
      target_space_manager =
      Teuchos::rcp( new DataTransferKit::FieldManager<ArrayField>(
          data_target, comm ) );

    // Construct shared domain map.
    DataTransferKit::SharedDomainMap<MeshType,MeshType>
      shared_domain_map( comm, mesh_dim );

    // Call setup. This creates the mapping.
    shared_domain_map.setup( source_mesh_manager, target_coords_manager );

    // Apply the map. This does the field evaluation and moves the data.
    shared_domain_map.apply( peaks_evaluator, target_space_manager );

    // Set the data on the target mesh and write.
    target_mesh.tag( *data_target );
    target_mesh.write( "quad_result.vtk" );

  }
  TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success)

    if (verbose) {
      if(success)  *out << "\nCongratulations! All of the tests checked out!\n";
      else         *out << "\nOh no! At least one of the tests failed!\n";
    }

  return ( success ? 0 : 1 );

}

//---------------------------------------------------------------------------//
// end scaling_study_1.cpp
//---------------------------------------------------------------------------//

<|endoftext|>


<commit_before>// File adopted by Nick Markwell (duckinator)

#include "client/input.h"

InputHandler::InputHandler(Context *context) : context(context), InChat(false) {
    context->window->ShowMouseCursor(false);
}

bool inputWaiting;

bool fullscreen = false;
void InputHandler::handleEvent(sf::Event Event) {
    float time;

    // Close window : exit
    if (Event.Type == sf::Event::Closed)
        context->window->Close();

    // Handle text input for chat
    if (InChat && Event.Type == sf::Event::TextEntered) {

        // Ignore the first char (which is t)
        if (inputWaiting) {
            inputWaiting = false;
            return;
        }

        // Handle ASCII characters only
        if (Event.Text.Unicode < 128) {
            context->hud->chatEntry += static_cast<char>(Event.Text.Unicode);
        }
    }

    // Handle enter to send message
    if (InChat && Event.Type == sf::Event::KeyPressed) {
        switch(Event.Key.Code) {
            // F11 : toggle fullscreen
            case sf::Key::F11:
                toggleFullscreen();
                break;

            // Escape key : cancel message
            case sf::Key::Escape:
                context->hud->chatEntry = "";
                InChat = false;
                return; // don't run the handlers from down there

            // Enter : send message
            case sf::Key::Return:
                context->socket->SendChat(context->hud->chatEntry);
                context->hud->chatEntry = "";
                InChat = false;
                return; // don't run the handlers from down there

        }
    }

    // Otherwise....
    if (!InChat && Event.Type == sf::Event::KeyPressed) {
        switch(Event.Key.Code) {
            // Escape key : exit
            case sf::Key::Escape:
                context->inGame = false;
                break;
            // F11 : toggle fullscreen
            case sf::Key::F11:
                toggleFullscreen();
                break;

            // T : chat
            case sf::Key::T:
                context->hud->chatEntry = ""; // TODO: needed?
                InChat = true;
                inputWaiting = true;
                break;

            // W : forward
            case sf::Key::W:
                context->player->Forward = true;
                break;
            // S : backward
            case sf::Key::S:
                context->player->Backward = true;
                break;
            // A : left
            case sf::Key::A:
                context->player->Left = true;
                break;
            // D : right
            case sf::Key::D:
                context->player->Right = true;
                break;

            // Left Control, C : crouch
            case sf::Key::LControl:
            case sf::Key::C:
                MovementTimer.Reset();
                WasCrouching = context->player->Crouching;
                context->player->Crouching = true;
                break;

            // V : crawl
            case sf::Key::V:
                MovementTimer.Reset();
                WasCrawling = context->player->Crawling;
                context->player->Crawling = true;
                break;

            // Left Shift : run
            case sf::Key::LShift:
                MovementTimer.Reset();
                WasRunning = context->player->Running;
                context->player->Running = true;
                break;

            // Space : jump
            case sf::Key::Space:
                context->player->Jumping = true;
                break;
        }
    }

    if (Event.Type == sf::Event::KeyReleased) {
        time = MovementTimer.GetElapsedTime();

        switch(Event.Key.Code) {
            // W : forward
            case sf::Key::W:
                context->player->Forward = false;
                break;
            // S : backward
            case sf::Key::S:
                context->player->Backward = false;
                break;
            // A : left
            case sf::Key::A:
                context->player->Left = false;
                break;
            // D : right
            case sf::Key::D:
                context->player->Right = false;
                break;

            // Left Control, C : crouch
            case sf::Key::LControl:
            case sf::Key::C:
                if (time > 0.1)
                    context->player->Crouching = false;
                else
                    context->player->Crouching = !WasCrouching;
                break;

            // V : crawl
            case sf::Key::V:
                if (time > 0.1)
                    context->player->Crawling = false;
                else
                    context->player->Crawling = !WasCrawling;
                break;

            // Left Shift : run
            case sf::Key::LShift:
                if (time > 0.1)
                    context->player->Running = false;
                else
                    context->player->Running = !WasRunning;

            // Space : jump
            case sf::Key::Space:
                context->player->Jumping = false;
                break;
        }
    }

    // Resize event : adjust viewport
    if (Event.Type == sf::Event::Resized)
        glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}

float ElapsedTime;
float mouseDeltaX, mouseDeltaY;

void InputHandler::handleEvents() {
    const sf::Input& Input = context->window->GetInput();

    // Constant movement speed
    ElapsedTime = Clock.GetElapsedTime();
    Clock.Reset();

    // Handle other events
    sf::Event Event;
    while (context->window->GetEvent(Event))
    {
        handleEvent(Event);
    }

    // Rotate view based on mouse movement
    mouseDeltaX = Input.GetMouseX() - 100;
    mouseDeltaY = Input.GetMouseY() - 100;
    context->window->SetCursorPosition(100, 100);

    if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0))
        context->player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10));

    context->player->DoStep(ElapsedTime);
}

void InputHandler::toggleFullscreen() {
    fullscreen = !fullscreen;
    context->window->Create(sf::VideoMode(800, 600, 32), "MineCube", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));

    context->renderer->InitGraphics();
    context->window->ShowMouseCursor(false);
}

<commit_msg>Added backspace to the chat textinput<commit_after>// File adopted by Nick Markwell (duckinator)

#include "client/input.h"

InputHandler::InputHandler(Context *context) : context(context), InChat(false) {
    context->window->ShowMouseCursor(false);
}

bool inputWaiting;

bool fullscreen = false;
void InputHandler::handleEvent(sf::Event Event) {
    float time;

    // Close window : exit
    if (Event.Type == sf::Event::Closed)
        context->window->Close();

    // Handle text input for chat
    if (InChat && Event.Type == sf::Event::TextEntered) {

        // Ignore the first char (which is t)
        if (inputWaiting) {
            inputWaiting = false;
            return;
        }

        // Handle ASCII characters only
        if (Event.Text.Unicode == 8) { // TODO: use KeyPressed?
            if (context->hud->chatEntry.size() > 0)
                context->hud->chatEntry.erase(context->hud->chatEntry.size() - 1, 1);
        } else if (Event.Text.Unicode < 128) {
            context->hud->chatEntry += static_cast<char>(Event.Text.Unicode);
        }
    }

    // Handle enter to send message
    if (InChat && Event.Type == sf::Event::KeyPressed) {
        switch(Event.Key.Code) {
            // F11 : toggle fullscreen
            case sf::Key::F11:
                toggleFullscreen();
                break;

            // Escape key : cancel message
            case sf::Key::Escape:
                context->hud->chatEntry = "";
                InChat = false;
                return; // don't run the handlers from down there

            // Enter : send message
            case sf::Key::Return:
                context->socket->SendChat(context->hud->chatEntry);
                context->hud->chatEntry = "";
                InChat = false;
                return; // don't run the handlers from down there

        }
    }

    // Otherwise....
    if (!InChat && Event.Type == sf::Event::KeyPressed) {
        switch(Event.Key.Code) {
            // Escape key : exit
            case sf::Key::Escape:
                context->inGame = false;
                break;
            // F11 : toggle fullscreen
            case sf::Key::F11:
                toggleFullscreen();
                break;

            // T : chat
            case sf::Key::T:
                context->hud->chatEntry = ""; // TODO: needed?
                InChat = true;
                inputWaiting = true;
                break;

            // W : forward
            case sf::Key::W:
                context->player->Forward = true;
                break;
            // S : backward
            case sf::Key::S:
                context->player->Backward = true;
                break;
            // A : left
            case sf::Key::A:
                context->player->Left = true;
                break;
            // D : right
            case sf::Key::D:
                context->player->Right = true;
                break;

            // Left Control, C : crouch
            case sf::Key::LControl:
            case sf::Key::C:
                MovementTimer.Reset();
                WasCrouching = context->player->Crouching;
                context->player->Crouching = true;
                break;

            // V : crawl
            case sf::Key::V:
                MovementTimer.Reset();
                WasCrawling = context->player->Crawling;
                context->player->Crawling = true;
                break;

            // Left Shift : run
            case sf::Key::LShift:
                MovementTimer.Reset();
                WasRunning = context->player->Running;
                context->player->Running = true;
                break;

            // Space : jump
            case sf::Key::Space:
                context->player->Jumping = true;
                break;
        }
    }

    if (Event.Type == sf::Event::KeyReleased) {
        time = MovementTimer.GetElapsedTime();

        switch(Event.Key.Code) {
            // W : forward
            case sf::Key::W:
                context->player->Forward = false;
                break;
            // S : backward
            case sf::Key::S:
                context->player->Backward = false;
                break;
            // A : left
            case sf::Key::A:
                context->player->Left = false;
                break;
            // D : right
            case sf::Key::D:
                context->player->Right = false;
                break;

            // Left Control, C : crouch
            case sf::Key::LControl:
            case sf::Key::C:
                if (time > 0.1)
                    context->player->Crouching = false;
                else
                    context->player->Crouching = !WasCrouching;
                break;

            // V : crawl
            case sf::Key::V:
                if (time > 0.1)
                    context->player->Crawling = false;
                else
                    context->player->Crawling = !WasCrawling;
                break;

            // Left Shift : run
            case sf::Key::LShift:
                if (time > 0.1)
                    context->player->Running = false;
                else
                    context->player->Running = !WasRunning;

            // Space : jump
            case sf::Key::Space:
                context->player->Jumping = false;
                break;
        }
    }

    // Resize event : adjust viewport
    if (Event.Type == sf::Event::Resized)
        glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}

float ElapsedTime;
float mouseDeltaX, mouseDeltaY;

void InputHandler::handleEvents() {
    const sf::Input& Input = context->window->GetInput();

    // Constant movement speed
    ElapsedTime = Clock.GetElapsedTime();
    Clock.Reset();

    // Handle other events
    sf::Event Event;
    while (context->window->GetEvent(Event))
    {
        handleEvent(Event);
    }

    // Rotate view based on mouse movement
    mouseDeltaX = Input.GetMouseX() - 100;
    mouseDeltaY = Input.GetMouseY() - 100;
    context->window->SetCursorPosition(100, 100);

    if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0))
        context->player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10));

    context->player->DoStep(ElapsedTime);
}

void InputHandler::toggleFullscreen() {
    fullscreen = !fullscreen;
    context->window->Create(sf::VideoMode(800, 600, 32), "MineCube", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));

    context->renderer->InitGraphics();
    context->window->ShowMouseCursor(false);
}

<|endoftext|>


<commit_before>/**
  \file   main.cc
  \brief  Main file fir the finite element example.
  **/
// disable warnings about problems in dune headers
#include <dune/fem-tools/header/disablewarnings.hh>

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <iostream>
#include <vector>

// dune-common includes
#include <dune/common/exceptions.hh>
#include <dune/common/fmatrix.hh>

// dune-grid includes
#include <dune/grid/utility/gridtype.hh>

// dune-istl includes
#include <dune/istl/bcrsmatrix.hh>
#include <dune/istl/solvers.hh>
#include <dune/istl/bvector.hh>

// dune-fem includes
#include <dune/fem/misc/mpimanager.hh>
//#include <dune/fem/gridpart/gridpart.hh>
//#include <dune/fem/storage/vector.hh>
//#include <dune/fem/function/adaptivefunction/adaptivefunction.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>

// reenable warnings
#include <dune/fem-tools/header/enablewarnings.hh>

// dune-functionals includes
#include <dune/functionals/discretefunctionspace/finiteelement.hh>
#include <dune/functionals/discretefunctionspace/subspace/linear.hh>
#include <dune/functionals/discretefunctionspace/subspace/affine.hh>
//#include <dune/fem/localoperation/interface.hh>
//#include <dune/fem/localoperation/integrator.hh>
//#include <dune/fem/subspace/subspaces.hh>
//#include <dune/fem/operator/linear.hh>
//#include <dune/fem/functional/finiteelement.hh>
//#include <dune/fem/container/factory.hh>
//#include <dune/fem/solver/femassembler.hh>

// dune-fem-tools includes
//#include <dune/fem-tools/function/functiontools.hh>
//#include <dune/fem-tools/space/projection.hh>

using namespace Dune::Functionals;

#ifndef POLORDER
const int polOrder = 1;
#else
const int polOrder = POLORDER;
#endif

///**
//  \brief  This represents the operation \f$fv\f$.

//          \f$f\f$ is a given right hand side (in this case 1) and \f$v\f$ may be a local function, i.e. a
//          testfunction.
//  \tparam FunctionSpaceImp
//          Type of the function space, where \f$f\f$ and \f$v\f$ live in.
//  **/
//template< class FunctionSpaceImp >
//class ProductOperation
//  : public Dune::Functionals::LocalOperation::Interface< FunctionSpaceImp >
//{
//public:

//  typedef FunctionSpaceImp
//    FunctionSpaceType;

//  typedef typename FunctionSpaceType::RangeFieldType
//    RangeFieldType;

//  typedef typename FunctionSpaceType::RangeType
//    RangeType;

//  /**
//    \brief      Evaluates \f$f(x)v(x)\f$ for a given local point \f$x\f$.

//    \tparam     LocalTestFunctionType
//                Type of the local function \f$v\f$, i.e. Dune::LocalFunction.
//    \tparam     LocalPointType
//                Type of the local point \f$x\f$, i.e. Dune::FieldVector.
//    \param[in]  localTestFunction
//                The local function \f$v\f$.
//    \param[in]  localPoint
//                The local point \f$x\f$. This point is local in the sense, that this is a point on a reference
//                element.
//    \return     \f$f(x)v(x)\f$
//    **/
//  template< class LocalTestFunctionType, class LocalPointType >
//  RangeFieldType evaluate(  const LocalTestFunctionType& localTestFunction,
//                            const LocalPointType& localPoint ) const
//  {
//    // init return value
//    RangeFieldType ret = 0.0;

//    // evaluate local function
//    RangeType localTestFunctionValue( 0.0 );
//    localTestFunction.evaluate( localPoint, localTestFunctionValue );

//    // 1.0 * v(x)
//    ret = 1.0 * localTestFunctionValue;

//    // return
//    return ret;
//  }

//}; // end class ProductOperation

///**
//  \brief  This represents the operation \f$a\nabla u \nabla v\f$.

//          \f$a\f$ is a given scalar function (in this case 1) and \f$u\f$ and \f$u\f$ may be local functions, i.e.
//          ansatz- and testfunctions.
//  \tparam FunctionSpaceImp
//          Type of the function space, where \f$f\f$, \f$u\f$ and \f$v\f$ live in.
//  **/
//template< class FunctionSpaceImp >
//class EllipticOperation
//  : public Dune::Functionals::LocalOperation::Interface< FunctionSpaceImp >
//{
//public:

//  typedef FunctionSpaceImp
//    FunctionSpaceType;

//  typedef Dune::Functionals::LocalOperation::Interface< FunctionSpaceImp >
//    BaseType;

//  typedef typename FunctionSpaceType::RangeFieldType
//    RangeFieldType;

//  typedef typename FunctionSpaceType::RangeType
//    RangeType;

//  typedef typename FunctionSpaceType::JacobianRangeType
//    JacobianRangeType;

//  /**
//    * \brief      Evaluates \f$a(x)\nabla u(x) \nabla v(x)\f$ for a given local point \f$x\f$.
//    *
//    * \tparam     LocalAnsatzFunctionType
//    *             Type of the local ansatz function \f$u\f$, i.e. Dune::LocalFunction.
//    * \tparam     LocalTestFunctionType
//    *             Type of the local test function \f$v\f$, i.e. Dune::LocalFunction.
//    * \tparam     LocalPointType
//    *             Type of the local point \f$x\f$, i.e. Dune::FieldVector.
//    * \param[in]  localAnsatzFunction
//    *             The local function \f$u\f$.
//    * \param[in]  localTestFunction
//    *             The local function \f$v\f$.
//    * \param[in]  localPoint
//    *             The local point \f$x\f$. This point is local in the sense, that this is a point on a reference
//    *             element.
//    * \return     \f$a(x)\nabla u(x) \nabla v(x)\f$
//    **/
//  template< class LocalAnsatzFunctionType, class LocalTestFunctionType, class LocalPointType >
//  RangeFieldType evaluate(  const LocalAnsatzFunctionType& localAnsatzFunction,
//                            const LocalTestFunctionType& localTestFunction,
//                            const LocalPointType& localPoint ) const
//  {
//    // init return value
//    RangeFieldType ret = 0.0;

//    // evaluate first gradient
//    JacobianRangeType gradientLocalAnsatzFunction( 0.0 );
//    localAnsatzFunction.jacobian( localPoint, gradientLocalAnsatzFunction );

//    // evaluate second gradient
//    JacobianRangeType gradientLocalTestFunction( 0.0 );
//    localTestFunction.jacobian( localPoint, gradientLocalTestFunction );

//    const RangeFieldType product = gradientLocalAnsatzFunction[0] * gradientLocalTestFunction[0];

//    // 1.0 * \gradient u(x) \gradient v(x)
//    ret = 1.0 * product;

//    // return
//    return ret;
//  }

//}; // end class EllipticOperation

int main( int argc, char** argv )
{
  try{

    // MPI manager
    Dune::MPIManager::initialize ( argc, argv );

    // grid
    static const unsigned int dimRange = 1;

    typedef Dune::GridSelector::GridType
      GridType;

    typedef Dune::AdaptiveLeafGridPart< GridType >
      GridPartType;

    Dune::GridPtr< GridType > gridPtr( "../macrogrids/unitcube2.dgf" );

    GridPartType gridPart( *gridPtr );

    // function spaces and functions
    typedef Dune::FunctionSpace< double, double, GridType::dimension, dimRange >
      FunctionSpaceType;

//    typedef Dune::Function< double, double >
//      FunctionType;

//    // local operations
//    typedef ProductOperation< FunctionSpaceType >
//      ProductOperationType;

//    ProductOperationType productOperation;

//    typedef EllipticOperation< FunctionSpaceType >
//      EllipticOperationType;

//    EllipticOperationType ellipticOperation;

//    // integration
//    typedef LocalOperation::Integrator::Codim0< FunctionSpaceType, ProductOperationType >
//      ProductIntegratorType;

//    ProductIntegratorType productIntegrator( productOperation );

//    typedef LocalOperation::Integrator::Codim0< FunctionSpaceType, EllipticOperationType >
//      EllipticIntegratorType;

//    EllipticIntegratorType ellipticIntegrator( ellipticOperation );

    // discrete function space
    typedef DiscreteFunctionSpace::ContinuousFiniteElement< FunctionSpaceType, GridPartType, polOrder >
      DiscreteH1Type;

    const DiscreteH1Type discreteH1( gridPart );

    typedef DiscreteFunctionSpace::Subspace::Linear::DirichletZero< DiscreteH1Type >
      DiscreteH10Type;

    const DiscreteH10Type discreteH10( discreteH1 );

    typedef DiscreteFunctionSpace::Subspace::Affine::Dirichlet< DiscreteH10Type >
      DiscreteH1GType;

    const DiscreteH1GType discreteH1G( discreteH10, "[1.0;1.0;1.0]" );

//    // operator and functional
//    typedef Operator::Linear< EllipticIntegratorType, DiscreteH1Type >
//      FEMellipticOperatorType;

//    FEMellipticOperatorType femEllipticOperator( ellipticIntegrator, discreteH1 );

//    typedef Functional::FiniteElementLOP< DiscreteH1Type, ProductIntegratorType >
//      FEMrhsFunctionalType;

//    FEMrhsFunctionalType femRhsFunctional( discreteH1, productIntegrator );

//    // matrix, rhs and solution storage
//    typedef Dune::FieldMatrix< double, dimRange, dimRange >
//      FieldMatrixType;

//    typedef Container::MatrixFactory< Dune::BCRSMatrix< FieldMatrixType > >
//      MatrixFactoryType;

//    typedef MatrixFactoryType::ContainerType
//      MatrixContainer;

//    typedef MatrixFactoryType::AutoPtrType
//      MatrixContainerPtr;

//    typedef Container::VectorFactory< Dune::BlockVector< Dune::FieldVector< double, 1 > > >
//      VectorFactoryType;

//    typedef VectorFactoryType::ContainerType
//      VectorContainer;

//    typedef VectorFactoryType::AutoPtrType
//      VectorContainerPtr;

//    MatrixContainerPtr A  = MatrixFactoryType::create( discreteH10 );
//    VectorContainerPtr F  = VectorFactoryType::create( discreteH10 );
//    VectorContainerPtr u0 = VectorFactoryType::create( discreteH10 );

//    // assembler
//    typedef Assembler::FiniteElement< MatrixContainer, VectorContainer >
//      Assembler;

//    Assembler::assembleMatrix( femEllipticOperator, *A );
//    Assembler::applyMatrixConstraints( discreteH10, *A );

//    Assembler::assembleVector( femRhsFunctional, *F );
//    Assembler::applyVectorConstraints( discreteH10, *F );

//    // preconditioner and solver
//    typedef Dune::MatrixAdapter< MatrixContainer, VectorContainer, VectorContainer >
//      MatrixAdapterType;

//    MatrixAdapterType op( *A );

//    typedef Dune::SeqILU0< MatrixContainer, VectorContainer, VectorContainer, 1 >
//      SeqILU0Type;

//    SeqILU0Type prec( *A, 1.0 );

//    typedef Dune::CGSolver< VectorContainer >
//      CG;

//    CG cg( op, prec, 1e-4, 100, 2 );

//    Dune::InverseOperatorResult res;

//    // u_0 = A^(-1) ( F - G )
//    cg.apply( *u0, *F, res );

//    // postprocessing
//    DiscreteFunctionType solution = Dune::FemTools::discreteFunctionFactory< DiscreteFunctionType >( discreteH1, *u0 );
//    Dune::FemTools::writeDiscreteFunctionToVTK( solution, "solution" );

    return 0;
  }
  catch (Dune::Exception &e){
    std::cerr << "Dune reported error: " << e << std::endl;
  }
  catch (...){
    std::cerr << "Unknown exception thrown!" << std::endl;
  }
}
<commit_msg>added dimension dependent choice of dgf file in example<commit_after>/**
  \file   main.cc
  \brief  Main file fir the finite element example.
  **/
// disable warnings about problems in dune headers
#include <dune/fem-tools/header/disablewarnings.hh>

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <iostream>
#include <vector>

// dune-common includes
#include <dune/common/exceptions.hh>
#include <dune/common/fmatrix.hh>

// dune-grid includes
#include <dune/grid/utility/gridtype.hh>

// dune-istl includes
#include <dune/istl/bcrsmatrix.hh>
#include <dune/istl/solvers.hh>
#include <dune/istl/bvector.hh>

// dune-fem includes
#include <dune/fem/misc/mpimanager.hh>
//#include <dune/fem/gridpart/gridpart.hh>
//#include <dune/fem/storage/vector.hh>
//#include <dune/fem/function/adaptivefunction/adaptivefunction.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>

// reenable warnings
#include <dune/fem-tools/header/enablewarnings.hh>

// dune-functionals includes
#include <dune/functionals/discretefunctionspace/finiteelement.hh>
#include <dune/functionals/discretefunctionspace/subspace/linear.hh>
#include <dune/functionals/discretefunctionspace/subspace/affine.hh>
//#include <dune/fem/localoperation/interface.hh>
//#include <dune/fem/localoperation/integrator.hh>
//#include <dune/fem/subspace/subspaces.hh>
//#include <dune/fem/operator/linear.hh>
//#include <dune/fem/functional/finiteelement.hh>
//#include <dune/fem/container/factory.hh>
//#include <dune/fem/solver/femassembler.hh>

// dune-fem-tools includes
#include <dune/fem-tools/common/string.hh>
//#include <dune/fem-tools/function/functiontools.hh>
//#include <dune/fem-tools/space/projection.hh>

using namespace Dune::Functionals;

#ifndef POLORDER
const int polOrder = 1;
#else
const int polOrder = POLORDER;
#endif

///**
//  \brief  This represents the operation \f$fv\f$.

//          \f$f\f$ is a given right hand side (in this case 1) and \f$v\f$ may be a local function, i.e. a
//          testfunction.
//  \tparam FunctionSpaceImp
//          Type of the function space, where \f$f\f$ and \f$v\f$ live in.
//  **/
//template< class FunctionSpaceImp >
//class ProductOperation
//  : public Dune::Functionals::LocalOperation::Interface< FunctionSpaceImp >
//{
//public:

//  typedef FunctionSpaceImp
//    FunctionSpaceType;

//  typedef typename FunctionSpaceType::RangeFieldType
//    RangeFieldType;

//  typedef typename FunctionSpaceType::RangeType
//    RangeType;

//  /**
//    \brief      Evaluates \f$f(x)v(x)\f$ for a given local point \f$x\f$.

//    \tparam     LocalTestFunctionType
//                Type of the local function \f$v\f$, i.e. Dune::LocalFunction.
//    \tparam     LocalPointType
//                Type of the local point \f$x\f$, i.e. Dune::FieldVector.
//    \param[in]  localTestFunction
//                The local function \f$v\f$.
//    \param[in]  localPoint
//                The local point \f$x\f$. This point is local in the sense, that this is a point on a reference
//                element.
//    \return     \f$f(x)v(x)\f$
//    **/
//  template< class LocalTestFunctionType, class LocalPointType >
//  RangeFieldType evaluate(  const LocalTestFunctionType& localTestFunction,
//                            const LocalPointType& localPoint ) const
//  {
//    // init return value
//    RangeFieldType ret = 0.0;

//    // evaluate local function
//    RangeType localTestFunctionValue( 0.0 );
//    localTestFunction.evaluate( localPoint, localTestFunctionValue );

//    // 1.0 * v(x)
//    ret = 1.0 * localTestFunctionValue;

//    // return
//    return ret;
//  }

//}; // end class ProductOperation

///**
//  \brief  This represents the operation \f$a\nabla u \nabla v\f$.

//          \f$a\f$ is a given scalar function (in this case 1) and \f$u\f$ and \f$u\f$ may be local functions, i.e.
//          ansatz- and testfunctions.
//  \tparam FunctionSpaceImp
//          Type of the function space, where \f$f\f$, \f$u\f$ and \f$v\f$ live in.
//  **/
//template< class FunctionSpaceImp >
//class EllipticOperation
//  : public Dune::Functionals::LocalOperation::Interface< FunctionSpaceImp >
//{
//public:

//  typedef FunctionSpaceImp
//    FunctionSpaceType;

//  typedef Dune::Functionals::LocalOperation::Interface< FunctionSpaceImp >
//    BaseType;

//  typedef typename FunctionSpaceType::RangeFieldType
//    RangeFieldType;

//  typedef typename FunctionSpaceType::RangeType
//    RangeType;

//  typedef typename FunctionSpaceType::JacobianRangeType
//    JacobianRangeType;

//  /**
//    * \brief      Evaluates \f$a(x)\nabla u(x) \nabla v(x)\f$ for a given local point \f$x\f$.
//    *
//    * \tparam     LocalAnsatzFunctionType
//    *             Type of the local ansatz function \f$u\f$, i.e. Dune::LocalFunction.
//    * \tparam     LocalTestFunctionType
//    *             Type of the local test function \f$v\f$, i.e. Dune::LocalFunction.
//    * \tparam     LocalPointType
//    *             Type of the local point \f$x\f$, i.e. Dune::FieldVector.
//    * \param[in]  localAnsatzFunction
//    *             The local function \f$u\f$.
//    * \param[in]  localTestFunction
//    *             The local function \f$v\f$.
//    * \param[in]  localPoint
//    *             The local point \f$x\f$. This point is local in the sense, that this is a point on a reference
//    *             element.
//    * \return     \f$a(x)\nabla u(x) \nabla v(x)\f$
//    **/
//  template< class LocalAnsatzFunctionType, class LocalTestFunctionType, class LocalPointType >
//  RangeFieldType evaluate(  const LocalAnsatzFunctionType& localAnsatzFunction,
//                            const LocalTestFunctionType& localTestFunction,
//                            const LocalPointType& localPoint ) const
//  {
//    // init return value
//    RangeFieldType ret = 0.0;

//    // evaluate first gradient
//    JacobianRangeType gradientLocalAnsatzFunction( 0.0 );
//    localAnsatzFunction.jacobian( localPoint, gradientLocalAnsatzFunction );

//    // evaluate second gradient
//    JacobianRangeType gradientLocalTestFunction( 0.0 );
//    localTestFunction.jacobian( localPoint, gradientLocalTestFunction );

//    const RangeFieldType product = gradientLocalAnsatzFunction[0] * gradientLocalTestFunction[0];

//    // 1.0 * \gradient u(x) \gradient v(x)
//    ret = 1.0 * product;

//    // return
//    return ret;
//  }

//}; // end class EllipticOperation

int main( int argc, char** argv )
{
  try{

    // MPI manager
    Dune::MPIManager::initialize ( argc, argv );

    // grid
    static const unsigned int dimRange = 1;

    typedef Dune::GridSelector::GridType
      GridType;

    typedef Dune::AdaptiveLeafGridPart< GridType >
      GridPartType;

    const std::string dgfFilename = "../macrogrids/unitcube" + Dune::FemTools::String::toString( GRIDDIM ) + ".dgf";

    Dune::GridPtr< GridType > gridPtr( dgfFilename );

    GridPartType gridPart( *gridPtr );

    // function spaces and functions
    typedef Dune::FunctionSpace< double, double, GridType::dimension, dimRange >
      FunctionSpaceType;

//    typedef Dune::Function< double, double >
//      FunctionType;

//    // local operations
//    typedef ProductOperation< FunctionSpaceType >
//      ProductOperationType;

//    ProductOperationType productOperation;

//    typedef EllipticOperation< FunctionSpaceType >
//      EllipticOperationType;

//    EllipticOperationType ellipticOperation;

//    // integration
//    typedef LocalOperation::Integrator::Codim0< FunctionSpaceType, ProductOperationType >
//      ProductIntegratorType;

//    ProductIntegratorType productIntegrator( productOperation );

//    typedef LocalOperation::Integrator::Codim0< FunctionSpaceType, EllipticOperationType >
//      EllipticIntegratorType;

//    EllipticIntegratorType ellipticIntegrator( ellipticOperation );

    // discrete function space
    typedef DiscreteFunctionSpace::ContinuousFiniteElement< FunctionSpaceType, GridPartType, polOrder >
      DiscreteH1Type;

    const DiscreteH1Type discreteH1( gridPart );

    typedef DiscreteFunctionSpace::Subspace::Linear::DirichletZero< DiscreteH1Type >
      DiscreteH10Type;

    const DiscreteH10Type discreteH10( discreteH1 );

    typedef DiscreteFunctionSpace::Subspace::Affine::Dirichlet< DiscreteH10Type >
      DiscreteH1GType;

    const DiscreteH1GType discreteH1G( discreteH10, "[1.0;1.0;1.0]" );

//    // operator and functional
//    typedef Operator::Linear< EllipticIntegratorType, DiscreteH1Type >
//      FEMellipticOperatorType;

//    FEMellipticOperatorType femEllipticOperator( ellipticIntegrator, discreteH1 );

//    typedef Functional::FiniteElementLOP< DiscreteH1Type, ProductIntegratorType >
//      FEMrhsFunctionalType;

//    FEMrhsFunctionalType femRhsFunctional( discreteH1, productIntegrator );

//    // matrix, rhs and solution storage
//    typedef Dune::FieldMatrix< double, dimRange, dimRange >
//      FieldMatrixType;

//    typedef Container::MatrixFactory< Dune::BCRSMatrix< FieldMatrixType > >
//      MatrixFactoryType;

//    typedef MatrixFactoryType::ContainerType
//      MatrixContainer;

//    typedef MatrixFactoryType::AutoPtrType
//      MatrixContainerPtr;

//    typedef Container::VectorFactory< Dune::BlockVector< Dune::FieldVector< double, 1 > > >
//      VectorFactoryType;

//    typedef VectorFactoryType::ContainerType
//      VectorContainer;

//    typedef VectorFactoryType::AutoPtrType
//      VectorContainerPtr;

//    MatrixContainerPtr A  = MatrixFactoryType::create( discreteH10 );
//    VectorContainerPtr F  = VectorFactoryType::create( discreteH10 );
//    VectorContainerPtr u0 = VectorFactoryType::create( discreteH10 );

//    // assembler
//    typedef Assembler::FiniteElement< MatrixContainer, VectorContainer >
//      Assembler;

//    Assembler::assembleMatrix( femEllipticOperator, *A );
//    Assembler::applyMatrixConstraints( discreteH10, *A );

//    Assembler::assembleVector( femRhsFunctional, *F );
//    Assembler::applyVectorConstraints( discreteH10, *F );

//    // preconditioner and solver
//    typedef Dune::MatrixAdapter< MatrixContainer, VectorContainer, VectorContainer >
//      MatrixAdapterType;

//    MatrixAdapterType op( *A );

//    typedef Dune::SeqILU0< MatrixContainer, VectorContainer, VectorContainer, 1 >
//      SeqILU0Type;

//    SeqILU0Type prec( *A, 1.0 );

//    typedef Dune::CGSolver< VectorContainer >
//      CG;

//    CG cg( op, prec, 1e-4, 100, 2 );

//    Dune::InverseOperatorResult res;

//    // u_0 = A^(-1) ( F - G )
//    cg.apply( *u0, *F, res );

//    // postprocessing
//    DiscreteFunctionType solution = Dune::FemTools::discreteFunctionFactory< DiscreteFunctionType >( discreteH1, *u0 );
//    Dune::FemTools::writeDiscreteFunctionToVTK( solution, "solution" );

    return 0;
  }
  catch (Dune::Exception &e){
    std::cerr << "Dune reported error: " << e << std::endl;
  }
  catch (...){
    std::cerr << "Unknown exception thrown!" << std::endl;
  }
}
<|endoftext|>


<commit_before>#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "util/murmur_hash.hh"

#include <iostream>

#include <string.h>
#include <stdlib.h>
#include <jni.h>
#include <pthread.h>

// Grr.  Everybody's compiler is slightly different and I'm trying to not depend on boost.
#include <ext/hash_map>

// This is needed to compile on OS X Lion / gcc 4.2.1
namespace __gnu_cxx {
template<>
struct hash<unsigned long long int>
{
	size_t
	operator()(unsigned long long int __x) const
			{
		return __x;
	}
};
}

// Verify that jint and lm::ngram::WordIndex are the same size. If this breaks
// for you, there's a need to revise probString.
namespace {

template<bool> struct StaticCheck {};

template<> struct StaticCheck<true> {
	typedef bool StaticAssertionPassed;
};

typedef StaticCheck<sizeof(jint) == sizeof(lm::WordIndex)>::StaticAssertionPassed FloatSize;

// Vocab ids above what the vocabulary knows about are unknown and should
// be mapped to that.
void MapArray(const std::vector<lm::WordIndex>& map, jint *begin, jint *end) {
	for (jint *i = begin; i < end; ++i) {
		*i = map[*i];
	}
}

char *PieceCopy(const StringPiece &str) {
	char *ret = (char*) malloc(str.size() + 1);
	memcpy(ret, str.data(), str.size());
	ret[str.size()] = 0;
	return ret;
}

// Rather than handle several different instantiations over JNI, we'll just
// do virtual calls C++-side.
class VirtualBase {
public:
	virtual ~VirtualBase() {
	}

	virtual float Prob(jint *begin, jint *end) const = 0;

	virtual float ProbString(jint * const begin, jint * const end,
			jint start) const = 0;

	virtual uint8_t Order() const = 0;

	virtual bool RegisterWord(const StringPiece& word, const int joshua_id) = 0;

protected:
	VirtualBase() {
	}

private:
};

template<class Model> class VirtualImpl: public VirtualBase {
public:
	VirtualImpl(const char *name) : m_(name) {
		// Insert unknown id mapping.
		map_.push_back(0);
	}

	~VirtualImpl() {
	}

	float Prob(jint * const begin, jint * const end) const {
		MapArray(map_, begin, end);

		std::reverse(begin, end - 1);
		lm::ngram::State ignored;
		return
				m_.FullScoreForgotState(
					reinterpret_cast<const lm::WordIndex*>(begin),
					reinterpret_cast<const lm::WordIndex*>(end - 1), *(end - 1),
					ignored).prob;
	}

	float ProbString(jint * const begin, jint * const end, jint start) const {
		MapArray(map_, begin, end);

		float prob;
		lm::ngram::State state;
		if (start == 0) {
			prob = 0;
			state = m_.NullContextState();
		} else {
			std::reverse(begin, begin + start);
			prob = m_.FullScoreForgotState(
					reinterpret_cast<const lm::WordIndex*>(begin),
					reinterpret_cast<const lm::WordIndex*>(begin + start), begin[start],
					state).prob;
			++start;
		}
		lm::ngram::State state2;
		for (const jint *i = begin + start;;) {
			if (i >= end)
				break;
			float got = m_.Score(state, *i, state2);
      i++;
			prob += got;
			if (i >= end)
				break;
			got = m_.Score(state2, *i, state);
      i++;
			prob += got;
		}
		return prob;
	}

	uint8_t Order() const {
		return m_.Order();
	}

	bool RegisterWord(const StringPiece& word, const int joshua_id) {
		if (map_.size() <= joshua_id) {
			map_.resize(joshua_id + 1, 0);
		}
		bool already_present = false;
		if (map_[joshua_id] != 0)
			already_present = true;
		map_[joshua_id] = m_.GetVocabulary().Index(word);
		return already_present;
	}

private:
	Model m_;
	std::vector<lm::WordIndex> map_;
};

VirtualBase *ConstructModel(const char *file_name) {
	using namespace lm::ngram;
	ModelType model_type;
	if (!RecognizeBinary(file_name, model_type))
		model_type = HASH_PROBING;
	switch (model_type) {
	case HASH_PROBING:
		return new VirtualImpl<ProbingModel>(file_name);
	case TRIE_SORTED:
		return new VirtualImpl<TrieModel>(file_name);
	case ARRAY_TRIE_SORTED:
		return new VirtualImpl<ArrayTrieModel>(file_name);
	case QUANT_TRIE_SORTED:
		return new VirtualImpl<QuantTrieModel>(file_name);
	case QUANT_ARRAY_TRIE_SORTED:
		return new VirtualImpl<QuantArrayTrieModel>(file_name);
	default:
		UTIL_THROW(
				lm::FormatLoadException,
				"Unrecognized file format " << (unsigned) model_type << " in file "
						<< file_name);
	}
}

} // namespace

extern "C" {

JNIEXPORT jlong JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_construct(
		JNIEnv *env, jclass, jstring file_name) {
	const char *str = env->GetStringUTFChars(file_name, 0);
	if (!str)
		return 0;
	jlong ret;
	try {
		ret = reinterpret_cast<jlong>(ConstructModel(str));
	} catch (std::exception &e) {
		std::cerr << e.what() << std::endl;
		abort();
	}
	env->ReleaseStringUTFChars(file_name, str);
	return ret;
}

JNIEXPORT void JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_destroy(
		JNIEnv *env, jclass, jlong pointer) {
	delete reinterpret_cast<VirtualBase*>(pointer);
}

JNIEXPORT jint JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_order(
		JNIEnv *env, jclass, jlong pointer) {
	return reinterpret_cast<VirtualBase*>(pointer)->Order();
}

JNIEXPORT jboolean JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_registerWord(
		JNIEnv *env, jclass, jlong pointer, jstring word, jint id) {
	const char *str = env->GetStringUTFChars(word, 0);
	if (!str)
		return false;
	jint ret;
	try {
		ret = reinterpret_cast<VirtualBase*>(pointer)->RegisterWord(str, id);
	} catch (std::exception &e) {
		std::cerr << e.what() << std::endl;
		abort();
	}
	env->ReleaseStringUTFChars(word, str);
	return ret;
}

JNIEXPORT jfloat JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_prob(
		JNIEnv *env, jclass, jlong pointer, jintArray arr) {
	jint length = env->GetArrayLength(arr);
	if (length <= 0)
		return 0.0;
	// GCC only.
	jint values[length];
	env->GetIntArrayRegion(arr, 0, length, values);

	return reinterpret_cast<const VirtualBase*>(pointer)->Prob(values,
			values + length);
}

JNIEXPORT jfloat JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_probString(
		JNIEnv *env, jclass, jlong pointer, jintArray arr, jint start) {
	jint length = env->GetArrayLength(arr);
	if (length <= start)
		return 0.0;
	// GCC only.
	jint values[length];
	env->GetIntArrayRegion(arr, 0, length, values);

	return reinterpret_cast<const VirtualBase*>(pointer)->ProbString(values,
			values + length, start);
}

} // extern
<commit_msg>Support rest with probing<commit_after>#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "util/murmur_hash.hh"

#include <iostream>

#include <string.h>
#include <stdlib.h>
#include <jni.h>
#include <pthread.h>

// Grr.  Everybody's compiler is slightly different and I'm trying to not depend on boost.
#include <ext/hash_map>

// This is needed to compile on OS X Lion / gcc 4.2.1
namespace __gnu_cxx {
template<>
struct hash<unsigned long long int>
{
	size_t
	operator()(unsigned long long int __x) const
			{
		return __x;
	}
};
}

// Verify that jint and lm::ngram::WordIndex are the same size. If this breaks
// for you, there's a need to revise probString.
namespace {

template<bool> struct StaticCheck {};

template<> struct StaticCheck<true> {
	typedef bool StaticAssertionPassed;
};

typedef StaticCheck<sizeof(jint) == sizeof(lm::WordIndex)>::StaticAssertionPassed FloatSize;

// Vocab ids above what the vocabulary knows about are unknown and should
// be mapped to that.
void MapArray(const std::vector<lm::WordIndex>& map, jint *begin, jint *end) {
	for (jint *i = begin; i < end; ++i) {
		*i = map[*i];
	}
}

char *PieceCopy(const StringPiece &str) {
	char *ret = (char*) malloc(str.size() + 1);
	memcpy(ret, str.data(), str.size());
	ret[str.size()] = 0;
	return ret;
}

// Rather than handle several different instantiations over JNI, we'll just
// do virtual calls C++-side.
class VirtualBase {
public:
	virtual ~VirtualBase() {
	}

	virtual float Prob(jint *begin, jint *end) const = 0;

	virtual float ProbString(jint * const begin, jint * const end,
			jint start) const = 0;

	virtual uint8_t Order() const = 0;

	virtual bool RegisterWord(const StringPiece& word, const int joshua_id) = 0;

protected:
	VirtualBase() {
	}

private:
};

template<class Model> class VirtualImpl: public VirtualBase {
public:
	VirtualImpl(const char *name) : m_(name) {
		// Insert unknown id mapping.
		map_.push_back(0);
	}

	~VirtualImpl() {
	}

	float Prob(jint * const begin, jint * const end) const {
		MapArray(map_, begin, end);

		std::reverse(begin, end - 1);
		lm::ngram::State ignored;
		return
				m_.FullScoreForgotState(
					reinterpret_cast<const lm::WordIndex*>(begin),
					reinterpret_cast<const lm::WordIndex*>(end - 1), *(end - 1),
					ignored).prob;
	}

	float ProbString(jint * const begin, jint * const end, jint start) const {
		MapArray(map_, begin, end);

		float prob;
		lm::ngram::State state;
		if (start == 0) {
			prob = 0;
			state = m_.NullContextState();
		} else {
			std::reverse(begin, begin + start);
			prob = m_.FullScoreForgotState(
					reinterpret_cast<const lm::WordIndex*>(begin),
					reinterpret_cast<const lm::WordIndex*>(begin + start), begin[start],
					state).prob;
			++start;
		}
		lm::ngram::State state2;
		for (const jint *i = begin + start;;) {
			if (i >= end)
				break;
			float got = m_.Score(state, *i, state2);
      i++;
			prob += got;
			if (i >= end)
				break;
			got = m_.Score(state2, *i, state);
      i++;
			prob += got;
		}
		return prob;
	}

	uint8_t Order() const {
		return m_.Order();
	}

	bool RegisterWord(const StringPiece& word, const int joshua_id) {
		if (map_.size() <= joshua_id) {
			map_.resize(joshua_id + 1, 0);
		}
		bool already_present = false;
		if (map_[joshua_id] != 0)
			already_present = true;
		map_[joshua_id] = m_.GetVocabulary().Index(word);
		return already_present;
	}

private:
	Model m_;
	std::vector<lm::WordIndex> map_;
};

VirtualBase *ConstructModel(const char *file_name) {
	using namespace lm::ngram;
	ModelType model_type;
	if (!RecognizeBinary(file_name, model_type))
		model_type = HASH_PROBING;
	switch (model_type) {
	case PROBING:
		return new VirtualImpl<ProbingModel>(file_name);
	case REST_PROBING:
		return new VirtualImpl<RestProbingModel>(file_name);
	case TRIE:
		return new VirtualImpl<TrieModel>(file_name);
	case ARRAY_TRIE:
		return new VirtualImpl<ArrayTrieModel>(file_name);
	case QUANT_TRIE:
		return new VirtualImpl<QuantTrieModel>(file_name);
	case QUANT_ARRAY_TRIE:
		return new VirtualImpl<QuantArrayTrieModel>(file_name);
	default:
		UTIL_THROW(
				lm::FormatLoadException,
				"Unrecognized file format " << (unsigned) model_type << " in file "
						<< file_name);
	}
}

} // namespace

extern "C" {

JNIEXPORT jlong JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_construct(
		JNIEnv *env, jclass, jstring file_name) {
	const char *str = env->GetStringUTFChars(file_name, 0);
	if (!str)
		return 0;
	jlong ret;
	try {
		ret = reinterpret_cast<jlong>(ConstructModel(str));
	} catch (std::exception &e) {
		std::cerr << e.what() << std::endl;
		abort();
	}
	env->ReleaseStringUTFChars(file_name, str);
	return ret;
}

JNIEXPORT void JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_destroy(
		JNIEnv *env, jclass, jlong pointer) {
	delete reinterpret_cast<VirtualBase*>(pointer);
}

JNIEXPORT jint JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_order(
		JNIEnv *env, jclass, jlong pointer) {
	return reinterpret_cast<VirtualBase*>(pointer)->Order();
}

JNIEXPORT jboolean JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_registerWord(
		JNIEnv *env, jclass, jlong pointer, jstring word, jint id) {
	const char *str = env->GetStringUTFChars(word, 0);
	if (!str)
		return false;
	jint ret;
	try {
		ret = reinterpret_cast<VirtualBase*>(pointer)->RegisterWord(str, id);
	} catch (std::exception &e) {
		std::cerr << e.what() << std::endl;
		abort();
	}
	env->ReleaseStringUTFChars(word, str);
	return ret;
}

JNIEXPORT jfloat JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_prob(
		JNIEnv *env, jclass, jlong pointer, jintArray arr) {
	jint length = env->GetArrayLength(arr);
	if (length <= 0)
		return 0.0;
	// GCC only.
	jint values[length];
	env->GetIntArrayRegion(arr, 0, length, values);

	return reinterpret_cast<const VirtualBase*>(pointer)->Prob(values,
			values + length);
}

JNIEXPORT jfloat JNICALL Java_joshua_decoder_ff_lm_kenlm_jni_KenLM_probString(
		JNIEnv *env, jclass, jlong pointer, jintArray arr, jint start) {
	jint length = env->GetArrayLength(arr);
	if (length <= start)
		return 0.0;
	// GCC only.
	jint values[length];
	env->GetIntArrayRegion(arr, 0, length, values);

	return reinterpret_cast<const VirtualBase*>(pointer)->ProbString(values,
			values + length, start);
}

} // extern
<|endoftext|>