<commit_before>/*
** Copyright 1993 by Miron Livny, and Mike Litzkow
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author:  Mike Litzkow
**
*/

#if defined(Solaris)
#include "condor_fix_timeval.h"
#if !defined(Solaris251)
#include </usr/ucbinclude/sys/rusage.h>
#endif
#endif

#if defined(IRIX53)
#include "condor_fix_unistd.h"
#endif

#define _POSIX_SOURCE

#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_jobqueue.h"
#include "condor_network.h"
#include "condor_io.h"
#include "sched.h"
#if DBM_QUEUE
#include "proc_obj.h"
#endif
#include "alloc.h"

static char *_FileName_ = __FILE__;		/* Used by EXCEPT (see except.h)     */

extern "C" char *get_schedd_addr(const char *);

#if DBM_QUEUE
DBM		*Q, *OpenJobQueue();
#else
#include "condor_qmgr.h"
#endif

char	*MyName;
#if DBM_QUEUE
char	*Spool;
#endif
BOOLEAN	TroubleReported;
BOOLEAN All;
static BOOLEAN Force = FALSE;
#if DBM_QUEUE
ProcFilter	*PFilter = new ProcFilter();
#endif

	// Prototypes of local interest
#if DBM_QUEUE
void do_it( ProcObj * );
void init_params();
#else
void ProcArg(const char*);
#endif
void notify_schedd( int cluster, int proc );
void usage();
#if DBM_QUEUE
extern "C" BOOLEAN	xdr_proc_id(XDR *, PROC_ID *);
#endif

#if !DBM_QUEUE
extern "C" int gethostname(char*, int);
#endif

char				hostname[512];

void
usage()
{
	fprintf( stderr,
		"Usage: %s [-r host] { -a | cluster | cluster.proc | user } ... \n",
		MyName
	);
	exit( 1 );
}

int
main( int argc, char *argv[] )
{
#if DBM_QUEUE
	char	queue_name[_POSIX_PATH_MAX];
#endif
	char	*arg;
#if DBM_QUEUE
	List<ProcObj>	*proc_list;
	ProcObj			*p;
#else
	char*				args[argc - 1];			// args of jobs to be deleted
	int					nArgs = 0;				// number of args to be deleted
	int					i;
	Qmgr_connection*	q;
#endif

	MyName = argv[0];

	config( 0 );
#if DBM_QUEUE
	init_params();
#endif

	if( argc < 2 ) {
		usage();
	}

	hostname[0] = '\0';
	for( argv++; arg = *argv; argv++ ) {
		if( arg[0] == '-' && arg[1] == 'a' ) {
			All = TRUE;
		} else {
			if( All ) {
				usage();
			}
			if ( arg[0] == '-' && arg[1] == 'f' ) {
				// "-f" is the undocumented "force" feature, which rips
				// out the job from the queue without any checks except for
				// permission.  -Todd 10/95
				Force = TRUE;
			} else
			if ( arg[0] == '-' && arg[1] == 'r' ) {
				// use the given name as the host name to connect to
				argv++;
				strcpy (hostname, *argv);
			} else {
			#if DBM_QUEUE
				if( !PFilter->Append(arg) ) {
					usage();
				}
			#else
				args[nArgs] = arg;
				nArgs++;
			#endif
			}
		}
	}

		/* Open job queue */
#if DBM_QUEUE
	(void)sprintf( queue_name, "%s/job_queue", Spool );
	if( (Q=OpenJobQueue(queue_name,O_RDWR,0)) == NULL ) {
		EXCEPT( "OpenJobQueue(%s)", queue_name );
	}

		// Create a list of all procs we're interested in
	PFilter->Install();
	proc_list = ProcObj::create_list( Q, ProcFilter::Func );

		// Process the list
	proc_list->Rewind();
	while( p = proc_list->Next() ) {
		do_it( p );
	}

		// Clean up
	LockJobQueue( Q, UNLOCK );
	CloseJobQueue( Q );
	ProcObj::delete_list( proc_list );
	delete PFilter;
#else
	if (hostname[0] == '\0')
	{
		// hostname was not set at command line; obtain from system
		if(gethostname(hostname, 200) < 0)
		{
			EXCEPT("gethostname failed, errno = %d", errno);
		}
	}
	if((q = ConnectQ(hostname)) == 0)
	{
		EXCEPT("Failed to connect to qmgr on host %s", hostname);
	}
	for(i = 0; i < nArgs; i++)
	{
		ProcArg(args[i]);
	}
	DisconnectQ(q);
#endif

#if defined(ALLOC_DEBUG)
	print_alloc_stats();
#endif

	return 0;
}

extern "C" int SetSyscalls( int foo ) { return foo; }

#if DBM_QUEUE
void
init_params()
{
	Spool = param("SPOOL");
	if( Spool == NULL ) {
		EXCEPT( "SPOOL not specified in config file\n" );
	}
}
#endif

void
notify_schedd( int cluster, int proc )
{
	ReliSock	*sock;
	char		*scheddAddr;
	int			cmd;
	PROC_ID		job_id;

	job_id.cluster = cluster;
	job_id.proc = proc;

	if (hostname[0] == '\0')
	{
		// if the hostname was not set at command line, obtain from system
		if( gethostname(hostname,sizeof(hostname)) < 0 ) {
			EXCEPT( "gethostname failed" );
		}
	}

	if ((scheddAddr = get_schedd_addr(hostname)) == NULL)
	{
		EXCEPT("Can't find schedd address on %s\n", hostname);
	}

		/* Connect to the schedd */
	sock = new ReliSock(scheddAddr, SCHED_PORT);
	if(sock->get_file_desc() < 0) {
		if( !TroubleReported ) {
			dprintf( D_ALWAYS, "Warning: can't connect to condor scheduler\n" );
			TroubleReported = 1;
		}
		delete sock;
		return;
	}

	sock->encode();

	cmd = KILL_FRGN_JOB;
	if( !sock->code(cmd) ) {
		dprintf( D_ALWAYS,
			"Warning: can't send KILL_JOB command to condor scheduler\n" );
		delete sock;
		return;
	}

	if( !sock->code(job_id) ) {
		dprintf( D_ALWAYS,
			"Warning: can't send proc_id to condor scheduler\n" );
		delete sock;
		return;
	}

	if( !sock->end_of_message() ) {
		dprintf( D_ALWAYS,
			"Warning: can't send endofrecord to condor scheduler\n" );
		delete sock;
		return;
	}

	dprintf( D_FULLDEBUG, "Sent KILL_FRGN_JOB command to condor scheduler\n" );
	delete sock;
}

#if DBM_QUEUE
void
do_it( ProcObj *p )
{
	PROC_ID	id;

		// Make sure it makes sense to remove the process, unless -f Force command line
		// option is in effect, in which case we trust the user knows better
	if ( Force == FALSE ) {
		switch( p->get_status() ) {
	  	case REMOVED:
	  	case COMPLETED:
	  	case SUBMISSION_ERR:
			return;
		}
	}

	id.cluster = p->get_cluster_id();
	id.proc = p->get_proc_id();

		// Make sure user is allowed to remove it
	if( !p->perm_to_modify() ) {
		fprintf( stderr, "%d.%d: Permission Denied\n", id.cluster, id.proc);
		return;
	}

		// Ok, go ahead and remove it
	TerminateProc( Q, &id, REMOVED );
	notify_schedd( id.cluster, id.proc );
	printf( "Deleted %d.%d\n", id.cluster, id.proc );
}
#else
void ProcArg(const char* arg)
{
	int		c, p;								// cluster/proc #
	char*	tmp;

	if(isdigit(*arg))
	// delete by cluster/proc #
	{
		c = strtol(arg, &tmp, 10);
		if(c <= 0)
		{
			fprintf(stderr, "Invalid cluster # from %s.\n", arg);
			return;
		}
		if(*tmp == '\0')
		// delete the cluster
		{
			if(DestroyCluster(c) < 0)
			{
				fprintf(stderr, "Couldn't find/delete cluster %d.\n", c);
			} else {
			fprintf(stderr, "Cluster %d removed.\n", c);
			}
#ifdef 0
			notify_schedd( c, -1 );
#endif
			return;
		}
		if(*tmp == '.')
		{
			p = strtol(tmp + 1, &tmp, 10);
			if(p < 0)
			{
				fprintf(stderr, "Invalid proc # from %s.\n", arg);
				return;
			}
			if(*tmp == '\0')
			// delete a proc
			{
				if(DestroyProc(c, p) < 0)
				{
					fprintf(stderr, "Couldn't find/delete job %d.%d.\n", c, p);
				} else {
					fprintf(stderr, "Job %d.%d removed.\n", c, p);
				}
#ifdef 0
				notify_schedd( c, p );
#endif
				return;
			}
			fprintf(stderr, "Warning: unrecognized \"%s\" skipped.\n", arg);
			return;
		}
		fprintf(stderr, "Warning: unrecognized \"%s\" skipped.\n", arg);
	}
	else if(isalpha(*arg))
	// delete by user name
	{
		char	constraint[1000];

		sprintf(constraint, "Owner == \"%s\"", arg);
		if(DestroyClusterByConstraint(constraint) < 0)
		{
			fprintf(stderr, "Couldn't find/delete user %s's job(s).\n", arg);
		} else {
			fprintf(stderr, "User %s's job(s) removed.\n", arg);
		}
	}
	else
	{
		fprintf(stderr, "Warning: unrecognized \"%s\" skipped.\n", arg);
	}
}
#endif
<commit_msg>generalized gethostname() prototype since it varies from platform to platform<commit_after>/*
** Copyright 1993 by Miron Livny, and Mike Litzkow
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author:  Mike Litzkow
**
*/

#if defined(Solaris)
#include "condor_fix_timeval.h"
#if !defined(Solaris251)
#include </usr/ucbinclude/sys/rusage.h>
#endif
#endif

#if defined(IRIX53)
#include "condor_fix_unistd.h"
#endif

#define _POSIX_SOURCE

#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_jobqueue.h"
#include "condor_network.h"
#include "condor_io.h"
#include "sched.h"
#if DBM_QUEUE
#include "proc_obj.h"
#endif
#include "alloc.h"

static char *_FileName_ = __FILE__;		/* Used by EXCEPT (see except.h)     */

extern "C" char *get_schedd_addr(const char *);

#if DBM_QUEUE
DBM		*Q, *OpenJobQueue();
#else
#include "condor_qmgr.h"
#endif

char	*MyName;
#if DBM_QUEUE
char	*Spool;
#endif
BOOLEAN	TroubleReported;
BOOLEAN All;
static BOOLEAN Force = FALSE;
#if DBM_QUEUE
ProcFilter	*PFilter = new ProcFilter();
#endif

	// Prototypes of local interest
#if DBM_QUEUE
void do_it( ProcObj * );
void init_params();
#else
void ProcArg(const char*);
#endif
void notify_schedd( int cluster, int proc );
void usage();
#if DBM_QUEUE
extern "C" BOOLEAN	xdr_proc_id(XDR *, PROC_ID *);
#endif

#if !DBM_QUEUE
extern "C" int gethostname();
#endif

char				hostname[512];

void
usage()
{
	fprintf( stderr,
		"Usage: %s [-r host] { -a | cluster | cluster.proc | user } ... \n",
		MyName
	);
	exit( 1 );
}

int
main( int argc, char *argv[] )
{
#if DBM_QUEUE
	char	queue_name[_POSIX_PATH_MAX];
#endif
	char	*arg;
#if DBM_QUEUE
	List<ProcObj>	*proc_list;
	ProcObj			*p;
#else
	char*				args[argc - 1];			// args of jobs to be deleted
	int					nArgs = 0;				// number of args to be deleted
	int					i;
	Qmgr_connection*	q;
#endif

	MyName = argv[0];

	config( 0 );
#if DBM_QUEUE
	init_params();
#endif

	if( argc < 2 ) {
		usage();
	}

	hostname[0] = '\0';
	for( argv++; arg = *argv; argv++ ) {
		if( arg[0] == '-' && arg[1] == 'a' ) {
			All = TRUE;
		} else {
			if( All ) {
				usage();
			}
			if ( arg[0] == '-' && arg[1] == 'f' ) {
				// "-f" is the undocumented "force" feature, which rips
				// out the job from the queue without any checks except for
				// permission.  -Todd 10/95
				Force = TRUE;
			} else
			if ( arg[0] == '-' && arg[1] == 'r' ) {
				// use the given name as the host name to connect to
				argv++;
				strcpy (hostname, *argv);
			} else {
			#if DBM_QUEUE
				if( !PFilter->Append(arg) ) {
					usage();
				}
			#else
				args[nArgs] = arg;
				nArgs++;
			#endif
			}
		}
	}

		/* Open job queue */
#if DBM_QUEUE
	(void)sprintf( queue_name, "%s/job_queue", Spool );
	if( (Q=OpenJobQueue(queue_name,O_RDWR,0)) == NULL ) {
		EXCEPT( "OpenJobQueue(%s)", queue_name );
	}

		// Create a list of all procs we're interested in
	PFilter->Install();
	proc_list = ProcObj::create_list( Q, ProcFilter::Func );

		// Process the list
	proc_list->Rewind();
	while( p = proc_list->Next() ) {
		do_it( p );
	}

		// Clean up
	LockJobQueue( Q, UNLOCK );
	CloseJobQueue( Q );
	ProcObj::delete_list( proc_list );
	delete PFilter;
#else
	if (hostname[0] == '\0')
	{
		// hostname was not set at command line; obtain from system
		if(gethostname(hostname, 200) < 0)
		{
			EXCEPT("gethostname failed, errno = %d", errno);
		}
	}
	if((q = ConnectQ(hostname)) == 0)
	{
		EXCEPT("Failed to connect to qmgr on host %s", hostname);
	}
	for(i = 0; i < nArgs; i++)
	{
		ProcArg(args[i]);
	}
	DisconnectQ(q);
#endif

#if defined(ALLOC_DEBUG)
	print_alloc_stats();
#endif

	return 0;
}

extern "C" int SetSyscalls( int foo ) { return foo; }

#if DBM_QUEUE
void
init_params()
{
	Spool = param("SPOOL");
	if( Spool == NULL ) {
		EXCEPT( "SPOOL not specified in config file\n" );
	}
}
#endif

void
notify_schedd( int cluster, int proc )
{
	ReliSock	*sock;
	char		*scheddAddr;
	int			cmd;
	PROC_ID		job_id;

	job_id.cluster = cluster;
	job_id.proc = proc;

	if (hostname[0] == '\0')
	{
		// if the hostname was not set at command line, obtain from system
		if( gethostname(hostname,sizeof(hostname)) < 0 ) {
			EXCEPT( "gethostname failed" );
		}
	}

	if ((scheddAddr = get_schedd_addr(hostname)) == NULL)
	{
		EXCEPT("Can't find schedd address on %s\n", hostname);
	}

		/* Connect to the schedd */
	sock = new ReliSock(scheddAddr, SCHED_PORT);
	if(sock->get_file_desc() < 0) {
		if( !TroubleReported ) {
			dprintf( D_ALWAYS, "Warning: can't connect to condor scheduler\n" );
			TroubleReported = 1;
		}
		delete sock;
		return;
	}

	sock->encode();

	cmd = KILL_FRGN_JOB;
	if( !sock->code(cmd) ) {
		dprintf( D_ALWAYS,
			"Warning: can't send KILL_JOB command to condor scheduler\n" );
		delete sock;
		return;
	}

	if( !sock->code(job_id) ) {
		dprintf( D_ALWAYS,
			"Warning: can't send proc_id to condor scheduler\n" );
		delete sock;
		return;
	}

	if( !sock->end_of_message() ) {
		dprintf( D_ALWAYS,
			"Warning: can't send endofrecord to condor scheduler\n" );
		delete sock;
		return;
	}

	dprintf( D_FULLDEBUG, "Sent KILL_FRGN_JOB command to condor scheduler\n" );
	delete sock;
}

#if DBM_QUEUE
void
do_it( ProcObj *p )
{
	PROC_ID	id;

		// Make sure it makes sense to remove the process, unless -f Force command line
		// option is in effect, in which case we trust the user knows better
	if ( Force == FALSE ) {
		switch( p->get_status() ) {
	  	case REMOVED:
	  	case COMPLETED:
	  	case SUBMISSION_ERR:
			return;
		}
	}

	id.cluster = p->get_cluster_id();
	id.proc = p->get_proc_id();

		// Make sure user is allowed to remove it
	if( !p->perm_to_modify() ) {
		fprintf( stderr, "%d.%d: Permission Denied\n", id.cluster, id.proc);
		return;
	}

		// Ok, go ahead and remove it
	TerminateProc( Q, &id, REMOVED );
	notify_schedd( id.cluster, id.proc );
	printf( "Deleted %d.%d\n", id.cluster, id.proc );
}
#else
void ProcArg(const char* arg)
{
	int		c, p;								// cluster/proc #
	char*	tmp;

	if(isdigit(*arg))
	// delete by cluster/proc #
	{
		c = strtol(arg, &tmp, 10);
		if(c <= 0)
		{
			fprintf(stderr, "Invalid cluster # from %s.\n", arg);
			return;
		}
		if(*tmp == '\0')
		// delete the cluster
		{
			if(DestroyCluster(c) < 0)
			{
				fprintf(stderr, "Couldn't find/delete cluster %d.\n", c);
			} else {
			fprintf(stderr, "Cluster %d removed.\n", c);
			}
#ifdef 0
			notify_schedd( c, -1 );
#endif
			return;
		}
		if(*tmp == '.')
		{
			p = strtol(tmp + 1, &tmp, 10);
			if(p < 0)
			{
				fprintf(stderr, "Invalid proc # from %s.\n", arg);
				return;
			}
			if(*tmp == '\0')
			// delete a proc
			{
				if(DestroyProc(c, p) < 0)
				{
					fprintf(stderr, "Couldn't find/delete job %d.%d.\n", c, p);
				} else {
					fprintf(stderr, "Job %d.%d removed.\n", c, p);
				}
#ifdef 0
				notify_schedd( c, p );
#endif
				return;
			}
			fprintf(stderr, "Warning: unrecognized \"%s\" skipped.\n", arg);
			return;
		}
		fprintf(stderr, "Warning: unrecognized \"%s\" skipped.\n", arg);
	}
	else if(isalpha(*arg))
	// delete by user name
	{
		char	constraint[1000];

		sprintf(constraint, "Owner == \"%s\"", arg);
		if(DestroyClusterByConstraint(constraint) < 0)
		{
			fprintf(stderr, "Couldn't find/delete user %s's job(s).\n", arg);
		} else {
			fprintf(stderr, "User %s's job(s) removed.\n", arg);
		}
	}
	else
	{
		fprintf(stderr, "Warning: unrecognized \"%s\" skipped.\n", arg);
	}
}
#endif
<|endoftext|>


<commit_before>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Collect the sequence of machine instructions for a basic block.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/BasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>
#include <algorithm>
using namespace llvm;

MachineBasicBlock::~MachineBasicBlock() {
  LeakDetector::removeGarbageObject(this);
}

// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
// gets the next available unique MBB number. If it is removed from a
// MachineFunction, it goes back to being #-1.
void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) {
  assert(N->Parent == 0 && "machine instruction already in a basic block");
  N->Parent = Parent;
  N->Number = Parent->addToMBBNumbering(N);
  LeakDetector::removeGarbageObject(N);
}

void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) {
  assert(N->Parent != 0 && "machine instruction not in a basic block");
  N->Parent->removeFromMBBNumbering(N->Number);
  N->Number = -1;
  N->Parent = 0;
  LeakDetector::addGarbageObject(N);
}

MachineInstr* ilist_traits<MachineInstr>::createSentinel() {
  MachineInstr* dummy = new MachineInstr(0, 0);
  LeakDetector::removeGarbageObject(dummy);
  return dummy;
}

void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) {
  assert(N->parent == 0 && "machine instruction already in a basic block");
  N->parent = parent;
  LeakDetector::removeGarbageObject(N);
}

void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) {
  assert(N->parent != 0 && "machine instruction not in a basic block");
  N->parent = 0;
  LeakDetector::addGarbageObject(N);
}

void ilist_traits<MachineInstr>::transferNodesFromList(
  iplist<MachineInstr, ilist_traits<MachineInstr> >& fromList,
  ilist_iterator<MachineInstr> first,
  ilist_iterator<MachineInstr> last) {
  if (parent != fromList.parent)
    for (; first != last; ++first)
      first->parent = parent;
}

MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo();
  iterator I = end();
  while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode()));
  if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I;
  return I;
}

void MachineBasicBlock::dump() const {
  print(std::cerr);
}

void MachineBasicBlock::print(std::ostream &OS) const {
  if(!getParent()) {
    OS << "Can't print out MachineBasicBlock because parent MachineFunction"
       << " is null\n";
    return;
  }

  const BasicBlock *LBB = getBasicBlock();
  if (LBB)
    OS << "\n" << LBB->getName() << " (" << (const void*)this
       << ", LLVM BB @" << (const void*) LBB << ", ID#" << getNumber()<< "):\n";
  // Print the preds of this block according to the CFG.
  if (!pred_empty()) {
    OS << "    Predecessors according to CFG:";
    for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
      OS << " " << *PI;
    OS << "\n";
  }

  for (const_iterator I = begin(); I != end(); ++I) {
    OS << "\t";
    I->print(OS, &getParent()->getTarget());
  }

  // Print the successors of this block according to the CFG.
  if (!succ_empty()) {
    OS << "    Successors according to CFG:";
    for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
      OS << " " << *SI;
    OS << "\n";
  }
}

void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
  Successors.push_back(succ);
  succ->addPredecessor(this);
}

void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  succ->removePredecessor(this);
  succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  assert(I != Successors.end() && "Not a current successor!");
  Successors.erase(I);
}

void MachineBasicBlock::removeSuccessor(succ_iterator I) {
  assert(I != Successors.end() && "Not a current successor!");
  (*I)->removePredecessor(this);
  Successors.erase(I);
}

void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  Predecessors.push_back(pred);
}

void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  std::vector<MachineBasicBlock *>::iterator I =
    std::find(Predecessors.begin(), Predecessors.end(), pred);
  assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  Predecessors.erase(I);
}
<commit_msg>print labels even if a MBB doesn't have a corresponding LLVM BB, just don't print the LLVM BB label.<commit_after>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Collect the sequence of machine instructions for a basic block.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/BasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/LeakDetector.h"
#include <iostream>
#include <algorithm>
using namespace llvm;

MachineBasicBlock::~MachineBasicBlock() {
  LeakDetector::removeGarbageObject(this);
}

// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
// gets the next available unique MBB number. If it is removed from a
// MachineFunction, it goes back to being #-1.
void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) {
  assert(N->Parent == 0 && "machine instruction already in a basic block");
  N->Parent = Parent;
  N->Number = Parent->addToMBBNumbering(N);
  LeakDetector::removeGarbageObject(N);
}

void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) {
  assert(N->Parent != 0 && "machine instruction not in a basic block");
  N->Parent->removeFromMBBNumbering(N->Number);
  N->Number = -1;
  N->Parent = 0;
  LeakDetector::addGarbageObject(N);
}

MachineInstr* ilist_traits<MachineInstr>::createSentinel() {
  MachineInstr* dummy = new MachineInstr(0, 0);
  LeakDetector::removeGarbageObject(dummy);
  return dummy;
}

void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) {
  assert(N->parent == 0 && "machine instruction already in a basic block");
  N->parent = parent;
  LeakDetector::removeGarbageObject(N);
}

void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) {
  assert(N->parent != 0 && "machine instruction not in a basic block");
  N->parent = 0;
  LeakDetector::addGarbageObject(N);
}

void ilist_traits<MachineInstr>::transferNodesFromList(
  iplist<MachineInstr, ilist_traits<MachineInstr> >& fromList,
  ilist_iterator<MachineInstr> first,
  ilist_iterator<MachineInstr> last) {
  if (parent != fromList.parent)
    for (; first != last; ++first)
      first->parent = parent;
}

MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo();
  iterator I = end();
  while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode()));
  if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I;
  return I;
}

void MachineBasicBlock::dump() const {
  print(std::cerr);
}

void MachineBasicBlock::print(std::ostream &OS) const {
  if(!getParent()) {
    OS << "Can't print out MachineBasicBlock because parent MachineFunction"
       << " is null\n";
    return;
  }

  const BasicBlock *LBB = getBasicBlock();
  OS << "\n";
  if (LBB) OS << LBB->getName();
  OS << " (" << (const void*)this
     << ", LLVM BB @" << (const void*) LBB << ", ID#" << getNumber()<< "):\n";
  // Print the preds of this block according to the CFG.
  if (!pred_empty()) {
    OS << "    Predecessors according to CFG:";
    for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
      OS << " " << *PI;
    OS << "\n";
  }

  for (const_iterator I = begin(); I != end(); ++I) {
    OS << "\t";
    I->print(OS, &getParent()->getTarget());
  }

  // Print the successors of this block according to the CFG.
  if (!succ_empty()) {
    OS << "    Successors according to CFG:";
    for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
      OS << " " << *SI;
    OS << "\n";
  }
}

void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
  Successors.push_back(succ);
  succ->addPredecessor(this);
}

void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  succ->removePredecessor(this);
  succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  assert(I != Successors.end() && "Not a current successor!");
  Successors.erase(I);
}

void MachineBasicBlock::removeSuccessor(succ_iterator I) {
  assert(I != Successors.end() && "Not a current successor!");
  (*I)->removePredecessor(this);
  Successors.erase(I);
}

void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  Predecessors.push_back(pred);
}

void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  std::vector<MachineBasicBlock *>::iterator I =
    std::find(Predecessors.begin(), Predecessors.end(), pred);
  assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  Predecessors.erase(I);
}
<|endoftext|>


<commit_before>//===-- TargetOptionsImpl.cpp - Options that apply to all targets ----------==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the methods in the TargetOptions.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Function.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;

/// DisableFramePointerElim - This returns true if frame pointer elimination
/// optimization should be disabled for the given machine function.
bool TargetOptions::DisableFramePointerElim(const MachineFunction &MF) const {
  // Check to see if we should eliminate non-leaf frame pointers and then
  // check to see if we should eliminate all frame pointers.
  bool NoFramePointerElimNonLeaf =
    MF.getFunction()->getFnAttribute("no-frame-pointer-elim-non-leaf")
      .getValueAsString() == "true";
  if (NoFramePointerElimNonLeaf && !NoFramePointerElim) {
    const MachineFrameInfo *MFI = MF.getFrameInfo();
    return MFI->hasCalls();
  }

  return NoFramePointerElim;
}

/// LessPreciseFPMAD - This flag return true when -enable-fp-mad option
/// is specified on the command line.  When this flag is off(default), the
/// code generator is not allowed to generate mad (multiply add) if the
/// result is "less precise" than doing those operations individually.
bool TargetOptions::LessPreciseFPMAD() const {
  return UnsafeFPMath || LessPreciseFPMADOption;
}

/// HonorSignDependentRoundingFPMath - Return true if the codegen must assume
/// that the rounding mode of the FPU can change from its default.
bool TargetOptions::HonorSignDependentRoundingFPMath() const {
  return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
}

/// getTrapFunctionName - If this returns a non-empty string, this means isel
/// should lower Intrinsic::trap to a call to the specified function name
/// instead of an ISD::TRAP node.
StringRef TargetOptions::getTrapFunctionName() const {
  return TrapFuncName;
}
<commit_msg>Check only if we have this attribute. If it's not an attribute, then it's assumed false.<commit_after>//===-- TargetOptionsImpl.cpp - Options that apply to all targets ----------==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the methods in the TargetOptions.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Function.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;

/// DisableFramePointerElim - This returns true if frame pointer elimination
/// optimization should be disabled for the given machine function.
bool TargetOptions::DisableFramePointerElim(const MachineFunction &MF) const {
  // Check to see if we should eliminate non-leaf frame pointers and then
  // check to see if we should eliminate all frame pointers.
  if (MF.getFunction()->hasFnAttribute("no-frame-pointer-elim-non-leaf") &&
      !NoFramePointerElim) {
    const MachineFrameInfo *MFI = MF.getFrameInfo();
    return MFI->hasCalls();
  }

  return NoFramePointerElim;
}

/// LessPreciseFPMAD - This flag return true when -enable-fp-mad option
/// is specified on the command line.  When this flag is off(default), the
/// code generator is not allowed to generate mad (multiply add) if the
/// result is "less precise" than doing those operations individually.
bool TargetOptions::LessPreciseFPMAD() const {
  return UnsafeFPMath || LessPreciseFPMADOption;
}

/// HonorSignDependentRoundingFPMath - Return true if the codegen must assume
/// that the rounding mode of the FPU can change from its default.
bool TargetOptions::HonorSignDependentRoundingFPMath() const {
  return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
}

/// getTrapFunctionName - If this returns a non-empty string, this means isel
/// should lower Intrinsic::trap to a call to the specified function name
/// instead of an ISD::TRAP node.
StringRef TargetOptions::getTrapFunctionName() const {
  return TrapFuncName;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "ScriptController.h"
#include "Input.h"
#include "Config.h"
#include "File.h"

using namespace std;
using namespace Graphos::Core;
using namespace Graphos::Graphics;
using namespace v8;

#pragma region Handlers
#pragma region Helpers
Handle<Value> IsKeyDown( const Arguments& args )
{
	return Boolean::New( Input::Get().IsKeyDown( args[ 0 ]->Int32Value() ) );
}

Handle<Value> IncludeHandler(const Arguments& args)
{
	for (int i = 0; i < args.Length(); i++)
	{
		String::Utf8Value str(args[i]);

		// load_file loads the file with this name into a string,
		// I imagine you can write a function to do this :)
		std::string js_file = File::ReadFile(*str);

		if(js_file.length() > 0)
		{
			Handle<String> source = String::New( js_file.c_str() );
			Handle<v8::Script> script = v8::Script::Compile( source );
			return script->Run();
		}
	}
	return Undefined();
}

Handle<Value> PrintHandler( const Arguments& args )
{
	for( int ii = 0; ii < args.Length(); ++ii )
		cout << *String::Utf8Value( args[ ii ] );

	cout << endl;

	return Undefined();
}
#pragma endregion

#pragma region Transform
// Access transform
Handle<Value> GetTransform(Local<String> property, const AccessorInfo& info)
{
	// Get object holder
	Local<Object> self = info.Holder();

	Handle<Object> global = info.GetIsolate()->GetCurrentContext()->Global();

	// Get owner
//	GameObject* owner = GameObject::GetGameObject( self->Get( String::New( "id" ) )->Uint32Value() );

	// Create position
	Handle<Object> position = Handle<Function>::Cast( global->Get( String::New( "Vector3" ) ) )->CallAsConstructor( 0, nullptr )->ToObject();
	//position->Set( String::New( "x" ), Number::New( owner->transform.Position().x ) );
	//position->Set( String::New( "y" ), Number::New( owner->transform.Position().y ) );
	//position->Set( String::New( "z" ), Number::New( owner->transform.Position().z ) );

	// Create rotation
	Handle<Object> rotation = Handle<Function>::Cast( global->Get( String::New( "Vector3" ) ) )->CallAsConstructor( 0, nullptr )->ToObject();
	//rotation->Set( String::New( "x" ), Number::New( owner->transform.Rotation().x ) );
	//rotation->Set( String::New( "y" ), Number::New( owner->transform.Rotation().y ) );
	//rotation->Set( String::New( "z" ), Number::New( owner->transform.Rotation().z ) );

	// Create scale
	Handle<Object> scale = Handle<Function>::Cast( global->Get( String::New( "Vector3" ) ) )->CallAsConstructor( 0, nullptr )->ToObject();
	//scale->Set( String::New( "x" ), Number::New( owner->transform.Scale().x ) );
	//scale->Set( String::New( "y" ), Number::New( owner->transform.Scale().y ) );
	//scale->Set( String::New( "z" ), Number::New( owner->transform.Scale().z ) );

	// Link them all
	Handle<Object> transform = Object::New();
	transform->Set( String::New( "position" ), position );
	transform->Set( String::New( "rotation" ), rotation );
	transform->Set( String::New( "scale" ), scale );

	return transform;
}

/*
// Change transform
void SetTransform(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
	Local<Object> self = info.Holder();
	Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
	void* ptr = wrap->Value();
	static_cast<Point*>(ptr)->x_ = value->Int32Value();
}
*/
#pragma endregion
#pragma endregion

void ScriptController::Initialize( void )
{
	// Create global object template, add function handlers
	Handle<ObjectTemplate> globalObjectTemplate = ObjectTemplate::New();
	globalObjectTemplate->Set( "include", FunctionTemplate::New( IncludeHandler ) );
	globalObjectTemplate->Set( "log", FunctionTemplate::New( PrintHandler ) );

	// Setup Input
	Handle<ObjectTemplate> input = ObjectTemplate::New();
	input->Set( "IsKeyDown", FunctionTemplate::New( IsKeyDown ) );
	globalObjectTemplate->Set( "Input", input );

	// Create the context for initializing the scripts
	context = Context::New( isolate, nullptr, globalObjectTemplate );

	// Scope for created variables
	Context::Scope contextScope( context );

	// Load and compile scripts
	for( auto file : File::ScanDir( Config::Get().GetData<string>( "Scripts.Path" ) ) )
	{
		v8::Script::Compile(
			String::New(
				file.GetContents().c_str()
			)
		);
	}

	// Get the "global" object
	globalObject = context->Global();
}

void ScriptController::Shutdown( void )
{
	if( isInitialized )
	{
		//context->Dispose();

		isInitialized = false;
	}
}

Graphos::Core::Script* ScriptController::CreateObjectInstance( string className, unsigned int ownerID, GameObject* owner /*= nullptr */ )
{
	if( !isInitialized )
		Initialize();

	// Create a scope
	Context::Scope contextScope( context );

	// Get an instance of the class
	Local<Function> ctor = Local<Function>::Cast( globalObject->Get( String::New( className.c_str() ) ) );

	// Return object
	if( !ctor.IsEmpty() )
	{
		// Get object
		Local<Object> instance = ctor->CallAsConstructor( 0, nullptr )->ToObject();

		// Set id
		instance->Set( String::New( "id" ), Int32::New( ownerID ) );

		// Set transform accessor
		instance->SetAccessor( String::New( "transform" ), GetTransform, nullptr );

		// Return new script
		return new Graphos::Core::Script( instance, owner );
	}
	else
		return nullptr;
}

/*
void ScriptController::MyHandler::OnMethodCall( WebView* caller, unsigned int remoteObjId, const WebString& methodName, const JSArray& args )
{
	if( methodName == WSLit( "log" ) )
	{
		if( args.size() )
		{
			cout << args[ 0 ].ToString();

			for( unsigned int ii = 1; ii < args.size(); ++ii )
				cout << ", " << args[ ii ].ToString();
		}

		cout << endl;
	}
}

JSValue ScriptController::MyHandler::OnMethodCallWithReturnValue( WebView* caller, unsigned int remoteObjectId, const WebString& methodName, const JSArray& args )
{
	if( remoteObjectId == owner->input.remote_id() && methodName == WSLit( "IsKeyDown" ) && args.size() )
	{
		if( args[ 0 ].IsInteger() )
			return JSValue( Input::Get().IsKeyDown( args[ 0 ].ToInteger() ) );
	}
	if( methodName == WSLit( "UpdateTransformC" ) && args.size() == 1 )
	{
		// Get GameObject reference
		string name = ToString( args[ 0 ].ToString() );

		GameObject& obj = GameObject::GetGameObject( name );

		// Get values
		const Vector3& positionVec = obj.transform.Position();

		JSObject transform, position;
		position.SetProperty( WSLit( "x" ), JSValue( positionVec.x ) );
		position.SetProperty( WSLit( "y" ), JSValue( positionVec.y ) );
		position.SetProperty( WSLit( "z" ), JSValue( positionVec.z ) );

		transform.SetProperty( WSLit( "position" ), position );

		return transform;
	}

	return JSValue::Undefined();
}
*/<commit_msg>Tweaked ScriptController so that file compilation order does not matter.<commit_after>#include <iostream>

#include "ScriptController.h"
#include "Input.h"
#include "Config.h"
#include "File.h"

using namespace std;
using namespace Graphos::Core;
using namespace Graphos::Graphics;
using namespace v8;

#pragma region Handlers
#pragma region Helpers
Handle<Value> IsKeyDown( const Arguments& args )
{
	return Boolean::New( Input::Get().IsKeyDown( args[ 0 ]->Int32Value() ) );
}

Handle<Value> IncludeHandler(const Arguments& args)
{
	for (int i = 0; i < args.Length(); i++)
	{
		String::Utf8Value str(args[i]);

		// load_file loads the file with this name into a string,
		// I imagine you can write a function to do this :)
		std::string js_file = File::ReadFile(*str);

		if(js_file.length() > 0)
		{
			Handle<String> source = String::New( js_file.c_str() );
			Handle<v8::Script> script = v8::Script::Compile( source );
			return script->Run();
		}
	}
	return Undefined();
}

Handle<Value> PrintHandler( const Arguments& args )
{
	for( int ii = 0; ii < args.Length(); ++ii )
		cout << *String::Utf8Value( args[ ii ] );

	cout << endl;

	return Undefined();
}
#pragma endregion

#pragma region Transform
// Access transform
Handle<Value> GetTransform(Local<String> property, const AccessorInfo& info)
{
	// Get object holder
	Local<Object> self = info.Holder();

	Handle<Object> global = info.GetIsolate()->GetCurrentContext()->Global();

	// Get owner
//	GameObject* owner = GameObject::GetGameObject( self->Get( String::New( "id" ) )->Uint32Value() );

	// Create position
	Handle<Object> position = Handle<Function>::Cast( global->Get( String::New( "Vector3" ) ) )->CallAsConstructor( 0, nullptr )->ToObject();
	//position->Set( String::New( "x" ), Number::New( owner->transform.Position().x ) );
	//position->Set( String::New( "y" ), Number::New( owner->transform.Position().y ) );
	//position->Set( String::New( "z" ), Number::New( owner->transform.Position().z ) );

	// Create rotation
	Handle<Object> rotation = Handle<Function>::Cast( global->Get( String::New( "Vector3" ) ) )->CallAsConstructor( 0, nullptr )->ToObject();
	//rotation->Set( String::New( "x" ), Number::New( owner->transform.Rotation().x ) );
	//rotation->Set( String::New( "y" ), Number::New( owner->transform.Rotation().y ) );
	//rotation->Set( String::New( "z" ), Number::New( owner->transform.Rotation().z ) );

	// Create scale
	Handle<Object> scale = Handle<Function>::Cast( global->Get( String::New( "Vector3" ) ) )->CallAsConstructor( 0, nullptr )->ToObject();
	//scale->Set( String::New( "x" ), Number::New( owner->transform.Scale().x ) );
	//scale->Set( String::New( "y" ), Number::New( owner->transform.Scale().y ) );
	//scale->Set( String::New( "z" ), Number::New( owner->transform.Scale().z ) );

	// Link them all
	Handle<Object> transform = Object::New();
	transform->Set( String::New( "position" ), position );
	transform->Set( String::New( "rotation" ), rotation );
	transform->Set( String::New( "scale" ), scale );

	return transform;
}

/*
// Change transform
void SetTransform(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
	Local<Object> self = info.Holder();
	Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
	void* ptr = wrap->Value();
	static_cast<Point*>(ptr)->x_ = value->Int32Value();
}
*/
#pragma endregion
#pragma endregion

void ScriptController::Initialize( void )
{
	// Create global object template, add function handlers
	Handle<ObjectTemplate> globalObjectTemplate = ObjectTemplate::New();
	globalObjectTemplate->Set( "include", FunctionTemplate::New( IncludeHandler ) );
	globalObjectTemplate->Set( "log", FunctionTemplate::New( PrintHandler ) );

	// Setup Input
	Handle<ObjectTemplate> input = ObjectTemplate::New();
	input->Set( "IsKeyDown", FunctionTemplate::New( IsKeyDown ) );
	globalObjectTemplate->Set( "Input", input );

	// Create the context for initializing the scripts
	context = Context::New( isolate, nullptr, globalObjectTemplate );

	// Scope for created variables
	Context::Scope contextScope( context );

	string scripts = "";

	// Load and compile scripts
	for( auto file : File::ScanDir( Config::Get().GetData<string>( "Scripts.Path" ) ) )
	{
		scripts = scripts.append( file.GetContents() ).append( "\n" );
	}

	v8::Script::Compile( String::New( scripts.c_str() ) );

	// Get the "global" object
	globalObject = context->Global();
}

void ScriptController::Shutdown( void )
{
	if( isInitialized )
	{
		//context->Dispose();

		isInitialized = false;
	}
}

Graphos::Core::Script* ScriptController::CreateObjectInstance( string className, unsigned int ownerID, GameObject* owner /*= nullptr */ )
{
	if( !isInitialized )
		Initialize();

	// Create a scope
	Context::Scope contextScope( context );

	// Get an instance of the class
	Local<Function> ctor = Local<Function>::Cast( globalObject->Get( String::New( className.c_str() ) ) );

	// Return object
	if( !ctor.IsEmpty() )
	{
		// Get object
		Local<Object> instance = ctor->CallAsConstructor( 0, nullptr )->ToObject();

		// Set id
		instance->Set( String::New( "id" ), Int32::New( ownerID ) );

		// Set transform accessor
		instance->SetAccessor( String::New( "transform" ), GetTransform, nullptr );

		// Return new script
		return new Graphos::Core::Script( instance, owner );
	}
	else
		return nullptr;
}

/*
void ScriptController::MyHandler::OnMethodCall( WebView* caller, unsigned int remoteObjId, const WebString& methodName, const JSArray& args )
{
	if( methodName == WSLit( "log" ) )
	{
		if( args.size() )
		{
			cout << args[ 0 ].ToString();

			for( unsigned int ii = 1; ii < args.size(); ++ii )
				cout << ", " << args[ ii ].ToString();
		}

		cout << endl;
	}
}

JSValue ScriptController::MyHandler::OnMethodCallWithReturnValue( WebView* caller, unsigned int remoteObjectId, const WebString& methodName, const JSArray& args )
{
	if( remoteObjectId == owner->input.remote_id() && methodName == WSLit( "IsKeyDown" ) && args.size() )
	{
		if( args[ 0 ].IsInteger() )
			return JSValue( Input::Get().IsKeyDown( args[ 0 ].ToInteger() ) );
	}
	if( methodName == WSLit( "UpdateTransformC" ) && args.size() == 1 )
	{
		// Get GameObject reference
		string name = ToString( args[ 0 ].ToString() );

		GameObject& obj = GameObject::GetGameObject( name );

		// Get values
		const Vector3& positionVec = obj.transform.Position();

		JSObject transform, position;
		position.SetProperty( WSLit( "x" ), JSValue( positionVec.x ) );
		position.SetProperty( WSLit( "y" ), JSValue( positionVec.y ) );
		position.SetProperty( WSLit( "z" ), JSValue( positionVec.z ) );

		transform.SetProperty( WSLit( "position" ), position );

		return transform;
	}

	return JSValue::Undefined();
}
*/<|endoftext|>


<commit_before><commit_msg>Add numa and sched headers<commit_after><|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2015 nabijaczleweli

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "../include/cpponfig/configuration.hpp"
#include "../include/cpponfig/parsing_error.hpp"
#include "../include/cpponfig/util/strings.hpp"
#include "../include/cpponfig/util/regex.hpp"
#include "../include/cpponfig/util/salt.hpp"
#include "config.h"
#include <iomanip>
#include <istream>
#include <fstream>
#include <cstring>
#include <regex>

using namespace std;
using namespace cpponfig;
using namespace cpponfig::util;

using datetime_mode = configuration::datetime_mode;

bool configuration::save_on_destruction           = true;
char configuration::comment_character             = '#';
char configuration::assignment_character          = '=';
char configuration::category_character            = ':';
char configuration::category_start_character      = '{';
char configuration::category_end_character        = '}';
datetime_mode configuration::datetime_footer_type = datetime_mode::none;

std::pair<std::string, std::string> configuration::property_path(const std::string & name) {
	const auto idx = name.find(category_character);
	if(idx == string::npos)
		return {"", trim(string(name))};
	else
		return {trim(name.substr(0, idx)), trim(name.substr(idx + 1))};
}

static void actually_put_time(ostream & to, datetime_mode mode, char comment) {
	if(mode != datetime_mode::none) {
		const bool isgmt = mode == datetime_mode::gmt;
		const time_t tme = time(nullptr);
		to << '\n' << comment << "  ";
#ifdef HAVE_STD_PUT_TIME_CHAR_
		to << put_time(isgmt ? gmtime(&tme) : localtime(&tme), "%d.%m.%Y %H:%M:%S");
#else
		char buf[20];
		to << strftime(buf, 20, "%d.%m.%Y %H:%M:%S", isgmt ? gmtime(&tme) : localtime(&tme)) ? buf : "<<DATE ERROR>>";
#endif
		if(isgmt)
			to << " GMT";
		to << "\n\n";
	}
}

configuration::configuration(const string & name) : filename(name) {}

configuration::~configuration() {
	if(save_on_destruction)
		save();
}

void configuration::swap(configuration & other) {
	using std::swap;
	swap(categories, other.categories);
	swap(filename, other.filename);
	swap(sof_comments, other.sof_comments);
}

// All hex numbers here are primes
size_t configuration::hash_code() const {
#define COLHASH(col, hash, prime) \
	if(col.empty())                 \
		result ^= prime;              \
	else                            \
		for(const auto & elem : col)  \
			result ^= hash(elem);

	static const salt slt{};
	static const hash<pair<string, configuration_category>> kv_hash{};
	static const hash<string> string_hash{};

	size_t result = 0x26FE1F8D;

	result ^= (filename.empty() ? 0x12C0852B : string_hash(filename));
	COLHASH(categories, kv_hash, 0x16447FAB)
	COLHASH(sof_comments, string_hash, 0x39531FBF)

	return result ^ slt;

#undef COLHASH
}

configuration & configuration::operator=(const configuration & other) {
	configuration temp(other);
	swap(temp);
	return *this;
}

configuration & configuration::operator+=(const configuration & other) {
	categories.insert(other.categories.begin(), other.categories.end());
	sof_comments.insert(sof_comments.end(), other.sof_comments.begin(), other.sof_comments.end());

	return *this;
}

configuration & configuration::operator-=(const configuration & other) {
	for(const auto & kv : other.categories)
		categories.erase(kv.first);

	for(const auto & cmt : other.sof_comments)
		sof_comments.erase(find(sof_comments.begin(), sof_comments.end(), cmt));

	return *this;
}

void configuration::load_properties(istream & from) {
	static const auto readfromline = [&](string & line, size_t lineno) {
		//
		static const auto is_comment       = CPPONFIG_CHARCACHED_REGEX("(?:[[:space:]]*(?:"s + chr + "[[:space:]]*(.*))?)?");
		static const auto is_tagless_start = CPPONFIG_TWOCHARCACHED_REGEX("[[:space:]]*\\"s + chr2 + "[[:space:]]*(?:\\" + chr1 + ".*)?");
		static const auto is_tagged_start  = CPPONFIG_TWOCHARCACHED_REGEX("[[:space:]]*([^[:space:]]+)[[:space:]]*\\"s + chr2 + "[[:space:]]*(?:\\" + chr1 + ".*)?");

		smatch match;
		if(regex_match(line, match, is_comment(comment_character)))
			return match.str(1);
		else if(regex_match(line, is_tagless_start(comment_character, category_start_character)))
			categories.emplace("", configuration_category()).first->second.load(from);
		else if(regex_match(line, match, is_tagged_start(comment_character, category_start_character)))
			categories.emplace(match.str(1), configuration_category()).first->second.load(from);
		else
			throw parsing_error("Line " + to_string(lineno) + " (\"" + line + "\") is not a comment nor a category start");
		return ""s;
	};

	size_t lineno = 1;
	for(string line; getline(from, line); ++lineno) {
		const auto & comment = readfromline(line, lineno);
		if(!comment.empty())
			sof_comments.emplace_back(comment);
		else
			break;
	}

	for(string line; getline(from, line); ++lineno)
		readfromline(line, lineno);
}

void configuration::save_properties(ostream & to) const {
	for(const auto & cmt : sof_comments)
		to << comment_character << ' ' << cmt << '\n';
	to << (sof_comments.empty() ? "" : "\n\n");
	for(const auto & pr : categories) {
		to << pr.first << (pr.first.empty() ? "" : " ") << category_start_character << '\n';
		pr.second.save(to);
		to << category_end_character << "\n\n";
	}

	actually_put_time(to, datetime_footer_type, comment_character);
}

bool configuration::load() {
	if(!filename.empty()) {
		ifstream file(filename);
		if(file && file.is_open()) {
			load_properties(file);
			return true;
		}
	}
	return false;
}

bool configuration::load(const string & name) {
	rename(name);
	return load();
}

bool configuration::load(istream & stream) {
	if(stream) {
		load_properties(stream);
		return true;
	}
	return false;
}

bool configuration::save() const {
	return save(filename);
}

bool configuration::save(const string & name) const {
	if(!name.empty()) {
		ofstream file(name);
		if(file && file.is_open()) {
			save_properties(file);
			return true;
		}
	}
	return false;
}

bool configuration::save(ostream & stream) const {
	if(stream) {
		save_properties(stream);
		return true;
	}
	return false;
}

property & configuration::get(const string & key, const string & default_value) {
	return get(key, property(trim(string(default_value))));
}

property & configuration::get(const string & key, const property & default_value) {
	const auto path = property_path(key);
	auto itr = categories.find(path.first);
	if(itr == categories.end()) {
		const auto kv = make_pair(path.second, default_value);
		itr           = categories.emplace(path.first, configuration_category(addressof(kv), addressof(kv) + 1)).first;
	}
	return itr->second.get(path.second, default_value);
}

void configuration::remove(const string & key) {
	const auto path = property_path(key);
	const auto itr = categories.find(path.first);
	if(itr != categories.end())
		itr->second.remove(path.second);
}

bool configuration::contains(const string & key) const {
	const auto path = property_path(key);
	const auto itr = categories.find(path.first);
	return itr != categories.end() && itr->second.contains(path.second);
}

void configuration::rename(const string & name) {
	filename = name;
}

bool configuration::empty() const {
	return sof_comments.empty() && all_of(categories.begin(), categories.end(), [](const auto & pr) { return pr.second.empty(); });
}

configuration operator+(const configuration & lhs, const configuration & rhs) {
	configuration temp(lhs);
	temp += rhs;
	return temp;
}

configuration operator-(const configuration & lhs, const configuration & rhs) {
	configuration temp(lhs);
	temp -= rhs;
	return temp;
}
<commit_msg>Warp the ternary in parens<commit_after>// The MIT License (MIT)

// Copyright (c) 2015 nabijaczleweli

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "../include/cpponfig/configuration.hpp"
#include "../include/cpponfig/parsing_error.hpp"
#include "../include/cpponfig/util/strings.hpp"
#include "../include/cpponfig/util/regex.hpp"
#include "../include/cpponfig/util/salt.hpp"
#include "config.h"
#include <iomanip>
#include <istream>
#include <fstream>
#include <cstring>
#include <regex>

using namespace std;
using namespace cpponfig;
using namespace cpponfig::util;

using datetime_mode = configuration::datetime_mode;

bool configuration::save_on_destruction           = true;
char configuration::comment_character             = '#';
char configuration::assignment_character          = '=';
char configuration::category_character            = ':';
char configuration::category_start_character      = '{';
char configuration::category_end_character        = '}';
datetime_mode configuration::datetime_footer_type = datetime_mode::none;

std::pair<std::string, std::string> configuration::property_path(const std::string & name) {
	const auto idx = name.find(category_character);
	if(idx == string::npos)
		return {"", trim(string(name))};
	else
		return {trim(name.substr(0, idx)), trim(name.substr(idx + 1))};
}

static void actually_put_time(ostream & to, datetime_mode mode, char comment) {
	if(mode != datetime_mode::none) {
		const bool isgmt = mode == datetime_mode::gmt;
		const time_t tme = time(nullptr);
		to << '\n' << comment << "  ";
#ifdef HAVE_STD_PUT_TIME_CHAR_
		to << put_time(isgmt ? gmtime(&tme) : localtime(&tme), "%d.%m.%Y %H:%M:%S");
#else
		char buf[20];
		to << (strftime(buf, 20, "%d.%m.%Y %H:%M:%S", isgmt ? gmtime(&tme) : localtime(&tme)) ? buf : "<<DATE ERROR>>");
#endif
		if(isgmt)
			to << " GMT";
		to << "\n\n";
	}
}

configuration::configuration(const string & name) : filename(name) {}

configuration::~configuration() {
	if(save_on_destruction)
		save();
}

void configuration::swap(configuration & other) {
	using std::swap;
	swap(categories, other.categories);
	swap(filename, other.filename);
	swap(sof_comments, other.sof_comments);
}

// All hex numbers here are primes
size_t configuration::hash_code() const {
#define COLHASH(col, hash, prime) \
	if(col.empty())                 \
		result ^= prime;              \
	else                            \
		for(const auto & elem : col)  \
			result ^= hash(elem);

	static const salt slt{};
	static const hash<pair<string, configuration_category>> kv_hash{};
	static const hash<string> string_hash{};

	size_t result = 0x26FE1F8D;

	result ^= (filename.empty() ? 0x12C0852B : string_hash(filename));
	COLHASH(categories, kv_hash, 0x16447FAB)
	COLHASH(sof_comments, string_hash, 0x39531FBF)

	return result ^ slt;

#undef COLHASH
}

configuration & configuration::operator=(const configuration & other) {
	configuration temp(other);
	swap(temp);
	return *this;
}

configuration & configuration::operator+=(const configuration & other) {
	categories.insert(other.categories.begin(), other.categories.end());
	sof_comments.insert(sof_comments.end(), other.sof_comments.begin(), other.sof_comments.end());

	return *this;
}

configuration & configuration::operator-=(const configuration & other) {
	for(const auto & kv : other.categories)
		categories.erase(kv.first);

	for(const auto & cmt : other.sof_comments)
		sof_comments.erase(find(sof_comments.begin(), sof_comments.end(), cmt));

	return *this;
}

void configuration::load_properties(istream & from) {
	static const auto readfromline = [&](string & line, size_t lineno) {
		//
		static const auto is_comment       = CPPONFIG_CHARCACHED_REGEX("(?:[[:space:]]*(?:"s + chr + "[[:space:]]*(.*))?)?");
		static const auto is_tagless_start = CPPONFIG_TWOCHARCACHED_REGEX("[[:space:]]*\\"s + chr2 + "[[:space:]]*(?:\\" + chr1 + ".*)?");
		static const auto is_tagged_start  = CPPONFIG_TWOCHARCACHED_REGEX("[[:space:]]*([^[:space:]]+)[[:space:]]*\\"s + chr2 + "[[:space:]]*(?:\\" + chr1 + ".*)?");

		smatch match;
		if(regex_match(line, match, is_comment(comment_character)))
			return match.str(1);
		else if(regex_match(line, is_tagless_start(comment_character, category_start_character)))
			categories.emplace("", configuration_category()).first->second.load(from);
		else if(regex_match(line, match, is_tagged_start(comment_character, category_start_character)))
			categories.emplace(match.str(1), configuration_category()).first->second.load(from);
		else
			throw parsing_error("Line " + to_string(lineno) + " (\"" + line + "\") is not a comment nor a category start");
		return ""s;
	};

	size_t lineno = 1;
	for(string line; getline(from, line); ++lineno) {
		const auto & comment = readfromline(line, lineno);
		if(!comment.empty())
			sof_comments.emplace_back(comment);
		else
			break;
	}

	for(string line; getline(from, line); ++lineno)
		readfromline(line, lineno);
}

void configuration::save_properties(ostream & to) const {
	for(const auto & cmt : sof_comments)
		to << comment_character << ' ' << cmt << '\n';
	to << (sof_comments.empty() ? "" : "\n\n");
	for(const auto & pr : categories) {
		to << pr.first << (pr.first.empty() ? "" : " ") << category_start_character << '\n';
		pr.second.save(to);
		to << category_end_character << "\n\n";
	}

	actually_put_time(to, datetime_footer_type, comment_character);
}

bool configuration::load() {
	if(!filename.empty()) {
		ifstream file(filename);
		if(file && file.is_open()) {
			load_properties(file);
			return true;
		}
	}
	return false;
}

bool configuration::load(const string & name) {
	rename(name);
	return load();
}

bool configuration::load(istream & stream) {
	if(stream) {
		load_properties(stream);
		return true;
	}
	return false;
}

bool configuration::save() const {
	return save(filename);
}

bool configuration::save(const string & name) const {
	if(!name.empty()) {
		ofstream file(name);
		if(file && file.is_open()) {
			save_properties(file);
			return true;
		}
	}
	return false;
}

bool configuration::save(ostream & stream) const {
	if(stream) {
		save_properties(stream);
		return true;
	}
	return false;
}

property & configuration::get(const string & key, const string & default_value) {
	return get(key, property(trim(string(default_value))));
}

property & configuration::get(const string & key, const property & default_value) {
	const auto path = property_path(key);
	auto itr = categories.find(path.first);
	if(itr == categories.end()) {
		const auto kv = make_pair(path.second, default_value);
		itr           = categories.emplace(path.first, configuration_category(addressof(kv), addressof(kv) + 1)).first;
	}
	return itr->second.get(path.second, default_value);
}

void configuration::remove(const string & key) {
	const auto path = property_path(key);
	const auto itr = categories.find(path.first);
	if(itr != categories.end())
		itr->second.remove(path.second);
}

bool configuration::contains(const string & key) const {
	const auto path = property_path(key);
	const auto itr = categories.find(path.first);
	return itr != categories.end() && itr->second.contains(path.second);
}

void configuration::rename(const string & name) {
	filename = name;
}

bool configuration::empty() const {
	return sof_comments.empty() && all_of(categories.begin(), categories.end(), [](const auto & pr) { return pr.second.empty(); });
}

configuration operator+(const configuration & lhs, const configuration & rhs) {
	configuration temp(lhs);
	temp += rhs;
	return temp;
}

configuration operator-(const configuration & lhs, const configuration & rhs) {
	configuration temp(lhs);
	temp -= rhs;
	return temp;
}
<|endoftext|>


<commit_before>#if !defined ADBASE_METRICS_HPP_
# error "Not allow include this header."
#endif

#ifndef ADBASE_METRICS_METERS_HPP_
#define ADBASE_METRICS_METERS_HPP_

namespace adbase {

/**
 * @addtogroup metrics adbase::Metrics
 */
/*@{*/

namespace metrics {

class Counter;
class Metrics;
class Meters {
public:
	Meters(const std::string moduleName,
		   const std::string metricName,
		   Metrics* metrics);
	const std::string& getModuleName();
	const std::string& getMetricName();
	void mark();
	int64_t getCounter();
	~Meters();

private:
	std::string  _moduleName;
	std::string  _metricName;
	Counter* _counter;
	Metrics* _metrics;
};

}

/*@}*/

}

#endif
<commit_msg>forward compatibility update for g++ 5.4.1<commit_after>#if !defined ADBASE_METRICS_HPP_
# error "Not allow include this header."
#endif

#ifndef ADBASE_METRICS_METERS_HPP_
#define ADBASE_METRICS_METERS_HPP_

#include <numeric>

namespace adbase {

/**
 * @addtogroup metrics adbase::Metrics
 */
/*@{*/

namespace metrics {

class Counter;
class Metrics;
class Meters {
public:
	Meters(const std::string moduleName,
		   const std::string metricName,
		   Metrics* metrics);
	const std::string& getModuleName();
	const std::string& getMetricName();
	void mark();
	int64_t getCounter();
	~Meters();

private:
	std::string  _moduleName;
	std::string  _metricName;
	Counter* _counter;
	Metrics* _metrics;
};

}

/*@}*/

}

#endif
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkPluginActivator.h"
#include "DicomEventHandler.h"
#include <service/event/ctkEventConstants.h>
#include <ctkDictionary.h>
#include <mitkLogMacros.h>
#include <mitkDicomSeriesReader.h>
#include <mitkDataNode.h>
#include <QmitkBaseFunctionalityComponent.h>
#include <mitkIDataStorageService.h>
#include <service/event/ctkEventAdmin.h>
#include <ctkServiceReference.h>
#include <mitkRenderingManager.h>

DicomEventHandler::DicomEventHandler()
{
}

DicomEventHandler::~DicomEventHandler()
{
}

void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)
{
    QString patientName = ctkEvent.getProperty("PatientName").toString();
    QString studyUID = ctkEvent.getProperty("StudyUID").toString();
    QString studyName = ctkEvent.getProperty("StudyName").toString();
    QString seriesUID = ctkEvent.getProperty("SeriesUID").toString();
    QString seriesName = ctkEvent.getProperty("SeriesName").toString();
    QString path = ctkEvent.getProperty("Path").toString();

    std::list<std::string> qualifiedUIDs;
    mitk::DicomSeriesReader::StringContainer seriesToLoad;
    std::size_t found;

    mitk::DicomSeriesReader::UidFileNamesMap dicomSeriesMap = mitk::DicomSeriesReader::GetSeries(path.toStdString(),false);
    mitk::DicomSeriesReader::UidFileNamesMap::const_iterator qualifiedSeriesInstanceUIDIterator;

    for(qualifiedSeriesInstanceUIDIterator = dicomSeriesMap.begin();
        qualifiedSeriesInstanceUIDIterator != dicomSeriesMap.end();
        ++qualifiedSeriesInstanceUIDIterator)
    {
        found = qualifiedSeriesInstanceUIDIterator->first.find(seriesUID.toStdString());
        if(found!= qualifiedSeriesInstanceUIDIterator->first.npos)
        {
            qualifiedUIDs.push_back(qualifiedSeriesInstanceUIDIterator->first);
            seriesToLoad = qualifiedSeriesInstanceUIDIterator->second;
        }
    }

    mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad);
    if (node.IsNull())
    {
        MITK_ERROR << "Could not load series: " << seriesUID.toStdString();
    }
    else
    {
        ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
        mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);

        storageService->GetActiveDataStorage().GetPointer()->GetDataStorage()->Add(node);
        mitk::RenderingManager::GetInstance()->SetDataStorage(storageService->GetActiveDataStorage().GetPointer()->GetDataStorage());
        mitk::RenderingManager::GetInstance()->RequestUpdateAll();
    }
}

void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent)
{
}

void DicomEventHandler::SubscribeSlots()
{
    ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();
    if (ref)
    {
        ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);
        ctkDictionary properties;
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);
    }
}
<commit_msg>Initialize render windows. Global reinit is no longer needed<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkPluginActivator.h"
#include "DicomEventHandler.h"
#include <service/event/ctkEventConstants.h>
#include <ctkDictionary.h>
#include <mitkLogMacros.h>
#include <mitkDicomSeriesReader.h>
#include <mitkDataNode.h>
#include <QmitkBaseFunctionalityComponent.h>
#include <mitkIDataStorageService.h>
#include <service/event/ctkEventAdmin.h>
#include <ctkServiceReference.h>
#include <mitkRenderingManager.h>

DicomEventHandler::DicomEventHandler()
{
}

DicomEventHandler::~DicomEventHandler()
{
}

void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)
{
    QString patientName = ctkEvent.getProperty("PatientName").toString();
    QString studyUID = ctkEvent.getProperty("StudyUID").toString();
    QString studyName = ctkEvent.getProperty("StudyName").toString();
    QString seriesUID = ctkEvent.getProperty("SeriesUID").toString();
    QString seriesName = ctkEvent.getProperty("SeriesName").toString();
    QString path = ctkEvent.getProperty("Path").toString();

    std::list<std::string> qualifiedUIDs;
    mitk::DicomSeriesReader::StringContainer seriesToLoad;
    std::size_t found;

    mitk::DicomSeriesReader::UidFileNamesMap dicomSeriesMap = mitk::DicomSeriesReader::GetSeries(path.toStdString(),false);
    mitk::DicomSeriesReader::UidFileNamesMap::const_iterator qualifiedSeriesInstanceUIDIterator;

    for(qualifiedSeriesInstanceUIDIterator = dicomSeriesMap.begin();
        qualifiedSeriesInstanceUIDIterator != dicomSeriesMap.end();
        ++qualifiedSeriesInstanceUIDIterator)
    {
        found = qualifiedSeriesInstanceUIDIterator->first.find(seriesUID.toStdString());
        if(found!= qualifiedSeriesInstanceUIDIterator->first.npos)
        {
            qualifiedUIDs.push_back(qualifiedSeriesInstanceUIDIterator->first);
            seriesToLoad = qualifiedSeriesInstanceUIDIterator->second;
        }
    }

    mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad);
    if (node.IsNull())
    {
        MITK_ERROR << "Could not load series: " << seriesUID.toStdString();
    }
    else
    {
        //Get Reference for default data storage.
        ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
        mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
        mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();

        dataStorage->Add(node);

        // Initialize the RenderWindow
        mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll());
        mitk::RenderingManager::GetInstance()->InitializeViews(geometry);

    }
}

void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent)
{
}

void DicomEventHandler::SubscribeSlots()
{
    ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();
    if (ref)
    {
        ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);
        ctkDictionary properties;
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);
    }
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    SurfacePlusEdges.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

// This test draws a sphere in anaglyphic stereo (red-blue) mode using deering
// frustum.

#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkMatrix4x4.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkConeSource.h"
#include "vtkSphereSource.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, var) \
  vtkSmartPointer<type> var = vtkSmartPointer<type>::New()

int TestSplitViewportStereoHorizontal(int argc, char *argv[])
{
  double bottomLeft[3]  = {-2.0, -1.0, -1.0};
  double bottomRight[3] = { 2.0, -1.0, -1.0};
  double topRight[3]    = { 2.0,  1.0, -1.0};

  VTK_CREATE(vtkSphereSource, sphere1);
  sphere1->SetCenter(0.0, 0.0, -5.0);
  sphere1->SetRadius(15.0);
  sphere1->SetThetaResolution(40);
  sphere1->SetPhiResolution(40);

  VTK_CREATE(vtkPolyDataMapper, mapper1);
  mapper1->SetInputConnection(sphere1->GetOutputPort());

  VTK_CREATE(vtkActor, actor1);
  actor1->SetMapper(mapper1);
  actor1->GetProperty()->SetAmbient(0.1);
  actor1->GetProperty()->SetRepresentationToWireframe();
  actor1->GetProperty()->SetColor(0.8, 0.8, 0.0);

  VTK_CREATE(vtkConeSource, cone1);
  cone1->SetCenter(0.0, 0.0, -5.0);
  cone1->SetResolution(100);

  VTK_CREATE(vtkPolyDataMapper, mapper2);
  mapper2->SetInputConnection(cone1->GetOutputPort());

  VTK_CREATE(vtkActor, actor2);
  actor2->SetMapper(mapper2);
  actor2->GetProperty()->SetAmbient(0.1);

  VTK_CREATE(vtkRenderer, renderer);
  renderer->AddActor(actor1);
  renderer->AddActor(actor2);
  renderer->SetAmbient(1.0, 1.0, 1.0);

  // Introduce scale to test out calculation of clipping range
  // by vtkRenderer.
  VTK_CREATE(vtkMatrix4x4, scaleMatrix);
  scaleMatrix->SetElement(0, 0, 1);
  scaleMatrix->SetElement(1, 1, 1);
  scaleMatrix->SetElement(2, 2, 1);

  double eyePosition[3] = {0.0, 0.0, 5.0};

  vtkCamera *camera = renderer->GetActiveCamera();
  camera->SetScreenBottomLeft(bottomLeft);
  camera->SetScreenBottomRight(bottomRight);
  camera->SetScreenTopRight(topRight);
  camera->SetUseOffAxisProjection(1);
  camera->SetEyePosition(eyePosition);
  camera->SetEyeSeparation(0.05);
  camera->SetModelTransformMatrix(scaleMatrix);

  VTK_CREATE(vtkRenderWindow, renwin);
  renwin->AddRenderer(renderer);
  renwin->SetSize(400, 400);
  renwin->SetStereoRender(1);
  renwin->SetStereoTypeToSplitViewportHorizontal();

  VTK_CREATE(vtkRenderWindowInteractor, iren);
  iren->SetRenderWindow(renwin);
  renwin->Render();

  int retVal = vtkRegressionTestImage(renwin);
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    retVal = vtkRegressionTester::PASSED;
    }

  return (retVal == vtkRegressionTester::PASSED) ? 0 : 1;
}
<commit_msg>Initialize camera with reasonable parameters<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    SurfacePlusEdges.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

// This test draws a sphere in anaglyphic stereo (red-blue) mode using deering
// frustum.

#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkMatrix4x4.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkConeSource.h"
#include "vtkSphereSource.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, var) \
  vtkSmartPointer<type> var = vtkSmartPointer<type>::New()

int TestSplitViewportStereoHorizontal(int argc, char *argv[])
{
  double bottomLeft[3]  = {-2.0, -1.0, -1.0};
  double bottomRight[3] = { 2.0, -1.0, -1.0};
  double topRight[3]    = { 2.0,  1.0, -1.0};

  VTK_CREATE(vtkSphereSource, sphere1);
  sphere1->SetCenter(0.0, 0.0, -5.0);
  sphere1->SetRadius(15.0);
  sphere1->SetThetaResolution(40);
  sphere1->SetPhiResolution(40);

  VTK_CREATE(vtkPolyDataMapper, mapper1);
  mapper1->SetInputConnection(sphere1->GetOutputPort());

  VTK_CREATE(vtkActor, actor1);
  actor1->SetMapper(mapper1);
  actor1->GetProperty()->SetAmbient(0.1);
  actor1->GetProperty()->SetRepresentationToWireframe();
  actor1->GetProperty()->SetColor(0.8, 0.8, 0.0);

  VTK_CREATE(vtkConeSource, cone1);
  cone1->SetCenter(0.0, 0.0, -5.0);
  cone1->SetResolution(100);

  VTK_CREATE(vtkPolyDataMapper, mapper2);
  mapper2->SetInputConnection(cone1->GetOutputPort());

  VTK_CREATE(vtkActor, actor2);
  actor2->SetMapper(mapper2);
  actor2->GetProperty()->SetAmbient(0.1);

  VTK_CREATE(vtkRenderer, renderer);
  renderer->AddActor(actor1);
  renderer->AddActor(actor2);
  renderer->SetAmbient(1.0, 1.0, 1.0);

  VTK_CREATE(vtkRenderWindow, renwin);
  renwin->AddRenderer(renderer);
  renwin->SetSize(400, 400);
  renwin->SetStereoRender(1);
  renwin->SetStereoTypeToSplitViewportHorizontal();

  VTK_CREATE(vtkRenderWindowInteractor, iren);
  iren->SetRenderWindow(renwin);

  double eyePosition[3] = {0.0, 0.0, 5.0};

  vtkCamera *camera = renderer->GetActiveCamera();
  camera->SetScreenBottomLeft(bottomLeft);
  camera->SetScreenBottomRight(bottomRight);
  camera->SetScreenTopRight(topRight);
  camera->SetUseOffAxisProjection(1);
  camera->SetEyePosition(eyePosition);
  camera->SetEyeSeparation(0.05);
  camera->SetPosition(0.0, 0.0, 0.0);
  camera->SetFocalPoint(0.0, 0.0, -1.0);
  camera->SetViewUp(0.0, 1.0, 0.0);
  camera->SetViewAngle(30.0);

  renwin->Render();

  int retVal = vtkRegressionTestImage(renwin);
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    retVal = vtkRegressionTester::PASSED;
    }

  return (retVal == vtkRegressionTester::PASSED) ? 0 : 1;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtSparql/QtSparql>

// This is a tracker-specific header file. The test also needs to be linked
// against libqsparqltracker.so (not only libqtsparql.so).
#include "QtSparql/qsparql_tracker_signals.h"

//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this

//TESTED_FILES=

class Receiver : public QObject
{
    Q_OBJECT

public slots:
    void changed(QList<QTrackerChangeNotifier::Quad> d, QList<QTrackerChangeNotifier::Quad> i);
public:
    QList<QTrackerChangeNotifier::Quad> deletes;
    QList<QTrackerChangeNotifier::Quad> inserts;
};

void Receiver::changed(QList<QTrackerChangeNotifier::Quad> d, QList<QTrackerChangeNotifier::Quad> i)
{
    deletes.append(d);
    inserts.append(i);
}

class tst_QSparqlTrackerSignals : public QObject
{
    Q_OBJECT

public:
    tst_QSparqlTrackerSignals();
    virtual ~tst_QSparqlTrackerSignals();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

private slots:
    void contact_added();
private:
    QString className;
    int typeId, personContactId, nameGivenId;
};

tst_QSparqlTrackerSignals::tst_QSparqlTrackerSignals()
{
}

tst_QSparqlTrackerSignals::~tst_QSparqlTrackerSignals()
{
}

void tst_QSparqlTrackerSignals::initTestCase()
{
    // For running the test without installing the plugins. Should work in
    // normal and vpath builds.
    QCoreApplication::addLibraryPath("../../../plugins");

    // Query: what's the current name of the contacts class?
    QSparqlConnection conn("QTRACKER");
    QSparqlQuery q("select tracker:uri(tracker:id(nco:PersonContact)) "
                   "tracker:id(rdf:type) "
                   "tracker:id(nco:PersonContact) "
                   "tracker:id(nco:nameGiven) "
                   "{}");
    QSparqlResult* r = conn.exec(q);
    r->waitForFinished();
    if (r->hasError()) {
        qWarning() << r->lastError().message();
        qFatal("Initial query: error");
    }
    if (r->next() && r->current().count() == 4) {
        className = r->value(0).toString();
        typeId = r->value(1).toInt();
        personContactId = r->value(2).toInt();
        nameGivenId = r->value(3).toInt();
    }
    else
        qFatal("Initial query: not enough data");
    delete r;
}

void tst_QSparqlTrackerSignals::cleanupTestCase()
{
}

void tst_QSparqlTrackerSignals::init()
{
}

void tst_QSparqlTrackerSignals::cleanup()
{
}

// For QSignalSpy
Q_DECLARE_METATYPE(QList<QTrackerChangeNotifier::Quad>)

void tst_QSparqlTrackerSignals::contact_added()
{
    QTrackerChangeNotifier notifier(className);

    // For QSignalSpy
    qRegisterMetaType<QList<QTrackerChangeNotifier::Quad> >("QList<QTrackerChangeNotifier::Quad>");

    QSignalSpy spy(&notifier,
                   SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                  QList<QTrackerChangeNotifier::Quad>)));

    // TODO: also read the parameters from the spy.
    Receiver receiver;
    QObject::connect(&notifier,
                     SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                    QList<QTrackerChangeNotifier::Quad>)),
                     &receiver,
                     SLOT(changed(QList<QTrackerChangeNotifier::Quad>,
                                  QList<QTrackerChangeNotifier::Quad>)));

    // Now do an insert...
    QSparqlQuery q("insert { <added.uri> a nco:PersonContact ;"
                   "nie:isLogicalPartOf <qsparql-tracker-tests> ;"
                   "nco:nameGiven \"temp.name\" .}", QSparqlQuery::InsertStatement);
    QSparqlConnection conn("QTRACKER");
    QSparqlResult* r = conn.exec(q);
    QVERIFY(r != 0);
    QVERIFY(!r->hasError());
    r->waitForFinished();
    QVERIFY(!r->hasError());

    // And process the events so that
    // 1) tracker sends the signal through D-Bus
    // 2) QTrackerChangeNotifier gets the signal and sends it to the spy

    QTime timer;
    timer.start();
    while(timer.elapsed() < 5000 && !spy.count())
        QCoreApplication::processEvents();

    QCOMPARE(spy.count(), 1);

    QVERIFY(receiver.deletes.size() == 0);
    QVERIFY(receiver.inserts.size() == 3);

    // The triples that are inserted:
    // newid rdf:type nco:PersonContact
    // newid nie:isLogicalPartOf testcontext
    // newid nameGiven 0

    // The graph is the default graph
    QCOMPARE(receiver.inserts[0].graph, 0);
    QCOMPARE(receiver.inserts[1].graph, 0);
    QCOMPARE(receiver.inserts[2].graph, 0);

    // The newid is the same for all rows
    QCOMPARE(receiver.inserts[0].subject, receiver.inserts[1].subject);
    QCOMPARE(receiver.inserts[0].subject, receiver.inserts[2].subject);

    //qDebug() << receiver.inserts;

    bool typeFound = false;
    bool nameFound = false;
    for (int i=0; i<3; ++i) {
        if (receiver.inserts[i].predicate == typeId && receiver.inserts[i].object == personContactId)
            typeFound = true;
        else if (receiver.inserts[i].predicate == nameGivenId && receiver.inserts[i].object == 0)
            nameFound = true;
    }
    QVERIFY(typeFound);
    QVERIFY(nameFound);
}

QTEST_MAIN( tst_QSparqlTrackerSignals )
#include "tst_qsparql_tracker_signals.moc"
<commit_msg>More tests for the tracker signals.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtSparql/QtSparql>

// This is a tracker-specific header file. The test also needs to be linked
// against libqsparqltracker.so (not only libqtsparql.so).
#include "QtSparql/qsparql_tracker_signals.h"

//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this

//TESTED_FILES=

class Receiver : public QObject
{
    Q_OBJECT

public slots:
    void changed(QList<QTrackerChangeNotifier::Quad> d, QList<QTrackerChangeNotifier::Quad> i);
public:
    QList<QTrackerChangeNotifier::Quad> deletes;
    QList<QTrackerChangeNotifier::Quad> inserts;
};

void Receiver::changed(QList<QTrackerChangeNotifier::Quad> d, QList<QTrackerChangeNotifier::Quad> i)
{
    deletes.append(d);
    inserts.append(i);
}

class tst_QSparqlTrackerSignals : public QObject
{
    Q_OBJECT

public:
    tst_QSparqlTrackerSignals();
    virtual ~tst_QSparqlTrackerSignals();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

private slots:
    void contact_added();
    void contact_deleted();
private:
    QString className;
    int typeId, personContactId, nameGivenId;
};

tst_QSparqlTrackerSignals::tst_QSparqlTrackerSignals()
{
}

tst_QSparqlTrackerSignals::~tst_QSparqlTrackerSignals()
{
}

void tst_QSparqlTrackerSignals::initTestCase()
{
    // For running the test without installing the plugins. Should work in
    // normal and vpath builds.
    QCoreApplication::addLibraryPath("../../../plugins");

    // Query: what's the current name of the contacts class?
    QSparqlConnection conn("QTRACKER");
    QSparqlQuery q("select tracker:uri(tracker:id(nco:PersonContact)) "
                   "tracker:id(rdf:type) "
                   "tracker:id(nco:PersonContact) "
                   "tracker:id(nco:nameGiven) "
                   "{}");
    QSparqlResult* r = conn.exec(q);
    r->waitForFinished();
    if (r->hasError()) {
        qWarning() << r->lastError().message();
        qFatal("Initial query: error");
    }
    if (r->next() && r->current().count() == 4) {
        className = r->value(0).toString();
        typeId = r->value(1).toInt();
        personContactId = r->value(2).toInt();
        nameGivenId = r->value(3).toInt();
        // Useful prints for debugging
        //qDebug() << "PersonContact" << personContactId;
        //qDebug() << "type" << typeId;
        //qDebug() << "nameGiven" << nameGivenId;
    }
    else
        qFatal("Initial query: not enough data");
    delete r;
    // For QSignalSpy
    qRegisterMetaType<QList<QTrackerChangeNotifier::Quad> >("QList<QTrackerChangeNotifier::Quad>");
}

void tst_QSparqlTrackerSignals::cleanupTestCase()
{
}

void tst_QSparqlTrackerSignals::init()
{
}

void tst_QSparqlTrackerSignals::cleanup()
{
}

// For QSignalSpy
Q_DECLARE_METATYPE(QList<QTrackerChangeNotifier::Quad>)

void tst_QSparqlTrackerSignals::contact_added()
{
    QTrackerChangeNotifier notifier(className);

    QSignalSpy spy(&notifier,
                   SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                  QList<QTrackerChangeNotifier::Quad>)));

    // TODO: also read the parameters from the spy.
    Receiver receiver;
    QObject::connect(&notifier,
                     SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                    QList<QTrackerChangeNotifier::Quad>)),
                     &receiver,
                     SLOT(changed(QList<QTrackerChangeNotifier::Quad>,
                                  QList<QTrackerChangeNotifier::Quad>)));

    // Now do an insert...
    QSparqlQuery q("insert { <added.uri> a nco:PersonContact ;"
                   "nie:isLogicalPartOf <qsparql-tracker-tests> ;"
                   "nco:nameGiven \"temp.name\" .}", QSparqlQuery::InsertStatement);
    QSparqlConnection conn("QTRACKER");
    QSparqlResult* r = conn.exec(q);
    QVERIFY(r != 0);
    QVERIFY(!r->hasError());
    r->waitForFinished();
    QVERIFY(!r->hasError());
    delete r;
    r = 0;

    // And process the events so that
    // 1) tracker sends the signal through D-Bus
    // 2) QTrackerChangeNotifier gets the signal and sends it to the spy

    QTime timer;
    timer.start();
    while(timer.elapsed() < 5000 && !spy.count())
        QCoreApplication::processEvents();

    QCOMPARE(spy.count(), 1);

    QVERIFY(receiver.deletes.size() == 0);
    QVERIFY(receiver.inserts.size() == 3);

    // The triples that are inserted:
    // newid rdf:type nco:PersonContact
    // newid nie:isLogicalPartOf testcontext
    // newid nameGiven 0

    // The graph is the default graph
    QCOMPARE(receiver.inserts[0].graph, 0);
    QCOMPARE(receiver.inserts[1].graph, 0);
    QCOMPARE(receiver.inserts[2].graph, 0);

    // The newid is the same for all rows
    QCOMPARE(receiver.inserts[0].subject, receiver.inserts[1].subject);
    QCOMPARE(receiver.inserts[0].subject, receiver.inserts[2].subject);

    //qDebug() << receiver.inserts;

    bool typeFound = false;
    bool nameFound = false;
    for (int i=0; i<3; ++i) {
        if (receiver.inserts[i].predicate == typeId && receiver.inserts[i].object == personContactId)
            typeFound = true;
        else if (receiver.inserts[i].predicate == nameGivenId && receiver.inserts[i].object == 0)
            nameFound = true;
    }
    QVERIFY(typeFound);
    QVERIFY(nameFound);
}

void tst_QSparqlTrackerSignals::contact_deleted()
{
    // First insert some data so that we can delete it. We need to make sure
    // that it was properly inserted (and the appropriate signal was sent)
    // before starting the real test.
    QTrackerChangeNotifier dummyNotifier(className);
    QSignalSpy dummySpy(&dummyNotifier,
                        SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                       QList<QTrackerChangeNotifier::Quad>)));

    QSparqlQuery q("insert { <uri.to.delete> a nco:PersonContact ;"
                   "nie:isLogicalPartOf <qsparql-tracker-tests> ;"
                   "nco:nameGiven \"temp.name\" .}", QSparqlQuery::InsertStatement);
    QSparqlConnection conn("QTRACKER");
    QSparqlResult* r = conn.exec(q);
    QVERIFY(r != 0);
    QVERIFY(!r->hasError());
    r->waitForFinished();
    QVERIFY(!r->hasError());
    delete r;
    r = 0;

    QTime timer;
    timer.start();
    while(timer.elapsed() < 5000 && !dummySpy.count())
        QCoreApplication::processEvents();

    // Then start listening to changes
    QTrackerChangeNotifier notifier(className);
    QSignalSpy spy(&notifier,
                   SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                  QList<QTrackerChangeNotifier::Quad>)));

    // TODO: also read the parameters from the spy.
    Receiver receiver;
    QObject::connect(&notifier,
                     SIGNAL(changed(QList<QTrackerChangeNotifier::Quad>,
                                    QList<QTrackerChangeNotifier::Quad>)),
                     &receiver,
                     SLOT(changed(QList<QTrackerChangeNotifier::Quad>,
                                  QList<QTrackerChangeNotifier::Quad>)));

    // Then do the deletion. Delete in this order so that we will get all the
    // triples in the delete array. If we delete "<uri.to.delete> a
    // nco:PersonContact" first, we'll get only that triple.
    QSparqlQuery q2("delete { <uri.to.delete> nie:isLogicalPartOf ?lp ;"
                   "nco:nameGiven ?n ;"
                    "a nco:PersonContact .} where"
                   "{ <uri.to.delete> nie:isLogicalPartOf ?lp ;"
                   "nco:nameGiven ?n .}", QSparqlQuery::DeleteStatement);

    r = conn.exec(q2);
    QVERIFY(r != 0);
    QVERIFY(!r->hasError());
    r->waitForFinished();
    QVERIFY(!r->hasError());
    delete r;

    // And process the events so that
    // 1) tracker sends the signal through D-Bus
    // 2) QTrackerChangeNotifier gets the signal and sends it to the spy

    timer.start();
    while(timer.elapsed() < 5000 && !spy.count())
        QCoreApplication::processEvents();

    QCOMPARE(spy.count(), 1);

    //qDebug() << receiver.inserts;
    //qDebug() << receiver.deletes;

    QVERIFY(receiver.deletes.size() == 3);
    QVERIFY(receiver.inserts.size() == 0);

    // The triples that are deleted:
    // someid rdf:type nco:PersonContact
    // someid nie:isLogicalPartOf testcontext
    // someid nameGiven 0

    // The graph is the default graph
    QCOMPARE(receiver.deletes[0].graph, 0);
    QCOMPARE(receiver.deletes[1].graph, 0);
    QCOMPARE(receiver.deletes[2].graph, 0);

    // The someid is the same for all rows
    QCOMPARE(receiver.deletes[0].subject, receiver.deletes[1].subject);
    QCOMPARE(receiver.deletes[0].subject, receiver.deletes[2].subject);

    bool typeFound = false;
    bool nameFound = false;
    for (int i=0; i<3; ++i) {
        if (receiver.deletes[i].predicate == typeId && receiver.deletes[i].object == personContactId)
            typeFound = true;
        else if (receiver.deletes[i].predicate == nameGivenId && receiver.deletes[i].object == 0)
            nameFound = true;
    }
    QVERIFY(typeFound);
    QVERIFY(nameFound);
}

QTEST_MAIN( tst_QSparqlTrackerSignals )
#include "tst_qsparql_tracker_signals.moc"
<|endoftext|>