text stringlengths 54 60.6k |
|---|
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_attributes.h"
#include "condor_syscall_mode.h"
#include "exit.h"
#include "vanilla_proc.h"
#include "starter.h"
#include "syscall_numbers.h"
#include "directory.h"
extern CStarter *Starter;
VanillaProc::VanillaProc( ClassAd *jobAd ) : OsProc()
{
family = NULL;
filetrans = NULL;
JobAd = jobAd;
snapshot_tid = -1;
shadowupdate_tid = -1;
shadowsock = NULL;
TransferAtVacate = false;
}
VanillaProc::~VanillaProc()
{
if (family) {
delete family;
}
if (filetrans) {
delete filetrans;
}
if ( snapshot_tid != -1 ) {
daemonCore->Cancel_Timer(snapshot_tid);
snapshot_tid = -1;
}
if ( shadowupdate_tid != -1 ) {
daemonCore->Cancel_Timer(shadowupdate_tid);
shadowupdate_tid = -1;
}
if ( shadowsock ) {
delete shadowsock;
}
}
int
VanillaProc::TransferCompleted(FileTransfer *ftrans)
{
char tmp[_POSIX_ARG_MAX];
// Make certain the file transfer succeeded. It is
// completely wrong to ASSERT here if it failed since
// we are a _multi_ starter -- it is just a quick hack
// to get WinNT out the door.
if ( ftrans ) {
ASSERT( (ftrans->GetInfo()).success );
}
// vanilla jobs, unlike standard jobs, are allowed to run
// shell scripts (or as is the case on NT, batch files). so
// edit the ad so we start up a shell, pass the executable as
// an argument to the shell, if we are asked to run a .bat file.
#ifdef WIN32
char argstmp[_POSIX_ARG_MAX];
char systemshell[_POSIX_PATH_MAX];
int joblen = strlen(jobtmp);
if ( joblen > 5 &&
( (stricmp(".bat",&(jobtmp[joblen-4])) == 0) ||
(stricmp(".cmd",&(jobtmp[joblen-4])) == 0) ) ) {
// executable name ends in .bat or .cmd
// first change executable to be cmd.exe
::GetSystemDirectory(systemshell,MAX_PATH);
sprintf(tmp,"%s=\"%s\\cmd.exe\"",ATTR_JOB_CMD,systemshell);
JobAd->InsertOrUpdate(tmp);
// now change arguments to include name of program cmd.exe
// should run
if (JobAd->LookupString(ATTR_JOB_ARGUMENTS,argstmp) != 1) {
argstmp[0] = '\0';
}
// also pass /Q and /C arguments to cmd.exe, to tell it we do not
// want an interactive shell -- just run the command and exit
sprintf ( tmp, "%s=\"/Q /C condor_exec.bat %s\"",
ATTR_JOB_ARGUMENTS, argstmp );
JobAd->InsertOrUpdate(tmp);
// finally we must rename file condor_exec to condor_exec.bat
rename(CONDOR_EXEC,"condor_exec.bat");
dprintf(D_FULLDEBUG,
"Executable is .bat, so running %s\\cmd.exe %s\n",
systemshell,tmp);
} // end of if executable name ends in .bat
#endif
// call OsProc to start it up; if success, create the ProcFamily
if (OsProc::StartJob()) {
// success! create a ProcFamily
family = new ProcFamily(JobPid,PRIV_USER);
ASSERT(family);
#ifdef WIN32
// we only support running jobs as user nobody for the first pass
char nobody_login[60];
sprintf(nobody_login,"condor-run-dir_%d",daemonCore->getpid());
// set ProcFamily to find decendants via a common login name
family->setFamilyLogin(nobody_login);
#endif
// take a snapshot of the family every 15 seconds
snapshot_tid = daemonCore->Register_Timer(2, 15,
(TimerHandlercpp)&ProcFamily::takesnapshot,
"ProcFamily::takesnapshot", family);
// update the shadow every 20 minutes. years of study say
// this is the optimal value. :^).
shadowupdate_tid = daemonCore->Register_Timer(8,(20*60)+6,
(TimerHandlercpp)&VanillaProc::UpdateShadow,
"VanillaProc::UpdateShadow", this);
return TRUE;
} else {
// failure
// return FALSE;
// DREADFUL HACK: for now, if we fail to start the job,
// do an EXCEPT. Of course this is wrong for a multi-starter,
// this is just a quick hack to get the first pass at WinNT
// Condor out the door.
EXCEPT("Failed to start job");
}
return FALSE;
}
int
VanillaProc::StartJob()
{
int ret_value;
char tmp[_POSIX_ARG_MAX];
dprintf(D_FULLDEBUG,"in VanillaProc::StartJob()\n");
// for now, stash the executable in jobtmp, and switch the ad to
// say the executable is condor_exec
jobtmp[0] = '\0';
JobAd->LookupString(ATTR_JOB_CMD,jobtmp);
sprintf(tmp,"%s=\"%s\"",ATTR_JOB_CMD,CONDOR_EXEC);
JobAd->InsertOrUpdate(tmp);
// setup value for TransferAtVacate
tmp[0] = '\0';
JobAd->LookupString(ATTR_TRANSFER_FILES,tmp);
// if set to "ALWAYS", then set TransferAtVacate to true
if ( tmp[0]=='a' || tmp[0]=='A' ) {
TransferAtVacate = true;
}
// taken from OsProc::StartJob for now, here we create the user and
// set the acls on the starter directory _before_ we start placing
// files in there.
{
// we only support running jobs as user nobody for the first pass
char nobody_login[60];
sprintf(nobody_login,"condor-run-dir_%d",daemonCore->getpid());
init_user_nobody_loginname(nobody_login);
init_user_ids("nobody");
{
perm dirperm;
dirperm.init(nobody_login);
int ret_val = dirperm.set_acls(Starter->GetWorkingDir());
if ( ret_val < 0 ) {
EXCEPT("UNABLE TO SET PREMISSIONS ON STARTER DIRECTORY");
}
}
}
// if requested in the jobad, transfer files over
char TransSock[40];
if (JobAd->LookupString(ATTR_TRANSFER_SOCKET, TransSock) == 1) {
char buf[ATTRLIST_MAX_EXPRESSION];
// reset iwd of job to the starter directory
sprintf(buf,"%s=\"%s\"",ATTR_JOB_IWD,Starter->GetWorkingDir());
JobAd->InsertOrUpdate(buf);
filetrans = new FileTransfer();
ASSERT( filetrans->Init(JobAd) );
filetrans->RegisterCallback(
(FileTransferHandler)&VanillaProc::TransferCompleted,this);
ret_value = filetrans->DownloadFiles(false); // do not block
} else {
// no file transfer desired, thus the file transfer is "done"
ret_value = TransferCompleted(NULL);
}
return ret_value;
}
int
VanillaProc::UpdateShadow()
{
unsigned long max_image;
long sys_time, user_time;
unsigned int execsz = 0;
ClassAd ad;
char buf[200];
if ( ShadowAddr[0] == '\0' ) {
// we do not have an address for the shadow
return FALSE;
}
if ( !family ) {
// we do not have a job family beneath us
return FALSE;
}
if ( !shadowsock ) {
shadowsock = new SafeSock();
ASSERT(shadowsock);
shadowsock->connect(ShadowAddr);
}
family->get_cpu_usage(sys_time,user_time);
family->get_max_imagesize(max_image);
// create an ad
sprintf(buf,"%s=%lu",ATTR_JOB_REMOTE_SYS_CPU,sys_time);
ad.InsertOrUpdate(buf);
sprintf(buf,"%s=%lu",ATTR_JOB_REMOTE_USER_CPU,user_time);
ad.InsertOrUpdate(buf);
sprintf(buf,"%s=%lu",ATTR_IMAGE_SIZE,max_image);
ad.InsertOrUpdate(buf);
// if there is a filetrans object, then let's send the current
// size of the starter execute directory back to the shadow. this
// way the ATTR_DISK_USAGE will be updated, and we won't end
// up on a machine without enough local disk space.
if ( filetrans ) {
Directory starter_dir(Starter->GetWorkingDir(),PRIV_USER);
execsz = starter_dir.GetDirectorySize();
sprintf(buf,"%s=%u",ATTR_DISK_USAGE, (execsz+1023)/1024 );
ad.InsertOrUpdate(buf);
}
// send it to the shadow
dprintf(D_FULLDEBUG,
"Sending shadow update, user_time=%lu, image=%lu, execsz=%u\n",
user_time,max_image,execsz);
shadowsock->snd_int(SHADOW_UPDATEINFO,FALSE);
ad.put(*shadowsock);
shadowsock->end_of_message();
return TRUE;
}
int
VanillaProc::JobExit(int pid, int status)
{
dprintf(D_FULLDEBUG,"in VanillaProc::JobExit()\n");
// ok, the parent exited. make certain all decendants are dead.
family->hardkill();
// update the shadow one last time, then cancel timers & close sockets
UpdateShadow();
daemonCore->Cancel_Timer(snapshot_tid);
daemonCore->Cancel_Timer(shadowupdate_tid);
delete shadowsock;
snapshot_tid = -1;
shadowupdate_tid = -1;
shadowsock = NULL;
// transfer output files back if requested job really finished.
// may as well do this in the foreground,
// since we do not want to be interrupted by anything short of a hardkill.
if ( filetrans &&
((Requested_Exit != TRUE) || TransferAtVacate) ) {
// The user job may have created files only readable by the user,
// so set_user_priv here.
bool final_transfer = (Requested_Exit != TRUE); // true if job exited on its own
priv_state saved_priv = set_user_priv();
ASSERT( filetrans->UploadFiles(true, final_transfer) ); // this will block
set_priv(saved_priv);
}
if ( OsProc::JobExit(pid,status) ) {
return 1;
}
return 0;
}
void
VanillaProc::Suspend()
{
dprintf(D_FULLDEBUG,"in VanillaProc::Suspend()\n");
// suspend any filetransfer activity
if ( filetrans ) {
filetrans->Suspend();
}
// suspend the user job
if ( family ) {
family->suspend();
}
// set our flag
job_suspended = TRUE;
}
void
VanillaProc::Continue()
{
dprintf(D_FULLDEBUG,"in VanillaProc::Continue()\n");
// resume any filetransfer activity
if ( filetrans ) {
filetrans->Continue();
}
// resume user job
if ( family ) {
family->resume();
}
// set our flag
job_suspended = FALSE;
}
bool
VanillaProc::ShutdownGraceful()
{
dprintf(D_FULLDEBUG,"in VanillaProc::ShutdownGraceful()\n");
if ( !family ) {
// there is no process family yet, probably because we are still
// transferring files. just return true to say we're all done,
// and that way the starter class will simply delete us and the
// FileTransfer destructor will clean up.
return true;
}
// take a snapshot before we softkill the parent job process.
// this helps ensure that if the parent exits without killing
// the kids, our JobExit() handler will get em all.
family->takesnapshot();
// now softkill the parent job process. this is exactly what
// OsProc::ShutdownGraceful does, so call it.
return OsProc::ShutdownGraceful();
}
bool
VanillaProc::ShutdownFast()
{
dprintf(D_FULLDEBUG,"in VanillaProc::ShutdownFast()\n");
if ( !family ) {
// there is no process family yet, probably because we are still
// transferring files. just return true to say we're all done,
// and that way the starter class will simply delete us and the
// FileTransfer destructor will clean up.
return true;
}
// We purposely do not do a SIGCONT here, since there is no sense
// in potentially swapping the job back into memory if our next
// step is to hard kill it.
// Despite what the user wants, do not transfer back any files
// on a ShutdownFast.
TransferAtVacate = false;
Requested_Exit = TRUE;
family->hardkill();
return false; // shutdown is pending, so return false
}
<commit_msg>Added #ifdef WIN32 around code that was only for (you guessed it) WIN32.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_attributes.h"
#include "condor_syscall_mode.h"
#include "exit.h"
#include "vanilla_proc.h"
#include "starter.h"
#include "syscall_numbers.h"
#include "directory.h"
extern CStarter *Starter;
VanillaProc::VanillaProc( ClassAd *jobAd ) : OsProc()
{
family = NULL;
filetrans = NULL;
JobAd = jobAd;
snapshot_tid = -1;
shadowupdate_tid = -1;
shadowsock = NULL;
TransferAtVacate = false;
}
VanillaProc::~VanillaProc()
{
if (family) {
delete family;
}
if (filetrans) {
delete filetrans;
}
if ( snapshot_tid != -1 ) {
daemonCore->Cancel_Timer(snapshot_tid);
snapshot_tid = -1;
}
if ( shadowupdate_tid != -1 ) {
daemonCore->Cancel_Timer(shadowupdate_tid);
shadowupdate_tid = -1;
}
if ( shadowsock ) {
delete shadowsock;
}
}
int
VanillaProc::TransferCompleted(FileTransfer *ftrans)
{
char tmp[_POSIX_ARG_MAX];
// Make certain the file transfer succeeded. It is
// completely wrong to ASSERT here if it failed since
// we are a _multi_ starter -- it is just a quick hack
// to get WinNT out the door.
if ( ftrans ) {
ASSERT( (ftrans->GetInfo()).success );
}
// vanilla jobs, unlike standard jobs, are allowed to run
// shell scripts (or as is the case on NT, batch files). so
// edit the ad so we start up a shell, pass the executable as
// an argument to the shell, if we are asked to run a .bat file.
#ifdef WIN32
char argstmp[_POSIX_ARG_MAX];
char systemshell[_POSIX_PATH_MAX];
int joblen = strlen(jobtmp);
if ( joblen > 5 &&
( (stricmp(".bat",&(jobtmp[joblen-4])) == 0) ||
(stricmp(".cmd",&(jobtmp[joblen-4])) == 0) ) ) {
// executable name ends in .bat or .cmd
// first change executable to be cmd.exe
::GetSystemDirectory(systemshell,MAX_PATH);
sprintf(tmp,"%s=\"%s\\cmd.exe\"",ATTR_JOB_CMD,systemshell);
JobAd->InsertOrUpdate(tmp);
// now change arguments to include name of program cmd.exe
// should run
if (JobAd->LookupString(ATTR_JOB_ARGUMENTS,argstmp) != 1) {
argstmp[0] = '\0';
}
// also pass /Q and /C arguments to cmd.exe, to tell it we do not
// want an interactive shell -- just run the command and exit
sprintf ( tmp, "%s=\"/Q /C condor_exec.bat %s\"",
ATTR_JOB_ARGUMENTS, argstmp );
JobAd->InsertOrUpdate(tmp);
// finally we must rename file condor_exec to condor_exec.bat
rename(CONDOR_EXEC,"condor_exec.bat");
dprintf(D_FULLDEBUG,
"Executable is .bat, so running %s\\cmd.exe %s\n",
systemshell,tmp);
} // end of if executable name ends in .bat
#endif
// call OsProc to start it up; if success, create the ProcFamily
if (OsProc::StartJob()) {
// success! create a ProcFamily
family = new ProcFamily(JobPid,PRIV_USER);
ASSERT(family);
#ifdef WIN32
// we only support running jobs as user nobody for the first pass
char nobody_login[60];
sprintf(nobody_login,"condor-run-dir_%d",daemonCore->getpid());
// set ProcFamily to find decendants via a common login name
family->setFamilyLogin(nobody_login);
#endif
// take a snapshot of the family every 15 seconds
snapshot_tid = daemonCore->Register_Timer(2, 15,
(TimerHandlercpp)&ProcFamily::takesnapshot,
"ProcFamily::takesnapshot", family);
// update the shadow every 20 minutes. years of study say
// this is the optimal value. :^).
shadowupdate_tid = daemonCore->Register_Timer(8,(20*60)+6,
(TimerHandlercpp)&VanillaProc::UpdateShadow,
"VanillaProc::UpdateShadow", this);
return TRUE;
} else {
// failure
// return FALSE;
// DREADFUL HACK: for now, if we fail to start the job,
// do an EXCEPT. Of course this is wrong for a multi-starter,
// this is just a quick hack to get the first pass at WinNT
// Condor out the door.
EXCEPT("Failed to start job");
}
return FALSE;
}
int
VanillaProc::StartJob()
{
int ret_value;
char tmp[_POSIX_ARG_MAX];
dprintf(D_FULLDEBUG,"in VanillaProc::StartJob()\n");
// for now, stash the executable in jobtmp, and switch the ad to
// say the executable is condor_exec
jobtmp[0] = '\0';
JobAd->LookupString(ATTR_JOB_CMD,jobtmp);
sprintf(tmp,"%s=\"%s\"",ATTR_JOB_CMD,CONDOR_EXEC);
JobAd->InsertOrUpdate(tmp);
// setup value for TransferAtVacate
tmp[0] = '\0';
JobAd->LookupString(ATTR_TRANSFER_FILES,tmp);
// if set to "ALWAYS", then set TransferAtVacate to true
if ( tmp[0]=='a' || tmp[0]=='A' ) {
TransferAtVacate = true;
}
#ifdef WIN32
// taken from OsProc::StartJob for now, here we create the user and
// set the acls on the starter directory _before_ we start placing
// files in there.
{
// we only support running jobs as user nobody for the first pass
char nobody_login[60];
sprintf(nobody_login,"condor-run-dir_%d",daemonCore->getpid());
init_user_nobody_loginname(nobody_login);
init_user_ids("nobody");
{
perm dirperm;
dirperm.init(nobody_login);
int ret_val = dirperm.set_acls(Starter->GetWorkingDir());
if ( ret_val < 0 ) {
EXCEPT("UNABLE TO SET PREMISSIONS ON STARTER DIRECTORY");
}
}
}
#endif
// if requested in the jobad, transfer files over
char TransSock[40];
if (JobAd->LookupString(ATTR_TRANSFER_SOCKET, TransSock) == 1) {
char buf[ATTRLIST_MAX_EXPRESSION];
// reset iwd of job to the starter directory
sprintf(buf,"%s=\"%s\"",ATTR_JOB_IWD,Starter->GetWorkingDir());
JobAd->InsertOrUpdate(buf);
filetrans = new FileTransfer();
ASSERT( filetrans->Init(JobAd) );
filetrans->RegisterCallback(
(FileTransferHandler)&VanillaProc::TransferCompleted,this);
ret_value = filetrans->DownloadFiles(false); // do not block
} else {
// no file transfer desired, thus the file transfer is "done"
ret_value = TransferCompleted(NULL);
}
return ret_value;
}
int
VanillaProc::UpdateShadow()
{
unsigned long max_image;
long sys_time, user_time;
unsigned int execsz = 0;
ClassAd ad;
char buf[200];
if ( ShadowAddr[0] == '\0' ) {
// we do not have an address for the shadow
return FALSE;
}
if ( !family ) {
// we do not have a job family beneath us
return FALSE;
}
if ( !shadowsock ) {
shadowsock = new SafeSock();
ASSERT(shadowsock);
shadowsock->connect(ShadowAddr);
}
family->get_cpu_usage(sys_time,user_time);
family->get_max_imagesize(max_image);
// create an ad
sprintf(buf,"%s=%lu",ATTR_JOB_REMOTE_SYS_CPU,sys_time);
ad.InsertOrUpdate(buf);
sprintf(buf,"%s=%lu",ATTR_JOB_REMOTE_USER_CPU,user_time);
ad.InsertOrUpdate(buf);
sprintf(buf,"%s=%lu",ATTR_IMAGE_SIZE,max_image);
ad.InsertOrUpdate(buf);
// if there is a filetrans object, then let's send the current
// size of the starter execute directory back to the shadow. this
// way the ATTR_DISK_USAGE will be updated, and we won't end
// up on a machine without enough local disk space.
if ( filetrans ) {
Directory starter_dir(Starter->GetWorkingDir(),PRIV_USER);
execsz = starter_dir.GetDirectorySize();
sprintf(buf,"%s=%u",ATTR_DISK_USAGE, (execsz+1023)/1024 );
ad.InsertOrUpdate(buf);
}
// send it to the shadow
dprintf(D_FULLDEBUG,
"Sending shadow update, user_time=%lu, image=%lu, execsz=%u\n",
user_time,max_image,execsz);
shadowsock->snd_int(SHADOW_UPDATEINFO,FALSE);
ad.put(*shadowsock);
shadowsock->end_of_message();
return TRUE;
}
int
VanillaProc::JobExit(int pid, int status)
{
dprintf(D_FULLDEBUG,"in VanillaProc::JobExit()\n");
// ok, the parent exited. make certain all decendants are dead.
family->hardkill();
// update the shadow one last time, then cancel timers & close sockets
UpdateShadow();
daemonCore->Cancel_Timer(snapshot_tid);
daemonCore->Cancel_Timer(shadowupdate_tid);
delete shadowsock;
snapshot_tid = -1;
shadowupdate_tid = -1;
shadowsock = NULL;
// transfer output files back if requested job really finished.
// may as well do this in the foreground,
// since we do not want to be interrupted by anything short of a hardkill.
if ( filetrans &&
((Requested_Exit != TRUE) || TransferAtVacate) ) {
// The user job may have created files only readable by the user,
// so set_user_priv here.
// true if job exited on its own
bool final_transfer = (Requested_Exit != TRUE);
priv_state saved_priv = set_user_priv();
// this will block
ASSERT( filetrans->UploadFiles(true, final_transfer) );
set_priv(saved_priv);
}
if ( OsProc::JobExit(pid,status) ) {
return 1;
}
return 0;
}
void
VanillaProc::Suspend()
{
dprintf(D_FULLDEBUG,"in VanillaProc::Suspend()\n");
// suspend any filetransfer activity
if ( filetrans ) {
filetrans->Suspend();
}
// suspend the user job
if ( family ) {
family->suspend();
}
// set our flag
job_suspended = TRUE;
}
void
VanillaProc::Continue()
{
dprintf(D_FULLDEBUG,"in VanillaProc::Continue()\n");
// resume any filetransfer activity
if ( filetrans ) {
filetrans->Continue();
}
// resume user job
if ( family ) {
family->resume();
}
// set our flag
job_suspended = FALSE;
}
bool
VanillaProc::ShutdownGraceful()
{
dprintf(D_FULLDEBUG,"in VanillaProc::ShutdownGraceful()\n");
if ( !family ) {
// there is no process family yet, probably because we are still
// transferring files. just return true to say we're all done,
// and that way the starter class will simply delete us and the
// FileTransfer destructor will clean up.
return true;
}
// take a snapshot before we softkill the parent job process.
// this helps ensure that if the parent exits without killing
// the kids, our JobExit() handler will get em all.
family->takesnapshot();
// now softkill the parent job process. this is exactly what
// OsProc::ShutdownGraceful does, so call it.
return OsProc::ShutdownGraceful();
}
bool
VanillaProc::ShutdownFast()
{
dprintf(D_FULLDEBUG,"in VanillaProc::ShutdownFast()\n");
if ( !family ) {
// there is no process family yet, probably because we are still
// transferring files. just return true to say we're all done,
// and that way the starter class will simply delete us and the
// FileTransfer destructor will clean up.
return true;
}
// We purposely do not do a SIGCONT here, since there is no sense
// in potentially swapping the job back into memory if our next
// step is to hard kill it.
// Despite what the user wants, do not transfer back any files
// on a ShutdownFast.
TransferAtVacate = false;
Requested_Exit = TRUE;
family->hardkill();
return false; // shutdown is pending, so return false
}
<|endoftext|> |
<commit_before>#ifndef MODIFIERNAME_HPP
#define MODIFIERNAME_HPP
#include "KeyCode.hpp"
#include "strlcpy_utf8.hpp"
namespace org_pqrs_Karabiner {
class ModifierName {
public:
class Item {
public:
Item(void) {
name_[0] = '\0';
}
Item(ModifierFlag modifierFlag, const char* name) : modifierFlag_(modifierFlag) {
pqrs::strlcpy_utf8::strlcpy(name_, name, sizeof(name_));
}
Item(ModifierFlag modifierFlag, const uint32_t* name, size_t size) : modifierFlag_(modifierFlag) {
char* tmp = new char[size + 1];
{
for (size_t i = 0; i < size; ++i) {
tmp[i] = name[i];
}
tmp[size] = '\0';
pqrs::strlcpy_utf8::strlcpy(name_, tmp, sizeof(name_));
}
delete[] tmp;
}
ModifierFlag getModifierFlag(void) const { return modifierFlag_; }
const char* getName(void) const { return name_; }
private:
enum {
MAXLEN = 32,
};
ModifierFlag modifierFlag_;
char name_[MAXLEN];
};
DECLARE_VECTOR(Item);
static void initialize(void) {
clearVirtualModifiers();
}
static void clearVirtualModifiers(void);
static void registerVirtualModifier(ModifierFlag modifierFlag, const uint32_t* name, size_t size);
static const char* getName(ModifierFlag modifierFlag);
private:
static Vector_Item items_;
};
}
#endif
<commit_msg>check args<commit_after>#ifndef MODIFIERNAME_HPP
#define MODIFIERNAME_HPP
#include "IOLogWrapper.hpp"
#include "KeyCode.hpp"
#include "strlcpy_utf8.hpp"
namespace org_pqrs_Karabiner {
class ModifierName {
public:
class Item {
public:
Item(void) {
name_[0] = '\0';
}
Item(ModifierFlag modifierFlag, const char* name) : modifierFlag_(modifierFlag) {
if (name) {
pqrs::strlcpy_utf8::strlcpy(name_, name, sizeof(name_));
}
}
Item(ModifierFlag modifierFlag, const uint32_t* name, size_t size) : modifierFlag_(modifierFlag) {
if (name) {
char* tmp = new char[size + 1];
if (! tmp) {
IOLOG_ERROR("ModifierName: Failed to allocate: %p, %ld", name, size);
} else {
for (size_t i = 0; i < size; ++i) {
tmp[i] = name[i];
}
tmp[size] = '\0';
pqrs::strlcpy_utf8::strlcpy(name_, tmp, sizeof(name_));
delete[] tmp;
}
}
}
ModifierFlag getModifierFlag(void) const { return modifierFlag_; }
const char* getName(void) const { return name_; }
private:
enum {
MAXLEN = 32,
};
ModifierFlag modifierFlag_;
char name_[MAXLEN];
};
DECLARE_VECTOR(Item);
static void initialize(void) {
clearVirtualModifiers();
}
static void clearVirtualModifiers(void);
static void registerVirtualModifier(ModifierFlag modifierFlag, const uint32_t* name, size_t size);
static const char* getName(ModifierFlag modifierFlag);
private:
static Vector_Item items_;
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2008 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
/** @cond DEV */
#include "base/util/StringMap.h"
BEGIN_NAMESPACE
const static StringBuffer nullVal(NULL);
// Find the element in the StringMap with the given key.
int StringMap::findElement(const char *key) {
KeyValuePair *e;
int i=0;
for (e=(KeyValuePair*)c.front(); e; e=(KeyValuePair*)c.next()) {
if ( e->getKey() == key ) {
return i; // item found
}
i++;
}
return -1;
}
// Add a new element to the StringMap, or modify an existent one
bool StringMap::put(const char *key, const char *val) {
int index = findElement(key);
if(index != -1) {
((KeyValuePair*)c[index])->setValue(val);
return false;
}
else {
c.add(KeyValuePair(key, val));
return true;
}
}
// Remove an element from the StringMap, if exists
bool StringMap::remove(const char *key) {
int index = findElement(key);
if(index != -1) {
if(c.removeElementAt(index) != -1){
return true; // Success
}
}
return false; // Not found or failure
}
// Retrieve an element from the StringMap, if exists.
const StringBuffer& StringMap::get(const char *key) {
int index = findElement(key);
if(index != -1) {
return ((KeyValuePair*)c[index])->getValue();
}
else {
return nullVal;
}
}
END_NAMESPACE
/** @endcond */
<commit_msg>Fixed build error on gcc.<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2008 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
/** @cond DEV */
#include "base/util/StringMap.h"
BEGIN_NAMESPACE
const static StringBuffer nullVal(NULL);
// Find the element in the StringMap with the given key.
int StringMap::findElement(const char *key) {
KeyValuePair *e;
int i=0;
for (e=(KeyValuePair*)c.front(); e; e=(KeyValuePair*)c.next()) {
if ( e->getKey() == key ) {
return i; // item found
}
i++;
}
return -1;
}
// Add a new element to the StringMap, or modify an existent one
bool StringMap::put(const char *key, const char *val) {
int index = findElement(key);
if(index != -1) {
((KeyValuePair*)c[index])->setValue(val);
return false;
}
else {
KeyValuePair kv(key, val);
c.add(kv);
return true;
}
}
// Remove an element from the StringMap, if exists
bool StringMap::remove(const char *key) {
int index = findElement(key);
if(index != -1) {
if(c.removeElementAt(index) != -1){
return true; // Success
}
}
return false; // Not found or failure
}
// Retrieve an element from the StringMap, if exists.
const StringBuffer& StringMap::get(const char *key) {
int index = findElement(key);
if(index != -1) {
return ((KeyValuePair*)c[index])->getValue();
}
else {
return nullVal;
}
}
END_NAMESPACE
/** @endcond */
<|endoftext|> |
<commit_before>/*
* RStudioAPI.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/Macros.hpp>
#include <core/Algorithm.hpp>
#include <core/Debug.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RExec.hpp>
#include <r/RJson.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rstudioapi {
namespace {
module_context::WaitForMethodFunction s_waitForShowDialog;
module_context::WaitForMethodFunction s_waitForOpenFileDialog;
} // end anonymous namespace
ClientEvent showDialogEvent(const std::string& title,
const std::string& message,
int dialogIcon,
bool prompt,
const std::string& promptDefault,
const std::string& ok,
const std::string& cancel,
const std::string& url)
{
json::Object data;
data["title"] = title;
data["message"] = message;
data["dialogIcon"] = dialogIcon;
data["prompt"] = prompt;
data["default"] = promptDefault;
data["ok"] = ok;
data["cancel"] = cancel;
data["url"] = url;
return ClientEvent(client_events::kRStudioAPIShowDialog, data);
}
SEXP rs_showDialog(SEXP titleSEXP,
SEXP messageSEXP,
SEXP dialogIconSEXP,
SEXP promptSEXP,
SEXP promptDefaultSEXP,
SEXP okSEXP,
SEXP cancelSEXP,
SEXP urlSEXP)
{
try
{
std::string title = r::sexp::asString(titleSEXP);
std::string message = r::sexp::asString(messageSEXP);
int dialogIcon = r::sexp::asInteger(dialogIconSEXP);
bool prompt = r::sexp::asLogical(promptSEXP);
std::string promptDefault = r::sexp::asString(promptDefaultSEXP);
std::string ok = r::sexp::asString(okSEXP);
std::string cancel = r::sexp::asString(cancelSEXP);
std::string url = r::sexp::asString(urlSEXP);
ClientEvent event = showDialogEvent(
title,
message,
dialogIcon,
prompt,
promptDefault,
ok,
cancel,
url);
// wait for rstudioapi_show_dialog_completed
json::JsonRpcRequest request;
if (!s_waitForShowDialog(&request, event))
{
return R_NilValue;
}
if (dialogIcon == 4 && !request.params[1].is_null()) {
bool result;
Error error = json::readParam(request.params, 1, &result);
if (error)
{
LOG_ERROR(error);
return R_NilValue;
}
r::sexp::Protect rProtect;
return r::sexp::create(result, &rProtect);
}
else if (!request.params[0].is_null())
{
std::string promptValue;
Error error = json::readParam(request.params, 0, &promptValue);
if (error)
{
LOG_ERROR(error);
return R_NilValue;
}
r::sexp::Protect rProtect;
return r::sexp::create(promptValue, &rProtect);
}
}
CATCH_UNEXPECTED_EXCEPTION
return R_NilValue;
}
SEXP rs_openFileDialog(SEXP typeSEXP,
SEXP captionSEXP,
SEXP labelSEXP,
SEXP pathSEXP,
SEXP filterSEXP,
SEXP existingSEXP)
{
// extract components
int type = r::sexp::asInteger(typeSEXP);
std::string caption = r::sexp::asString(captionSEXP);
std::string label = r::sexp::asString(labelSEXP);
std::string path = r::sexp::asString(pathSEXP);
std::string filter = r::sexp::asString(filterSEXP);
bool existing = r::sexp::asLogical(existingSEXP);
// default to all files when filter is empty
if (filter.empty())
filter = "All Files (*)";
// when path is empty, use project path if available, user home path
// otherwise
FilePath filePath;
if (path.empty())
{
if (projects::projectContext().hasProject())
filePath = projects::projectContext().directory();
else
filePath = module_context::userHomePath();
}
else
{
filePath = module_context::resolveAliasedPath(path);
}
json::Object data;
data["type"] = type;
data["caption"] = caption;
data["label"] = label;
data["file"] = module_context::createFileSystemItem(filePath);
data["filter"] = filter;
data["existing"] = existing;
ClientEvent event(client_events::kOpenFileDialog, data);
json::JsonRpcRequest request;
if (!s_waitForOpenFileDialog(&request, event))
return R_NilValue;
std::string selection;
Error error = json::readParams(request.params, &selection);
if (error)
LOG_ERROR(error);
if (selection.empty())
return R_NilValue;
r::sexp::Protect protect;
return r::sexp::create(selection, &protect);
}
Error initialize()
{
using boost::bind;
using namespace module_context;
// register waitForMethod handler
s_waitForShowDialog = registerWaitForMethod("rstudioapi_show_dialog_completed");
s_waitForOpenFileDialog = registerWaitForMethod("open_file_dialog_completed");
RS_REGISTER_CALL_METHOD(rs_showDialog, 8);
RS_REGISTER_CALL_METHOD(rs_openFileDialog, 6);
return Success();
}
} // namespace connections
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>safeAsString for NULLs<commit_after>/*
* RStudioAPI.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/Macros.hpp>
#include <core/Algorithm.hpp>
#include <core/Debug.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RExec.hpp>
#include <r/RJson.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rstudioapi {
namespace {
module_context::WaitForMethodFunction s_waitForShowDialog;
module_context::WaitForMethodFunction s_waitForOpenFileDialog;
} // end anonymous namespace
ClientEvent showDialogEvent(const std::string& title,
const std::string& message,
int dialogIcon,
bool prompt,
const std::string& promptDefault,
const std::string& ok,
const std::string& cancel,
const std::string& url)
{
json::Object data;
data["title"] = title;
data["message"] = message;
data["dialogIcon"] = dialogIcon;
data["prompt"] = prompt;
data["default"] = promptDefault;
data["ok"] = ok;
data["cancel"] = cancel;
data["url"] = url;
return ClientEvent(client_events::kRStudioAPIShowDialog, data);
}
SEXP rs_showDialog(SEXP titleSEXP,
SEXP messageSEXP,
SEXP dialogIconSEXP,
SEXP promptSEXP,
SEXP promptDefaultSEXP,
SEXP okSEXP,
SEXP cancelSEXP,
SEXP urlSEXP)
{
try
{
std::string title = r::sexp::asString(titleSEXP);
std::string message = r::sexp::asString(messageSEXP);
int dialogIcon = r::sexp::asInteger(dialogIconSEXP);
bool prompt = r::sexp::asLogical(promptSEXP);
std::string promptDefault = r::sexp::asString(promptDefaultSEXP);
std::string ok = r::sexp::asString(okSEXP);
std::string cancel = r::sexp::asString(cancelSEXP);
std::string url = r::sexp::asString(urlSEXP);
ClientEvent event = showDialogEvent(
title,
message,
dialogIcon,
prompt,
promptDefault,
ok,
cancel,
url);
// wait for rstudioapi_show_dialog_completed
json::JsonRpcRequest request;
if (!s_waitForShowDialog(&request, event))
{
return R_NilValue;
}
if (dialogIcon == 4 && !request.params[1].is_null()) {
bool result;
Error error = json::readParam(request.params, 1, &result);
if (error)
{
LOG_ERROR(error);
return R_NilValue;
}
r::sexp::Protect rProtect;
return r::sexp::create(result, &rProtect);
}
else if (!request.params[0].is_null())
{
std::string promptValue;
Error error = json::readParam(request.params, 0, &promptValue);
if (error)
{
LOG_ERROR(error);
return R_NilValue;
}
r::sexp::Protect rProtect;
return r::sexp::create(promptValue, &rProtect);
}
}
CATCH_UNEXPECTED_EXCEPTION
return R_NilValue;
}
SEXP rs_openFileDialog(SEXP typeSEXP,
SEXP captionSEXP,
SEXP labelSEXP,
SEXP pathSEXP,
SEXP filterSEXP,
SEXP existingSEXP)
{
// extract components
int type = r::sexp::asInteger(typeSEXP);
std::string caption = r::sexp::asString(captionSEXP);
std::string label = r::sexp::asString(labelSEXP);
std::string path = r::sexp::safeAsString(pathSEXP);
std::string filter = r::sexp::safeAsString(filterSEXP);
bool existing = r::sexp::asLogical(existingSEXP);
// default to all files when filter is empty
if (filter.empty())
filter = "All Files (*)";
// when path is empty, use project path if available, user home path
// otherwise
FilePath filePath;
if (path.empty())
{
if (projects::projectContext().hasProject())
filePath = projects::projectContext().directory();
else
filePath = module_context::userHomePath();
}
else
{
filePath = module_context::resolveAliasedPath(path);
}
json::Object data;
data["type"] = type;
data["caption"] = caption;
data["label"] = label;
data["file"] = module_context::createFileSystemItem(filePath);
data["filter"] = filter;
data["existing"] = existing;
ClientEvent event(client_events::kOpenFileDialog, data);
json::JsonRpcRequest request;
if (!s_waitForOpenFileDialog(&request, event))
return R_NilValue;
std::string selection;
Error error = json::readParams(request.params, &selection);
if (error)
LOG_ERROR(error);
if (selection.empty())
return R_NilValue;
r::sexp::Protect protect;
return r::sexp::create(selection, &protect);
}
Error initialize()
{
using boost::bind;
using namespace module_context;
// register waitForMethod handler
s_waitForShowDialog = registerWaitForMethod("rstudioapi_show_dialog_completed");
s_waitForOpenFileDialog = registerWaitForMethod("open_file_dialog_completed");
RS_REGISTER_CALL_METHOD(rs_showDialog, 8);
RS_REGISTER_CALL_METHOD(rs_openFileDialog, 6);
return Success();
}
} // namespace connections
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "fnord/test/unittest.h"
#include "fnord/protobuf/MessageEncoder.h"
#include "fnord/protobuf/MessagePrinter.h"
#include "tsdb/RecordSet.h"
#include "cstable/CSTableReader.h"
#include "cstable/CSTableBuilder.h"
#include "cstable/RecordMaterializer.h"
#include "cstable/StringColumnReader.h"
using namespace fnord;
using namespace fnord::cstable;
using namespace fnord::msg;
UNIT_TEST(RecordMaterializerTest);
TEST_CASE(RecordMaterializerTest, TestSimpleReMaterialization, [] () {
String testfile = "/tmp/__fnord_testcstablematerialization.cst";
msg::MessageSchemaField level1(
1,
"level1",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level1_str(
2,
"str",
msg::FieldType::STRING,
1024,
true,
false);
level1.schema = new MessageSchema(
"Level1",
Vector<msg::MessageSchemaField> { level1_str });
msg::MessageSchema schema(
"TestSchema",
Vector<msg::MessageSchemaField> { level1 });
msg::MessageObject sobj;
auto& l1_a = sobj.addChild(1);
l1_a.addChild(2, "fnord1");
l1_a.addChild(2, "fnord2");
auto& l1_b = sobj.addChild(1);
l1_b.addChild(2, "fnord3");
l1_b.addChild(2, "fnord4");
cstable::CSTableBuilder builder(&schema);
builder.addRecord(sobj);
builder.write(testfile);
cstable::CSTableReader reader(testfile);
cstable::RecordMaterializer materializer(&schema, &reader);
msg::MessageObject robj;
materializer.nextRecord(&robj);
EXPECT_EQ(robj.asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asString(), "fnord1");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asString(), "fnord2");
EXPECT_EQ(robj.asObject()[1].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[1].asObject()[0].asString(), "fnord3");
EXPECT_EQ(robj.asObject()[1].asObject()[1].asString(), "fnord4");
});
TEST_CASE(RecordMaterializerTest, TestSimpleReMaterializationWithNull, [] () {
String testfile = "/tmp/__fnord_testcstablematerialization.cst";
msg::MessageSchemaField level1(
1,
"level1",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level1_str(
2,
"str",
msg::FieldType::STRING,
1024,
true,
false);
level1.schema = new MessageSchema(
"Level1",
Vector<msg::MessageSchemaField> { level1_str });
msg::MessageSchema schema(
"TestSchema",
Vector<msg::MessageSchemaField> { level1 });
msg::MessageObject sobj;
auto& l1_a = sobj.addChild(1);
l1_a.addChild(2, "fnord1");
l1_a.addChild(2, "fnord2");
auto& l1_b = sobj.addChild(1);
auto& l1_c = sobj.addChild(1);
l1_c.addChild(2, "fnord3");
l1_c.addChild(2, "fnord4");
cstable::CSTableBuilder builder(&schema);
builder.addRecord(sobj);
builder.write(testfile);
cstable::CSTableReader reader(testfile);
cstable::RecordMaterializer materializer(&schema, &reader);
msg::MessageObject robj;
materializer.nextRecord(&robj);
EXPECT_EQ(robj.asObject().size(), 3);
EXPECT_EQ(robj.asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asString(), "fnord1");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asString(), "fnord2");
EXPECT_EQ(robj.asObject()[1].asObject().size(), 0);
EXPECT_EQ(robj.asObject()[2].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[2].asObject()[0].asString(), "fnord3");
EXPECT_EQ(robj.asObject()[2].asObject()[1].asString(), "fnord4");
});
TEST_CASE(RecordMaterializerTest, TestReMatWithNonRepeatedParent, [] () {
String testfile = "/tmp/__fnord_testcstablematerialization.cst";
msg::MessageSchemaField level1(
1,
"level1",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level2(
2,
"level2",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level2_str(
3,
"str",
msg::FieldType::STRING,
1024,
true,
false);
level2.schema = new MessageSchema(
"Level2",
Vector<msg::MessageSchemaField> { level2_str });
level1.schema = new MessageSchema(
"Level1",
Vector<msg::MessageSchemaField> { level2 });
msg::MessageSchema schema(
"TestSchema",
Vector<msg::MessageSchemaField> { level1 });
msg::MessageObject sobj;
auto& l1_a = sobj.addChild(1);
auto& l2_aa = l1_a.addChild(2);
l2_aa.addChild(3, "fnord1");
l2_aa.addChild(3, "fnord2");
auto& l2_ab = l1_a.addChild(2);
l2_ab.addChild(3, "fnord3");
l2_ab.addChild(3, "fnord4");
auto& l1_b = sobj.addChild(1);
auto& l1_c = sobj.addChild(1);
auto& l2_ca = l1_c.addChild(2);
auto& l2_cb = l1_c.addChild(2);
l2_cb.addChild(3, "fnord5");
l2_cb.addChild(3, "fnord6");
cstable::CSTableBuilder builder(&schema);
builder.addRecord(sobj);
builder.write(testfile);
cstable::CSTableReader reader(testfile);
cstable::RecordMaterializer materializer(&schema, &reader);
msg::MessageObject robj;
materializer.nextRecord(&robj);
EXPECT_EQ(robj.asObject().size(), 3);
EXPECT_EQ(robj.asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asObject()[0].asString(), "fnord1");
EXPECT_EQ(robj.asObject()[0].asObject()[0].asObject()[1].asString(), "fnord2");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[1].asObject()[0].asString(), "fnord3");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asObject()[1].asString(), "fnord4");
EXPECT_EQ(robj.asObject()[1].asObject().size(), 0);
EXPECT_EQ(robj.asObject()[2].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[2].asObject()[0].asObject().size(), 0);
EXPECT_EQ(robj.asObject()[2].asObject()[1].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[2].asObject()[1].asObject()[0].asString(), "fnord5");
EXPECT_EQ(robj.asObject()[2].asObject()[1].asObject()[1].asString(), "fnord6");
});
<commit_msg>remove dead include<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "fnord/test/unittest.h"
#include "fnord/protobuf/MessageEncoder.h"
#include "fnord/protobuf/MessagePrinter.h"
#include "cstable/CSTableReader.h"
#include "cstable/CSTableBuilder.h"
#include "cstable/RecordMaterializer.h"
#include "cstable/StringColumnReader.h"
using namespace fnord;
using namespace fnord::cstable;
using namespace fnord::msg;
UNIT_TEST(RecordMaterializerTest);
TEST_CASE(RecordMaterializerTest, TestSimpleReMaterialization, [] () {
String testfile = "/tmp/__fnord_testcstablematerialization.cst";
msg::MessageSchemaField level1(
1,
"level1",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level1_str(
2,
"str",
msg::FieldType::STRING,
1024,
true,
false);
level1.schema = new MessageSchema(
"Level1",
Vector<msg::MessageSchemaField> { level1_str });
msg::MessageSchema schema(
"TestSchema",
Vector<msg::MessageSchemaField> { level1 });
msg::MessageObject sobj;
auto& l1_a = sobj.addChild(1);
l1_a.addChild(2, "fnord1");
l1_a.addChild(2, "fnord2");
auto& l1_b = sobj.addChild(1);
l1_b.addChild(2, "fnord3");
l1_b.addChild(2, "fnord4");
cstable::CSTableBuilder builder(&schema);
builder.addRecord(sobj);
builder.write(testfile);
cstable::CSTableReader reader(testfile);
cstable::RecordMaterializer materializer(&schema, &reader);
msg::MessageObject robj;
materializer.nextRecord(&robj);
EXPECT_EQ(robj.asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asString(), "fnord1");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asString(), "fnord2");
EXPECT_EQ(robj.asObject()[1].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[1].asObject()[0].asString(), "fnord3");
EXPECT_EQ(robj.asObject()[1].asObject()[1].asString(), "fnord4");
});
TEST_CASE(RecordMaterializerTest, TestSimpleReMaterializationWithNull, [] () {
String testfile = "/tmp/__fnord_testcstablematerialization.cst";
msg::MessageSchemaField level1(
1,
"level1",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level1_str(
2,
"str",
msg::FieldType::STRING,
1024,
true,
false);
level1.schema = new MessageSchema(
"Level1",
Vector<msg::MessageSchemaField> { level1_str });
msg::MessageSchema schema(
"TestSchema",
Vector<msg::MessageSchemaField> { level1 });
msg::MessageObject sobj;
auto& l1_a = sobj.addChild(1);
l1_a.addChild(2, "fnord1");
l1_a.addChild(2, "fnord2");
auto& l1_b = sobj.addChild(1);
auto& l1_c = sobj.addChild(1);
l1_c.addChild(2, "fnord3");
l1_c.addChild(2, "fnord4");
cstable::CSTableBuilder builder(&schema);
builder.addRecord(sobj);
builder.write(testfile);
cstable::CSTableReader reader(testfile);
cstable::RecordMaterializer materializer(&schema, &reader);
msg::MessageObject robj;
materializer.nextRecord(&robj);
EXPECT_EQ(robj.asObject().size(), 3);
EXPECT_EQ(robj.asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asString(), "fnord1");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asString(), "fnord2");
EXPECT_EQ(robj.asObject()[1].asObject().size(), 0);
EXPECT_EQ(robj.asObject()[2].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[2].asObject()[0].asString(), "fnord3");
EXPECT_EQ(robj.asObject()[2].asObject()[1].asString(), "fnord4");
});
TEST_CASE(RecordMaterializerTest, TestReMatWithNonRepeatedParent, [] () {
String testfile = "/tmp/__fnord_testcstablematerialization.cst";
msg::MessageSchemaField level1(
1,
"level1",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level2(
2,
"level2",
msg::FieldType::OBJECT,
0,
true,
false);
msg::MessageSchemaField level2_str(
3,
"str",
msg::FieldType::STRING,
1024,
true,
false);
level2.schema = new MessageSchema(
"Level2",
Vector<msg::MessageSchemaField> { level2_str });
level1.schema = new MessageSchema(
"Level1",
Vector<msg::MessageSchemaField> { level2 });
msg::MessageSchema schema(
"TestSchema",
Vector<msg::MessageSchemaField> { level1 });
msg::MessageObject sobj;
auto& l1_a = sobj.addChild(1);
auto& l2_aa = l1_a.addChild(2);
l2_aa.addChild(3, "fnord1");
l2_aa.addChild(3, "fnord2");
auto& l2_ab = l1_a.addChild(2);
l2_ab.addChild(3, "fnord3");
l2_ab.addChild(3, "fnord4");
auto& l1_b = sobj.addChild(1);
auto& l1_c = sobj.addChild(1);
auto& l2_ca = l1_c.addChild(2);
auto& l2_cb = l1_c.addChild(2);
l2_cb.addChild(3, "fnord5");
l2_cb.addChild(3, "fnord6");
cstable::CSTableBuilder builder(&schema);
builder.addRecord(sobj);
builder.write(testfile);
cstable::CSTableReader reader(testfile);
cstable::RecordMaterializer materializer(&schema, &reader);
msg::MessageObject robj;
materializer.nextRecord(&robj);
EXPECT_EQ(robj.asObject().size(), 3);
EXPECT_EQ(robj.asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[0].asObject()[0].asString(), "fnord1");
EXPECT_EQ(robj.asObject()[0].asObject()[0].asObject()[1].asString(), "fnord2");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[0].asObject()[1].asObject()[0].asString(), "fnord3");
EXPECT_EQ(robj.asObject()[0].asObject()[1].asObject()[1].asString(), "fnord4");
EXPECT_EQ(robj.asObject()[1].asObject().size(), 0);
EXPECT_EQ(robj.asObject()[2].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[2].asObject()[0].asObject().size(), 0);
EXPECT_EQ(robj.asObject()[2].asObject()[1].asObject().size(), 2);
EXPECT_EQ(robj.asObject()[2].asObject()[1].asObject()[0].asString(), "fnord5");
EXPECT_EQ(robj.asObject()[2].asObject()[1].asObject()[1].asString(), "fnord6");
});
<|endoftext|> |
<commit_before>#include <stan/math/mix/mat.hpp>
#include <stan/math/prim/scal.hpp>
#include <stan/math/prim/mat.hpp>
#include <stan/math/prim/scal/prob/von_mises_lpdf.hpp>
#include <iostream>
/*
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <limits>
#include <string>
*/
int main() {
double y = -0.8;
double mu = 0.4;
double kappa = 0;
stan::math::von_mises_lpdf(y, mu, kappa);
/*
const double t = 1.0;
Eigen::MatrixXd A(0, 0);
Eigen::MatrixXd B(0, 0);
Eigen::Matrix<var, -1, -1> C(0, 2);
auto D = stan::math::scale_matrix_exp_multiply(t, A, C);
std::cout << "rows: " << D.rows() << ", cols: " << D.cols() << std::endl;
double nan = std::numeric_limits<double>::quiet_NaN();
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> y(1, 1);
y << nan;
stan::math::check_pos_definite("ciao", "y", y);
*/
}
<commit_msg>Remove spurious file<commit_after><|endoftext|> |
<commit_before><commit_msg>[(UTC +8:00) 2017-12-30 23:22] Add our own object_pool, not tested.<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil -*- */
#include "processor.h"
#include <cassert>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include <schwa/msgpack.h>
#include <schwa/pool.h>
#include <schwa/port.h>
#include <schwa/unicode.h>
namespace io = schwa::io;
namespace mp = schwa::msgpack;
namespace schwa {
namespace mp_less {
const std::string Processor::SEP(std::string("\t") + port::DARK_GREY + "# ");
const std::string Processor::REPR_NIL("<nil>");
const std::string Processor::REPR_UNKNOWN("<UNKNOWN VALUE>");
Processor::Processor(void) : _indent(0), _out(nullptr) { }
Processor::~Processor(void) { }
std::ostream &
Processor::_write_indent(void) {
for (unsigned int i = 0; i != _indent; ++i)
*_out << " ";
return *_out;
}
void
Processor::_write_value(const mp::Value &value, const bool add_description) {
if (is_bool(value.type)) {
*_out << std::boolalpha << value.via._bool;
if (add_description)
*_out << SEP << "bool" << port::OFF;
}
else if (is_double(value.type)) {
*_out << value.via._double;
if (add_description)
*_out << SEP << "double" << port::OFF;
}
else if (is_float(value.type)) {
*_out << value.via._float;
if (add_description)
*_out << SEP << "float" << port::OFF;
}
else if (is_nil(value.type)) {
*_out << REPR_NIL;
if (add_description)
*_out << SEP << "nil" << port::OFF;
}
else if (is_sint(value.type)) {
*_out << "0x" << std::hex << value.via._int64 << std::dec;
if (add_description)
*_out << SEP << "int (" << value.via._int64 << ")" << port::OFF;
}
else if (is_uint(value.type)) {
*_out << "0x" << std::hex << value.via._uint64 << std::dec;
if (add_description)
*_out << SEP << "uint (" << value.via._uint64 << ")" << port::OFF;
}
else if (is_str(value.type)) {
const mp::Str &obj = *value.via._str;
const UnicodeString s = UnicodeString::from_utf8(obj.data(), obj.nbytes());
*_out << "\"" << s << "\"";
if (add_description)
*_out << SEP << "str (" << std::dec << obj.nbytes() << "B, " << s.size() << " code point(s))" << port::OFF;
}
else if (is_bin(value.type)) {
const mp::Bin &obj = *value.via._bin;
*_out << "\"";
for (uint32_t i = 0; i != obj.nbytes(); ++i) {
const char c = obj.data()[i];
if (std::isprint(c))
*_out << c;
else
*_out << "\\x" << std::hex << static_cast<unsigned int>(c) << std::dec;
}
*_out << "\"";
if (add_description)
*_out << SEP << "bin (" << std::dec << obj.nbytes() << "B)" << port::OFF;
}
else if (is_array(value.type)) {
const mp::Array &obj = *value.via._array;
_write_indent() << port::BOLD << "[" << port::OFF;
if (obj.size() == 0)
*_out << port::BOLD << "]" << port::OFF;
if (add_description)
*_out << SEP << "array (" << std::dec << obj.size() << ")" << port::OFF;
if (obj.size() != 0) {
*_out << "\n";
++_indent;
for (uint32_t i = 0; i != obj.size(); ++i) {
_write_indent();
_write_value(obj[i]);
*_out << ",\n";
}
--_indent;
_write_indent() << port::BOLD << "]" << port::OFF;
}
}
else if (is_map(value.type)) {
const mp::Map &obj = *value.via._map;
_write_indent() << port::BOLD << "{" << port::OFF;
if (obj.size() == 0)
*_out << port::BOLD << "}" << port::OFF;
if (add_description)
*_out << SEP << "map (" << std::dec << obj.size() << ")" << port::OFF;
if (obj.size() != 0) {
*_out << "\n";
++_indent;
for (uint32_t i = 0; i != obj.size(); ++i) {
const mp::Map::Pair &pair = obj[i];
_write_indent();
_write_value(pair.key, false);
*_out << port::BOLD << ": " << port::OFF;
_write_value(pair.value);
*_out << ",\n";
}
--_indent;
_write_indent() << port::BOLD << "}" << port::OFF;
}
}
else if (is_ext(value.type)) {
const mp::Ext &obj = *value.via._ext;
*_out << "\"";
for (uint32_t i = 0; i != obj.nbytes(); ++i) {
const char c = obj.data()[i];
if (std::isprint(c))
*_out << std::dec << c;
else
*_out << "\\x" << std::hex << static_cast<unsigned int>(c);
}
*_out << "\"";
if (add_description)
*_out << SEP << "ext (" << std::dec << obj.nbytes() << "B)" << port::OFF;
}
else
*_out << port::RED << REPR_UNKNOWN << port::OFF;
}
void
Processor::process(std::istream &in, std::ostream &out) {
// Reset our state.
_indent = 0;
_out = &out;
Pool pool(4096);
while (in) {
// Read in the next MessagePack object.
const auto at_byte = in.tellg();
mp::Value *value = nullptr;
try {
value = mp::read_dynamic(in, pool);
assert(value != nullptr);
}
catch (mp::ReadError &e) {
*_out << port::RED << "ReadError at byte " << std::dec << in.tellg() << ": " << e.what() << port::OFF << std::endl;
break;
}
// Pretty-print the object.
*_out << port::DARK_GREY << "# at byte " << at_byte << port::OFF << "\n";
_write_value(*value);
*_out << "\n";
}
}
} // namespace mp_less
} // namespace schwa
<commit_msg>Corrected EOF detection in `mp-less`.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil -*- */
#include "processor.h"
#include <cassert>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include <schwa/msgpack.h>
#include <schwa/pool.h>
#include <schwa/port.h>
#include <schwa/unicode.h>
namespace io = schwa::io;
namespace mp = schwa::msgpack;
namespace schwa {
namespace mp_less {
const std::string Processor::SEP(std::string("\t") + port::DARK_GREY + "# ");
const std::string Processor::REPR_NIL("<nil>");
const std::string Processor::REPR_UNKNOWN("<UNKNOWN VALUE>");
Processor::Processor(void) : _indent(0), _out(nullptr) { }
Processor::~Processor(void) { }
std::ostream &
Processor::_write_indent(void) {
for (unsigned int i = 0; i != _indent; ++i)
*_out << " ";
return *_out;
}
void
Processor::_write_value(const mp::Value &value, const bool add_description) {
if (is_bool(value.type)) {
*_out << std::boolalpha << value.via._bool;
if (add_description)
*_out << SEP << "bool" << port::OFF;
}
else if (is_double(value.type)) {
*_out << value.via._double;
if (add_description)
*_out << SEP << "double" << port::OFF;
}
else if (is_float(value.type)) {
*_out << value.via._float;
if (add_description)
*_out << SEP << "float" << port::OFF;
}
else if (is_nil(value.type)) {
*_out << REPR_NIL;
if (add_description)
*_out << SEP << "nil" << port::OFF;
}
else if (is_sint(value.type)) {
*_out << "0x" << std::hex << value.via._int64 << std::dec;
if (add_description)
*_out << SEP << "int (" << value.via._int64 << ")" << port::OFF;
}
else if (is_uint(value.type)) {
*_out << "0x" << std::hex << value.via._uint64 << std::dec;
if (add_description)
*_out << SEP << "uint (" << value.via._uint64 << ")" << port::OFF;
}
else if (is_str(value.type)) {
const mp::Str &obj = *value.via._str;
const UnicodeString s = UnicodeString::from_utf8(obj.data(), obj.nbytes());
*_out << "\"" << s << "\"";
if (add_description)
*_out << SEP << "str (" << std::dec << obj.nbytes() << "B, " << s.size() << " code point(s))" << port::OFF;
}
else if (is_bin(value.type)) {
const mp::Bin &obj = *value.via._bin;
*_out << "\"";
for (uint32_t i = 0; i != obj.nbytes(); ++i) {
const char c = obj.data()[i];
if (std::isprint(c))
*_out << c;
else
*_out << "\\x" << std::hex << static_cast<unsigned int>(c) << std::dec;
}
*_out << "\"";
if (add_description)
*_out << SEP << "bin (" << std::dec << obj.nbytes() << "B)" << port::OFF;
}
else if (is_array(value.type)) {
const mp::Array &obj = *value.via._array;
_write_indent() << port::BOLD << "[" << port::OFF;
if (obj.size() == 0)
*_out << port::BOLD << "]" << port::OFF;
if (add_description)
*_out << SEP << "array (" << std::dec << obj.size() << ")" << port::OFF;
if (obj.size() != 0) {
*_out << "\n";
++_indent;
for (uint32_t i = 0; i != obj.size(); ++i) {
_write_indent();
_write_value(obj[i]);
*_out << ",\n";
}
--_indent;
_write_indent() << port::BOLD << "]" << port::OFF;
}
}
else if (is_map(value.type)) {
const mp::Map &obj = *value.via._map;
_write_indent() << port::BOLD << "{" << port::OFF;
if (obj.size() == 0)
*_out << port::BOLD << "}" << port::OFF;
if (add_description)
*_out << SEP << "map (" << std::dec << obj.size() << ")" << port::OFF;
if (obj.size() != 0) {
*_out << "\n";
++_indent;
for (uint32_t i = 0; i != obj.size(); ++i) {
const mp::Map::Pair &pair = obj[i];
_write_indent();
_write_value(pair.key, false);
*_out << port::BOLD << ": " << port::OFF;
_write_value(pair.value);
*_out << ",\n";
}
--_indent;
_write_indent() << port::BOLD << "}" << port::OFF;
}
}
else if (is_ext(value.type)) {
const mp::Ext &obj = *value.via._ext;
*_out << "\"";
for (uint32_t i = 0; i != obj.nbytes(); ++i) {
const char c = obj.data()[i];
if (std::isprint(c))
*_out << std::dec << c;
else
*_out << "\\x" << std::hex << static_cast<unsigned int>(c);
}
*_out << "\"";
if (add_description)
*_out << SEP << "ext (" << std::dec << obj.nbytes() << "B)" << port::OFF;
}
else
*_out << port::RED << REPR_UNKNOWN << port::OFF;
}
void
Processor::process(std::istream &in, std::ostream &out) {
// Reset our state.
_indent = 0;
_out = &out;
Pool pool(4096);
while (in) {
// Read in the next MessagePack object.
const auto at_byte = in.tellg();
mp::Value *value = nullptr;
try {
value = mp::read_dynamic(in, pool);
}
catch (mp::ReadError &e) {
*_out << port::RED << "ReadError at byte " << std::dec << in.tellg() << ": " << e.what() << port::OFF << std::endl;
break;
}
// Check for EOF.
if (value == nullptr) {
assert(in.eof());
break;
}
// Pretty-print the object.
*_out << port::DARK_GREY << "# at byte " << at_byte << port::OFF << "\n";
_write_value(*value);
*_out << "\n";
}
}
} // namespace mp_less
} // namespace schwa
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Gabe Black
* Kevin Lim
*/
#include "arch/alpha/miscregfile.hh"
#include "base/misc.hh"
namespace AlphaISA
{
void
MiscRegFile::serialize(std::ostream &os)
{
SERIALIZE_SCALAR(fpcr);
SERIALIZE_SCALAR(uniq);
SERIALIZE_SCALAR(lock_flag);
SERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
SERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
void
MiscRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(fpcr);
UNSERIALIZE_SCALAR(uniq);
UNSERIALIZE_SCALAR(lock_flag);
UNSERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
UNSERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
MiscReg
MiscRegFile::readReg(int misc_reg)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
return ipr[misc_reg];
#else
default:
panic("Attempt to read an invalid misc register!");
return 0;
#endif
}
}
MiscReg
MiscRegFile::readRegWithEffect(int misc_reg, ThreadContext *tc)
{
#if FULL_SYSTEM
return readIpr(misc_reg, tc);
#else
panic("No faulting misc regs in SE mode!");
return 0;
#endif
}
void
MiscRegFile::setReg(int misc_reg, const MiscReg &val)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
ipr[misc_reg] = val;
return;
#else
default:
panic("Attempt to write to an invalid misc register!");
#endif
}
}
void
MiscRegFile::setRegWithEffect(int misc_reg, const MiscReg &val,
ThreadContext *tc)
{
#if FULL_SYSTEM
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
default:
return setIpr(misc_reg, val, tc);
}
#else
//panic("No registers with side effects in SE mode!");
return;
#endif
}
}
<commit_msg>Make setRegWithEffect do something in SE mode.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Gabe Black
* Kevin Lim
*/
#include "arch/alpha/miscregfile.hh"
#include "base/misc.hh"
namespace AlphaISA
{
void
MiscRegFile::serialize(std::ostream &os)
{
SERIALIZE_SCALAR(fpcr);
SERIALIZE_SCALAR(uniq);
SERIALIZE_SCALAR(lock_flag);
SERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
SERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
void
MiscRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(fpcr);
UNSERIALIZE_SCALAR(uniq);
UNSERIALIZE_SCALAR(lock_flag);
UNSERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
UNSERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
MiscReg
MiscRegFile::readReg(int misc_reg)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
return ipr[misc_reg];
#else
default:
panic("Attempt to read an invalid misc register!");
return 0;
#endif
}
}
MiscReg
MiscRegFile::readRegWithEffect(int misc_reg, ThreadContext *tc)
{
#if FULL_SYSTEM
return readIpr(misc_reg, tc);
#else
panic("No faulting misc regs in SE mode!");
return 0;
#endif
}
void
MiscRegFile::setReg(int misc_reg, const MiscReg &val)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
ipr[misc_reg] = val;
return;
#else
default:
panic("Attempt to write to an invalid misc register!");
#endif
}
}
void
MiscRegFile::setRegWithEffect(int misc_reg, const MiscReg &val,
ThreadContext *tc)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
default:
#if FULL_SYSTEM
setIpr(misc_reg, val, tc);
#else
panic("No registers with side effects in SE mode!");
#endif
return;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>[nostalgia/studio] Cleanup main<commit_after><|endoftext|> |
<commit_before><commit_msg>network_driver: Cleanup<commit_after><|endoftext|> |
<commit_before><commit_msg>Bugfix: should not depend on keyNum to decide whether UintFullIndex is used or not within Build()<commit_after><|endoftext|> |
<commit_before>#include "Game.h"
namespace hm
{
Game::Game() : capFrameRate(true), framerate(30), frameTimer(), maxFrameTime(0), cappedFrameTime(0)
{
// Set up our members.
window = new Window("No Title", 640, 480);
manager = new StateManager(window);
}
Game::Game(std::string title) : capFrameRate(true), framerate(30), frameTimer(), maxFrameTime(0), cappedFrameTime(0)
{
window = new Window(title, 640, 480);
manager = new StateManager(window);
}
Game::Game(std::string title, int width, int height, int bpp) : capFrameRate(true), framerate(30), frameTimer(), maxFrameTime(0), cappedFrameTime(0)
{
window = new Window(title, width, height, bpp);
manager = new StateManager(window);
}
Game::~Game()
{
delete manager;
manager = NULL;
delete window;
window = NULL;
}
void Game::setCapFrameRate(bool b)
{
capFrameRate = b;
return;
}
bool Game::frameRateIsCapped()
{
return capFrameRate;
}
void Game::setFrameRate(int i)
{
framerate = i;
return;
}
float Game::getMaxFrameTime()
{
return maxFrameTime;
}
float Game::getCappedFrameTime()
{
return cappedFrameTime;
}
float Game::getMaxFrameRate()
{
// Frame Rate = 1000ms / Time Spent per Frame
return 1000 / maxFrameTime;
}
float Game::getCappedFrameRate()
{
// Frame Rate = 1000ms / Time Spent per Frame
return 1000 / cappedFrameTime;
}
float Game::getFrameRate()
{
if(frameRateIsCapped())
return 1000 / cappedFrameTime;
else
return 1000 / maxFrameTime;
}
void Game::loop()
{
while(running)
{
frameTimer.start();
processInput();
update();
display();
// Record the faster time.
frameTimer.pause();
maxFrameTime = (float)(maxFrameTime * .995 + frameTimer.getTime() * .005);
frameTimer.unpause();
// Record the capped time.
if(capFrameRate && frameTimer.getTime() < 1000 / framerate)
{
SDL_Delay((Uint32)(1000 / framerate - frameTimer.getTime()));
cappedFrameTime = (float)((cappedFrameTime * .95 + frameTimer.getTime() * .05));
}
}
// Clean up afterwards.
cleanup();
}
}
<commit_msg>Changed sample size for capped frame rate average.<commit_after>#include "Game.h"
namespace hm
{
Game::Game() : capFrameRate(true), framerate(30), frameTimer(), maxFrameTime(0), cappedFrameTime(0)
{
// Set up our members.
window = new Window("No Title", 640, 480);
manager = new StateManager(window);
}
Game::Game(std::string title) : capFrameRate(true), framerate(30), frameTimer(), maxFrameTime(0), cappedFrameTime(0)
{
window = new Window(title, 640, 480);
manager = new StateManager(window);
}
Game::Game(std::string title, int width, int height, int bpp) : capFrameRate(true), framerate(30), frameTimer(), maxFrameTime(0), cappedFrameTime(0)
{
window = new Window(title, width, height, bpp);
manager = new StateManager(window);
}
Game::~Game()
{
delete manager;
manager = NULL;
delete window;
window = NULL;
}
void Game::setCapFrameRate(bool b)
{
capFrameRate = b;
return;
}
bool Game::frameRateIsCapped()
{
return capFrameRate;
}
void Game::setFrameRate(int i)
{
framerate = i;
return;
}
float Game::getMaxFrameTime()
{
return maxFrameTime;
}
float Game::getCappedFrameTime()
{
return cappedFrameTime;
}
float Game::getMaxFrameRate()
{
// Frame Rate = 1000ms / Time Spent per Frame
return 1000 / maxFrameTime;
}
float Game::getCappedFrameRate()
{
// Frame Rate = 1000ms / Time Spent per Frame
return 1000 / cappedFrameTime;
}
float Game::getFrameRate()
{
if(frameRateIsCapped())
return 1000 / cappedFrameTime;
else
return 1000 / maxFrameTime;
}
void Game::loop()
{
while(running)
{
frameTimer.start();
processInput();
update();
display();
// Record the faster time.
frameTimer.pause();
maxFrameTime = (float)(maxFrameTime * .995 + frameTimer.getTime() * .005);
frameTimer.unpause();
// Record the capped time.
if(capFrameRate && frameTimer.getTime() < 1000 / framerate)
{
SDL_Delay((Uint32)(1000 / framerate - frameTimer.getTime()));
cappedFrameTime = (float)((cappedFrameTime * .995 + frameTimer.getTime() * .005));
}
}
// Clean up afterwards.
cleanup();
}
}
<|endoftext|> |
<commit_before><commit_msg>Remove whitespace from path valued configuration file settings.<commit_after><|endoftext|> |
<commit_before><commit_msg>Documentation: clarify that DOMWriter::writeToString always returns string in UTF-16<commit_after><|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS c09v003 (1.33.14); FILE MERGED 2006/03/01 10:30:35 os 1.33.14.1: #132598# repositioning of component buttons fixed<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
namespace {
class ResourceDispatcherTest : public UITest {
public:
void CheckTitleTest(const std::wstring& file,
const std::wstring& expected_title,
int expected_navigations) {
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(FilePath::FromWStringHack(file)),
expected_navigations);
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
protected:
ResourceDispatcherTest() : UITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
CheckTitleTest(L"nosniff-test.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
CheckTitleTest(L"content-sniffer-test1.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
CheckTitleTest(L"content-sniffer-test2.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
CheckTitleTest(L"content-sniffer-test3.html",
L"Content Sniffer Test 3", 1);
EXPECT_EQ(1, GetTabCount());
// Make sure the download shelf is not showing.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
bool visible = false;
ASSERT_TRUE(browser->IsShelfVisible(&visible));
EXPECT_FALSE(visible);
}
TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
CheckTitleTest(L"content-disposition-empty.html", L"success", 1);
}
TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
CheckTitleTest(L"content-disposition-inline.html", L"success", 1);
}
// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSyncRequestSucceed());",
&success));
EXPECT_TRUE(success);
}
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_disallowed.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSucceed());",
&success));
EXPECT_TRUE(success);
}
// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_during_unload.html")));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"sync xhr on unload", tab_title);
// Navigate to a new page, to dispatch unload event and trigger xhr.
// (the bug would make this step hang the renderer).
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL("files/title2.html")));
// Check that the new page got loaded, and that no download was triggered.
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
bool shelf_is_visible = false;
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
EXPECT_FALSE(shelf_is_visible);
}
// Tests that onunload is run for cross-site requests. (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site page, to dispatch unload event and set the
// cookie.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Check that the cookie was set.
std::string value_result;
ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
ASSERT_FALSE(value_result.empty());
ASSERT_STREQ("foo", value_result.c_str());
}
#if !defined(OS_MACOSX)
#if defined(OS_WIN)
// http://crbug.com/32048
#define CrossSiteAfterCrash FLAKY_CrossSiteAfterCrash
#endif
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone. In that case, we don't want to wait for the old renderer
// to run the handlers.
// We need to disable this on Mac because the crash causes the OS CrashReporter
// process to kick in to analyze the poor dead renderer. Unfortunately, if the
// app isn't stripped of debug symbols, this takes about five minutes to
// complete and isn't conducive to quick turnarounds. As we don't currently
// strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Cause the renderer to crash.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
// Wait for browser to notice the renderer crash.
PlatformThread::Sleep(sleep_timeout_ms());
// Navigate to a new cross-site page. The browser should not wait around for
// the old renderer's on{before}unload handlers to run.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
#endif // !defined(OS_MACOSX)
// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with an HTTP page.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Now load a file:// page, which does not use the BufferedEventHandler.
// Make sure that the page loads and displays a title, and doesn't get stuck.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title2.html");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_file)));
EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}
// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page. (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site URL that results in an error page.
// TODO(creis): If this causes crashes or hangs, it might be for the same
// reason as ErrorPageTest::DNSError. See bug 1199491 and
// http://crbug.com/22877.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
GURL(URLRequestFailedDnsJob::kTestUrl), 2));
EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());
// Check that the cookie was set, meaning that the onunload handler ran.
std::string value_result;
EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
EXPECT_FALSE(value_result.empty());
EXPECT_STREQ("foo", value_result.c_str());
// Check that renderer-initiated navigations still work. In a previous bug,
// the ResourceDispatcherHost would think that such navigations were
// cross-site, because we didn't clean up from the previous request. Since
// TabContents was in the NORMAL state, it would ignore the attempt to run
// the onunload handler, and the navigation would fail.
// (Test by redirecting to javascript:window.location='someURL'.)
GURL test_url(test_server.GetURL("files/title2.html"));
std::string redirect_url = "javascript:window.location='" +
test_url.possibly_invalid_spec() + "'";
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(GURL(redirect_url)));
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}
TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) {
// We expect the following URL requests from this test:
// 1- http://mock.http/cross-origin-redirect-blocked.html
// 2- http://mock.http/redirect-to-title2.html
// 3- http://mock.http/title2.html
//
// If the redirect in #2 were not blocked, we'd also see a request
// for http://mock.http:4000/title2.html, and the title would be different.
CheckTitleTest(L"cross-origin-redirect-blocked.html",
L"Title Of More Awesomeness", 2);
}
// Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed
// requests, to prevent calling Read on a request that has already failed.
// See bug 40250.
TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Visit another URL first to trigger a cross-site navigation.
GURL url(chrome::kChromeUINewTabURL);
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Visit a URL that fails without calling ResourceDispatcherHost::Read.
GURL broken_url("chrome://theme");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url));
// Make sure the navigation finishes.
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"chrome://theme/ is not available", tab_title);
}
} // namespace
<commit_msg>Disable ResourceDispatcherTest.SyncXMLHttpRequest_DuringUnload.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
namespace {
class ResourceDispatcherTest : public UITest {
public:
void CheckTitleTest(const std::wstring& file,
const std::wstring& expected_title,
int expected_navigations) {
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(FilePath::FromWStringHack(file)),
expected_navigations);
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
protected:
ResourceDispatcherTest() : UITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
CheckTitleTest(L"nosniff-test.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
CheckTitleTest(L"content-sniffer-test1.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
CheckTitleTest(L"content-sniffer-test2.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
CheckTitleTest(L"content-sniffer-test3.html",
L"Content Sniffer Test 3", 1);
EXPECT_EQ(1, GetTabCount());
// Make sure the download shelf is not showing.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
bool visible = false;
ASSERT_TRUE(browser->IsShelfVisible(&visible));
EXPECT_FALSE(visible);
}
TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
CheckTitleTest(L"content-disposition-empty.html", L"success", 1);
}
TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
CheckTitleTest(L"content-disposition-inline.html", L"success", 1);
}
// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSyncRequestSucceed());",
&success));
EXPECT_TRUE(success);
}
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_disallowed.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSucceed());",
&success));
EXPECT_TRUE(success);
}
// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
// Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264
TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_during_unload.html")));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"sync xhr on unload", tab_title);
// Navigate to a new page, to dispatch unload event and trigger xhr.
// (the bug would make this step hang the renderer).
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL("files/title2.html")));
// Check that the new page got loaded, and that no download was triggered.
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
bool shelf_is_visible = false;
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
EXPECT_FALSE(shelf_is_visible);
}
// Tests that onunload is run for cross-site requests. (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site page, to dispatch unload event and set the
// cookie.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Check that the cookie was set.
std::string value_result;
ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
ASSERT_FALSE(value_result.empty());
ASSERT_STREQ("foo", value_result.c_str());
}
#if !defined(OS_MACOSX)
#if defined(OS_WIN)
// http://crbug.com/32048
#define CrossSiteAfterCrash FLAKY_CrossSiteAfterCrash
#endif
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone. In that case, we don't want to wait for the old renderer
// to run the handlers.
// We need to disable this on Mac because the crash causes the OS CrashReporter
// process to kick in to analyze the poor dead renderer. Unfortunately, if the
// app isn't stripped of debug symbols, this takes about five minutes to
// complete and isn't conducive to quick turnarounds. As we don't currently
// strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Cause the renderer to crash.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
// Wait for browser to notice the renderer crash.
PlatformThread::Sleep(sleep_timeout_ms());
// Navigate to a new cross-site page. The browser should not wait around for
// the old renderer's on{before}unload handlers to run.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
#endif // !defined(OS_MACOSX)
// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with an HTTP page.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Now load a file:// page, which does not use the BufferedEventHandler.
// Make sure that the page loads and displays a title, and doesn't get stuck.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title2.html");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_file)));
EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}
// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page. (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site URL that results in an error page.
// TODO(creis): If this causes crashes or hangs, it might be for the same
// reason as ErrorPageTest::DNSError. See bug 1199491 and
// http://crbug.com/22877.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
GURL(URLRequestFailedDnsJob::kTestUrl), 2));
EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());
// Check that the cookie was set, meaning that the onunload handler ran.
std::string value_result;
EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
EXPECT_FALSE(value_result.empty());
EXPECT_STREQ("foo", value_result.c_str());
// Check that renderer-initiated navigations still work. In a previous bug,
// the ResourceDispatcherHost would think that such navigations were
// cross-site, because we didn't clean up from the previous request. Since
// TabContents was in the NORMAL state, it would ignore the attempt to run
// the onunload handler, and the navigation would fail.
// (Test by redirecting to javascript:window.location='someURL'.)
GURL test_url(test_server.GetURL("files/title2.html"));
std::string redirect_url = "javascript:window.location='" +
test_url.possibly_invalid_spec() + "'";
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(GURL(redirect_url)));
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}
TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) {
// We expect the following URL requests from this test:
// 1- http://mock.http/cross-origin-redirect-blocked.html
// 2- http://mock.http/redirect-to-title2.html
// 3- http://mock.http/title2.html
//
// If the redirect in #2 were not blocked, we'd also see a request
// for http://mock.http:4000/title2.html, and the title would be different.
CheckTitleTest(L"cross-origin-redirect-blocked.html",
L"Title Of More Awesomeness", 2);
}
// Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed
// requests, to prevent calling Read on a request that has already failed.
// See bug 40250.
TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Visit another URL first to trigger a cross-site navigation.
GURL url(chrome::kChromeUINewTabURL);
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Visit a URL that fails without calling ResourceDispatcherHost::Read.
GURL broken_url("chrome://theme");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url));
// Make sure the navigation finishes.
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"chrome://theme/ is not available", tab_title);
}
} // namespace
<|endoftext|> |
<commit_before>#ifndef INCLUDED_SROOK_MPL_CONSTANT_SEQUENCE_ALGORITHM_MERGE_HPP
#define INCLUDED_SROOK_MPL_CONSTANT_SEQUENCE_ALGORITHM_MERGE_HPP
#include<srook/mpl/constant_sequence/algorithm/sort.hpp>
#include<srook/mpl/constant_sequence/algorithm/first.hpp>
#include<srook/mpl/constant_sequence/algorithm/concat.hpp>
namespace srook{
inline namespace mpl{
namespace constant_sequence{
inline namespace v1{
template<bool,class,class,template<std::size_t,std::size_t>class>
struct merge;
template<
std::size_t head1,std::size_t head_next1,std::size_t... tail1,
std::size_t head2,std::size_t... tail2,
template<std::size_t,std::size_t>class comp
>
struct merge<true,std::index_sequence<head1,head_next1,tail1...>,std::index_sequence<head2,tail2...>,comp>{
using type=
concat_t<
std::index_sequence<head1>,
typename merge<
comp<head_next1,head2>::value,
std::index_sequence<head_next1,tail1...>,
std::index_sequence<head2,tail2...>,
comp
>::type
>;
};
template<
std::size_t head1,std::size_t... tail1,
std::size_t head2,std::size_t head_next2,std::size_t... tail2,
template<std::size_t,std::size_t>class comp
>
struct merge<false,std::index_sequence<head1,tail1...>,std::index_sequence<head2,head_next2,tail2...>,comp>{
using type=
concat_t<
std::index_sequence<head2>,
typename merge<
comp<head1,head_next2>::value,
std::index_sequence<head1,tail1...>,
std::index_sequence<head_next2,tail2...>,
comp
>::type
>;
};
template<
std::size_t last1,
std::size_t prev_last,std::size_t... last2,
template<std::size_t,std::size_t>class comp
>
struct merge<true,std::index_sequence<last1>,std::index_sequence<prev_last,last2...>,comp>{
using type=std::index_sequence<last1,prev_last,last2...>;
};
template<
std::size_t last1,
std::size_t prev_last,std::size_t prev_next_last2,std::size_t... last2,
template<std::size_t,std::size_t>class comp
>
struct merge<false,std::index_sequence<last1>,std::index_sequence<prev_last,prev_next_last2,last2...>,comp>{
using type=
concat_t<
std::index_sequence<prev_last>,
typename merge<
comp<last1,prev_next_last2>::value,
std::index_sequence<last1>,
std::index_sequence<prev_next_last2,last2...>,
comp
>::type
>;
};
/*template<std::size_t last1,std::size_t last2,template<std::size_t,std::size_t>class comp>
struct merge<true,std::index_sequence<last1>,std::index_sequence<last2>,comp>{
using type=std::index_sequence<last1,last2>;
};
template<std::size_t last1,std::size_t last2,template<std::size_t,std::size_t>class comp>
struct merge<false,std::index_sequence<last1>,std::index_sequence<last2>,comp>{
using type=std::index_sequence<last2,last1>;
};*/
template<bool b,std::size_t last,template<std::size_t,std::size_t>class comp>
struct merge<b,std::index_sequence<last>,std::index_sequence<>,comp>{
using type=std::index_sequence<last>;
};
template<std::size_t prev_last,std::size_t next_last,std::size_t... last1,std::size_t last2,template<std::size_t,std::size_t>class comp>
struct merge<true,std::index_sequence<prev_last,next_last,last1...>,std::index_sequence<last2>,comp>{
using type=
concat_t<
std::index_sequence<prev_last>,
typename merge<
comp<next_last,last2>::value,
std::index_sequence<next_last,last1...>,
std::index_sequence<last2>,
comp
>::type
>;
};
template<std::size_t... last1,std::size_t last2,template<std::size_t,std::size_t>class comp>
struct merge<false,std::index_sequence<last1...>,std::index_sequence<last2>,comp>{
using type=std::index_sequence<last2,last1...>;
};
template<class Seq1,class Seq2,template<std::size_t,std::size_t>class comp=less>
using merge_t=
typename merge<
(Seq1::size()<Seq2::size())?comp<first_v<Seq1>,first_v<Seq2>>::value:comp<first_v<Seq2>,first_v<Seq1>>::value,
std::conditional_t<(Seq1::size()<Seq2::size()),Seq1,Seq2>,
std::conditional_t<(Seq1::size()<Seq2::size()),Seq2,Seq1>,
comp
>::type;
} // inline namespace v1
} // inline namespace constant_sequence
} // inline namespace mpl
} // namespace srook
#endif
<commit_msg>remove comment<commit_after>#ifndef INCLUDED_SROOK_MPL_CONSTANT_SEQUENCE_ALGORITHM_MERGE_HPP
#define INCLUDED_SROOK_MPL_CONSTANT_SEQUENCE_ALGORITHM_MERGE_HPP
#include<srook/mpl/constant_sequence/algorithm/sort.hpp>
#include<srook/mpl/constant_sequence/algorithm/first.hpp>
#include<srook/mpl/constant_sequence/algorithm/concat.hpp>
namespace srook{
inline namespace mpl{
namespace constant_sequence{
inline namespace v1{
template<bool,class,class,template<std::size_t,std::size_t>class>
struct merge;
template<
std::size_t head1,std::size_t head_next1,std::size_t... tail1,
std::size_t head2,std::size_t... tail2,
template<std::size_t,std::size_t>class comp
>
struct merge<true,std::index_sequence<head1,head_next1,tail1...>,std::index_sequence<head2,tail2...>,comp>{
using type=
concat_t<
std::index_sequence<head1>,
typename merge<
comp<head_next1,head2>::value,
std::index_sequence<head_next1,tail1...>,
std::index_sequence<head2,tail2...>,
comp
>::type
>;
};
template<
std::size_t head1,std::size_t... tail1,
std::size_t head2,std::size_t head_next2,std::size_t... tail2,
template<std::size_t,std::size_t>class comp
>
struct merge<false,std::index_sequence<head1,tail1...>,std::index_sequence<head2,head_next2,tail2...>,comp>{
using type=
concat_t<
std::index_sequence<head2>,
typename merge<
comp<head1,head_next2>::value,
std::index_sequence<head1,tail1...>,
std::index_sequence<head_next2,tail2...>,
comp
>::type
>;
};
template<
std::size_t last1,
std::size_t prev_last,std::size_t... last2,
template<std::size_t,std::size_t>class comp
>
struct merge<true,std::index_sequence<last1>,std::index_sequence<prev_last,last2...>,comp>{
using type=std::index_sequence<last1,prev_last,last2...>;
};
template<
std::size_t last1,
std::size_t prev_last,std::size_t prev_next_last2,std::size_t... last2,
template<std::size_t,std::size_t>class comp
>
struct merge<false,std::index_sequence<last1>,std::index_sequence<prev_last,prev_next_last2,last2...>,comp>{
using type=
concat_t<
std::index_sequence<prev_last>,
typename merge<
comp<last1,prev_next_last2>::value,
std::index_sequence<last1>,
std::index_sequence<prev_next_last2,last2...>,
comp
>::type
>;
};
template<bool b,std::size_t last,template<std::size_t,std::size_t>class comp>
struct merge<b,std::index_sequence<last>,std::index_sequence<>,comp>{
using type=std::index_sequence<last>;
};
template<std::size_t prev_last,std::size_t next_last,std::size_t... last1,std::size_t last2,template<std::size_t,std::size_t>class comp>
struct merge<true,std::index_sequence<prev_last,next_last,last1...>,std::index_sequence<last2>,comp>{
using type=
concat_t<
std::index_sequence<prev_last>,
typename merge<
comp<next_last,last2>::value,
std::index_sequence<next_last,last1...>,
std::index_sequence<last2>,
comp
>::type
>;
};
template<std::size_t... last1,std::size_t last2,template<std::size_t,std::size_t>class comp>
struct merge<false,std::index_sequence<last1...>,std::index_sequence<last2>,comp>{
using type=std::index_sequence<last2,last1...>;
};
template<class Seq1,class Seq2,template<std::size_t,std::size_t>class comp=less>
using merge_t=
typename merge<
(Seq1::size()<Seq2::size())?comp<first_v<Seq1>,first_v<Seq2>>::value:comp<first_v<Seq2>,first_v<Seq1>>::value,
std::conditional_t<(Seq1::size()<Seq2::size()),Seq1,Seq2>,
std::conditional_t<(Seq1::size()<Seq2::size()),Seq2,Seq1>,
comp
>::type;
} // inline namespace v1
} // inline namespace constant_sequence
} // inline namespace mpl
} // namespace srook
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
#include "base/loader/raw_object.hh"
#include "base/loader/symtab.hh"
#include "base/trace.hh"
ObjectFile *
RawObject::tryFile(const std::string &fname, int fd, size_t len, uint8_t *data)
{
return new RawObject(fname, fd, len, data, ObjectFile::UnknownArch,
ObjectFile::UnknownOpSys);
}
RawObject::RawObject(const std::string &_filename, int _fd, size_t _len,
uint8_t *_data, Arch _arch, OpSys _opSys)
: ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
{
text.baseAddr = 0;
text.size = len;
text.fileImage = fileData;
data.baseAddr = 0;
data.size = 0;
data.fileImage = NULL;
bss.baseAddr = 0;
bss.size = 0;
bss.fileImage = NULL;
DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
text.baseAddr, text.size, data.baseAddr, data.size,
bss.baseAddr, bss.size);
}
bool
RawObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
{
int fnameStart = filename.rfind('/',filename.size()) + 1;
int extStart = filename.rfind('.',filename.size());
symtab->insert(text.baseAddr & addrMask, filename.substr(fnameStart,
extStart-fnameStart) + "_start");
return true;
}
bool
RawObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
{
int fnameStart = filename.rfind('/',filename.size()) + 1;
int extStart = filename.rfind('.',filename.size());
symtab->insert(text.baseAddr & addrMask, filename.substr(fnameStart,
extStart-fnameStart) + "_start");
return true;
}
<commit_msg>Don't add symbols for loaded files to symbol table since they are pretty much meaningless with all the copying that goes on<commit_after>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
#include "base/loader/raw_object.hh"
#include "base/loader/symtab.hh"
#include "base/trace.hh"
ObjectFile *
RawObject::tryFile(const std::string &fname, int fd, size_t len, uint8_t *data)
{
return new RawObject(fname, fd, len, data, ObjectFile::UnknownArch,
ObjectFile::UnknownOpSys);
}
RawObject::RawObject(const std::string &_filename, int _fd, size_t _len,
uint8_t *_data, Arch _arch, OpSys _opSys)
: ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
{
text.baseAddr = 0;
text.size = len;
text.fileImage = fileData;
data.baseAddr = 0;
data.size = 0;
data.fileImage = NULL;
bss.baseAddr = 0;
bss.size = 0;
bss.fileImage = NULL;
DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
text.baseAddr, text.size, data.baseAddr, data.size,
bss.baseAddr, bss.size);
}
bool
RawObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
{
/* int fnameStart = filename.rfind('/',filename.size()) + 1;
int extStart = filename.rfind('.',filename.size());
symtab->insert(text.baseAddr & addrMask, filename.substr(fnameStart,
extStart-fnameStart) + "_start");*/
return true;
}
bool
RawObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
{
/* int fnameStart = filename.rfind('/',filename.size()) + 1;
int extStart = filename.rfind('.',filename.size());
symtab->insert(text.baseAddr & addrMask, filename.substr(fnameStart,
extStart-fnameStart) + "_start");*/
return true;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <algorithm>
#include <limits>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <unistd.h>
extern "C" {
#include "stinger_core/stinger.h"
#include "stinger_core/stinger_shared.h"
#include "stinger_utils/stinger_utils.h"
#include "stinger_utils/timer.h"
#include "stinger_core/xmalloc.h"
}
#include "proto/stinger-batch.pb.h"
#include "server.h"
#include "send_rcv.h"
using namespace gt::stinger;
int main(int argc, char *argv[])
{
/* default global options */
int port = 10101;
uint64_t buffer_size = 1ULL << 28ULL;
char * graph_name = (char *) xmalloc (128*sizeof(char));
sprintf(graph_name, "/default");
char * input_file = (char *) xmalloc (1024*sizeof(char));
input_file[0] = '\0';
/* parse command line configuration */
int opt = 0;
while(-1 != (opt = getopt(argc, argv, "p:b:n:i:"))) {
switch(opt) {
case 'p': {
port = atoi(optarg);
} break;
case 'b': {
buffer_size = atol(optarg);
} break;
case 'n': {
strcpy (graph_name, optarg);
} break;
case 'i': {
strcpy (input_file, optarg);
} break;
case '?':
case 'h': {
printf("Usage: %s [-p port] [-b buffer_size]\n", argv[0]);
printf("Defaults: port: %d buffer_size: %lu\n", port, (unsigned long) buffer_size);
exit(0);
} break;
}
}
/* print configuration to the terminal */
printf("\tName: %s\n", graph_name);
/* allocate the graph */
struct stinger * S = stinger_shared_new(&graph_name);
//struct stinger * S = stinger_new ();
size_t graph_sz = S->length + sizeof(struct stinger);
int64_t nv, ne;
int64_t *off, *ind, *weight, *graphmem;
/* load edges from disk (if applicable) */
if (input_file[0] != '\0')
{
snarf_graph (input_file, &nv, &ne, (int64_t**)&off,
(int64_t**)&ind, (int64_t**)&weight, (int64_t**)&graphmem);
stinger_set_initial_edges (S, nv, 0, off, ind, weight, NULL, NULL, 0);
free(graphmem);
}
printf("Graph created. Running stats...");
tic();
printf("\n\tVertices: %ld\n\tEdges: %ld\n",
stinger_num_active_vertices(S), stinger_total_edges(S));
/* consistency check */
printf("\tConsistency %ld\n", stinger_consistency_check(S, STINGER_MAX_LVERTICES));
printf("\tDone. %lf seconds\n", toc());
/* we need a socket that can reply with the shmem name & size of the graph */
pid_t name_pid, batch_pid;
/* child will handle name and size requests */
name_pid = fork ();
if (name_pid == 0)
{
start_udp_graph_name_server (graph_name, graph_sz, port);
exit (0);
}
/* and we need a listener that can receive new edges */
batch_pid = fork ();
if (batch_pid == 0)
{
start_tcp_batch_server (S, port, buffer_size);
exit (0);
}
printf("Press <return> to shut down the server...\n");
getchar();
printf("Shutting down the name server..."); fflush(stdout);
int status;
kill(name_pid, SIGTERM);
waitpid(name_pid, &status, 0);
printf(" done.\n"); fflush(stdout);
printf("Shutting down the batch server..."); fflush(stdout);
kill(batch_pid, SIGTERM);
waitpid(batch_pid, &status, 0);
printf(" done.\n"); fflush(stdout);
/* clean up */
stinger_shared_free(S, graph_name, graph_sz);
free(graph_name);
free(input_file);
return 0;
}
<commit_msg>Server can now import DIMACS edge list graph files. Tested with NY road map.<commit_after>#include <cstdio>
#include <algorithm>
#include <limits>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <unistd.h>
extern "C" {
#include "stinger_core/stinger.h"
#include "stinger_core/stinger_shared.h"
#include "stinger_core/xmalloc.h"
#include "stinger_utils/stinger_utils.h"
#include "stinger_utils/timer.h"
#include "stinger_utils/dimacs_support.h"
}
#include "proto/stinger-batch.pb.h"
#include "server.h"
#include "send_rcv.h"
using namespace gt::stinger;
int main(int argc, char *argv[])
{
/* default global options */
int port = 10101;
uint64_t buffer_size = 1ULL << 28ULL;
char * graph_name = (char *) xmalloc (128*sizeof(char));
sprintf(graph_name, "/default");
char * input_file = (char *) xmalloc (1024*sizeof(char));
input_file[0] = '\0';
char * file_type = (char *) xmalloc (128*sizeof(char));
file_type[0] = '\0';
/* parse command line configuration */
int opt = 0;
while(-1 != (opt = getopt(argc, argv, "p:b:n:i:t:h?"))) {
switch(opt) {
case 'p': {
port = atoi(optarg);
} break;
case 'b': {
buffer_size = atol(optarg);
} break;
case 'n': {
strcpy (graph_name, optarg);
} break;
case 'i': {
strcpy (input_file, optarg);
} break;
case 't': {
strcpy (file_type, optarg);
} break;
case '?':
case 'h': {
printf("Usage: %s [-p port] [-b buffer_size] [-n graph_name] [-i input_file_path [-t file_type]]\n", argv[0]);
printf("Defaults:\n\tport: %d\n\tbuffer_size: %lu\n\tgraph_name: %s\n", port, (unsigned long) buffer_size, graph_name);
exit(0);
} break;
}
}
/* print configuration to the terminal */
printf("\tName: %s\n", graph_name);
/* allocate the graph */
struct stinger * S = stinger_shared_new(&graph_name);
//struct stinger * S = stinger_new ();
size_t graph_sz = S->length + sizeof(struct stinger);
/* load edges from disk (if applicable) */
if (input_file[0] != '\0')
{
switch (file_type[0])
{
case 'b': {
int64_t nv, ne;
int64_t *off, *ind, *weight, *graphmem;
snarf_graph (input_file, &nv, &ne, (int64_t**)&off,
(int64_t**)&ind, (int64_t**)&weight, (int64_t**)&graphmem);
stinger_set_initial_edges (S, nv, 0, off, ind, weight, NULL, NULL, 0);
free(graphmem);
} break; /* STINGER binary */
case 'c': {
} break; /* CSV */
case 'd': {
load_dimacs_graph (S, input_file);
} break; /* DIMACS */
case 'e': {
} break; /* Edge list */
case 'g': {
} break; /* GML / GraphML / GEXF -- you pick */
case 'j': {
} break; /* JSON */
case 'x': {
} break; /* XML */
default: {
printf("Unsupported file type.\n");
exit(0);
} break;
}
}
printf("Graph created. Running stats...");
tic();
printf("\n\tVertices: %ld\n\tEdges: %ld\n",
stinger_num_active_vertices(S), stinger_total_edges(S));
/* consistency check */
printf("\tConsistency %ld\n", stinger_consistency_check(S, STINGER_MAX_LVERTICES));
printf("\tDone. %lf seconds\n", toc());
/* we need a socket that can reply with the shmem name & size of the graph */
pid_t name_pid, batch_pid;
/* child will handle name and size requests */
name_pid = fork ();
if (name_pid == 0)
{
start_udp_graph_name_server (graph_name, graph_sz, port);
exit (0);
}
/* and we need a listener that can receive new edges */
batch_pid = fork ();
if (batch_pid == 0)
{
start_tcp_batch_server (S, port, buffer_size);
exit (0);
}
printf("Press <return> to shut down the server...\n");
getchar();
printf("Shutting down the name server..."); fflush(stdout);
int status;
kill(name_pid, SIGTERM);
waitpid(name_pid, &status, 0);
printf(" done.\n"); fflush(stdout);
printf("Shutting down the batch server..."); fflush(stdout);
kill(batch_pid, SIGTERM);
waitpid(batch_pid, &status, 0);
printf(" done.\n"); fflush(stdout);
/* clean up */
stinger_shared_free(S, graph_name, graph_sz);
free(graph_name);
free(input_file);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define IN_FRUIT_CPP_FILE
#include <cstdlib>
#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fruit/impl/util/type_info.h>
#include <fruit/impl/storage/injector_storage.h>
#include <fruit/impl/storage/component_storage.h>
#include <fruit/impl/data_structures/semistatic_graph.templates.h>
#include <fruit/impl/meta/basics.h>
#include <fruit/impl/storage/normalized_component_storage.h>
using std::cout;
using std::endl;
using namespace fruit::impl;
namespace {
std::string multipleBindingsError(TypeId type) {
return "Fatal injection error: the type " + type.type_info->name() + " was provided more than once, with different bindings.\n"
+ "This was not caught at compile time because at least one of the involved components bound this type but didn't expose it in the component signature.\n"
+ "If the type has a default constructor or an Inject annotation, this problem may arise even if this type is bound/provided by only one component (and then hidden), if this type is auto-injected in another component.\n"
+ "If the source of the problem is unclear, try exposing this type in all the component signatures where it's bound; if no component hides it this can't happen.\n";
}
auto typeInfoLessThanForMultibindings = [](const std::pair<TypeId, MultibindingData>& x,
const std::pair<TypeId, MultibindingData>& y) {
return x.first < y.first;
};
} // namespace
namespace fruit {
namespace impl {
std::vector<std::pair<TypeId, BindingData>>
BindingNormalization::normalizeBindings(const std::vector<std::pair<TypeId, BindingData>>& bindings_vector,
FixedSizeAllocator::FixedSizeAllocatorData& fixed_size_allocator_data,
std::vector<CompressedBinding>&& compressed_bindings_vector,
const std::vector<std::pair<TypeId, MultibindingData>>& multibindings_vector,
const std::vector<TypeId>& exposed_types,
BindingNormalization::BindingCompressionInfoMap& bindingCompressionInfoMap) {
HashMap<TypeId, BindingData> binding_data_map = createHashMap<TypeId, BindingData>(bindings_vector.size());
for (auto& p : bindings_vector) {
auto itr = binding_data_map.find(p.first);
if (itr != binding_data_map.end()) {
if (!(p.second == itr->second)) {
std::cerr << multipleBindingsError(p.first) << std::endl;
exit(1);
}
// Otherwise ok, duplicate but consistent binding.
} else {
// New binding, add it to the map.
binding_data_map[p.first] = p.second;
}
}
for (const auto& p : bindings_vector) {
if (p.second.needsAllocation()) {
fixed_size_allocator_data.addType(p.first);
} else {
fixed_size_allocator_data.addExternallyAllocatedType(p.first);
}
}
// Remove duplicates from `compressedBindingsVector'.
// CtypeId -> (ItypeId, bindingData)
HashMap<TypeId, std::pair<TypeId, BindingData>> compressed_bindings_map =
createHashMap<TypeId, std::pair<TypeId, BindingData>>(compressed_bindings_vector.size());
// This also removes any duplicates. No need to check for multiple I->C, I2->C mappings, will filter these out later when
// considering deps.
for (CompressedBinding& compressed_binding : compressed_bindings_vector) {
compressed_bindings_map[compressed_binding.class_id] = {compressed_binding.interface_id, compressed_binding.binding_data};
}
// We can't compress the binding if C is a dep of a multibinding.
for (auto p : multibindings_vector) {
const BindingDeps* deps = p.second.deps;
if (deps != nullptr) {
for (std::size_t i = 0; i < deps->num_deps; ++i) {
compressed_bindings_map.erase(deps->deps[i]);
}
}
}
// We can't compress the binding if C is an exposed type (but I is likely to be exposed instead).
for (TypeId type : exposed_types) {
compressed_bindings_map.erase(type);
}
// We can't compress the binding if some type X depends on C and X!=I.
for (auto& p : binding_data_map) {
TypeId x_id = p.first;
BindingData binding_data = p.second;
if (!binding_data.isCreated()) {
for (std::size_t i = 0; i < binding_data.getDeps()->num_deps; ++i) {
TypeId c_id = binding_data.getDeps()->deps[i];
auto itr = compressed_bindings_map.find(c_id);
if (itr != compressed_bindings_map.end() && itr->second.first != x_id) {
compressed_bindings_map.erase(itr);
}
}
}
}
// Two pairs of compressible bindings (I->C) and (C->X) can not exist (the C of a compressible binding is always bound either
// using constructor binding or provider binding, it can't be a binding itself). So no need to check for that.
bindingCompressionInfoMap =
createHashMap<TypeId, BindingNormalization::BindingCompressionInfo>(compressed_bindings_map.size());
// Now perform the binding compression.
for (auto& p : compressed_bindings_map) {
TypeId c_id = p.first;
TypeId i_id = p.second.first;
BindingData binding_data = p.second.second;
auto i_binding_data = binding_data_map.find(i_id);
auto c_binding_data = binding_data_map.find(c_id);
FruitAssert(i_binding_data != binding_data_map.end());
FruitAssert(c_binding_data != binding_data_map.end());
bindingCompressionInfoMap[c_id] = BindingCompressionInfo{i_id, i_binding_data->second, c_binding_data->second};
// Note that even if I is the one that remains, C is the one that will be allocated, not I.
FruitAssert(!i_binding_data->second.needsAllocation());
i_binding_data->second = binding_data;
binding_data_map.erase(c_binding_data);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: performing binding compression for the edge " << i_id << "->" << c_id << std::endl;
#endif
}
// Copy the normalized bindings into the result vector.
std::vector<std::pair<TypeId, BindingData>> result;
result.reserve(binding_data_map.size());
for (auto& p : binding_data_map) {
result.push_back(p);
}
return result;
}
void BindingNormalization::addMultibindings(std::unordered_map<TypeId, NormalizedMultibindingData>& multibindings,
FixedSizeAllocator::FixedSizeAllocatorData& fixed_size_allocator_data,
const std::vector<std::pair<TypeId, MultibindingData>>& multibindingsVector) {
std::vector<std::pair<TypeId, MultibindingData>> sortedMultibindingsVector = multibindingsVector;
std::sort(sortedMultibindingsVector.begin(), sortedMultibindingsVector.end(),
typeInfoLessThanForMultibindings);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: adding multibindings:" << std::endl;
#endif
// Now we must merge multiple bindings for the same type.
for (auto i = sortedMultibindingsVector.begin(); i != sortedMultibindingsVector.end(); /* no increment */) {
const std::pair<TypeId, MultibindingData>& x = *i;
NormalizedMultibindingData& b = multibindings[x.first];
// Might be set already, but we need to set it if there was no multibinding for this type.
b.get_multibindings_vector = x.second.get_multibindings_vector;
#ifdef FRUIT_EXTRA_DEBUG
std::cout << x.first << " has " << std::distance(i, sortedMultibindingsVector.end()) << " multibindings." << std::endl;
#endif
// Insert all multibindings for this type (note that x is also inserted here).
for (; i != sortedMultibindingsVector.end() && i->first == x.first; ++i) {
b.elems.push_back(NormalizedMultibindingData::Elem(i->second));
if (i->second.needs_allocation) {
fixed_size_allocator_data.addType(x.first);
} else {
fixed_size_allocator_data.addExternallyAllocatedType(x.first);
}
}
#ifdef FRUIT_EXTRA_DEBUG
std::cout << std::endl;
#endif
}
}
} // namespace impl
} // namespace fruit
<commit_msg>Add some debug prints (executed only with FRUIT_EXTRA_DEBUG) to help debug compressed bindings.<commit_after>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define IN_FRUIT_CPP_FILE
#include <cstdlib>
#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fruit/impl/util/type_info.h>
#include <fruit/impl/storage/injector_storage.h>
#include <fruit/impl/storage/component_storage.h>
#include <fruit/impl/data_structures/semistatic_graph.templates.h>
#include <fruit/impl/meta/basics.h>
#include <fruit/impl/storage/normalized_component_storage.h>
using std::cout;
using std::endl;
using namespace fruit::impl;
namespace {
std::string multipleBindingsError(TypeId type) {
return "Fatal injection error: the type " + type.type_info->name() + " was provided more than once, with different bindings.\n"
+ "This was not caught at compile time because at least one of the involved components bound this type but didn't expose it in the component signature.\n"
+ "If the type has a default constructor or an Inject annotation, this problem may arise even if this type is bound/provided by only one component (and then hidden), if this type is auto-injected in another component.\n"
+ "If the source of the problem is unclear, try exposing this type in all the component signatures where it's bound; if no component hides it this can't happen.\n";
}
auto typeInfoLessThanForMultibindings = [](const std::pair<TypeId, MultibindingData>& x,
const std::pair<TypeId, MultibindingData>& y) {
return x.first < y.first;
};
} // namespace
namespace fruit {
namespace impl {
std::vector<std::pair<TypeId, BindingData>>
BindingNormalization::normalizeBindings(const std::vector<std::pair<TypeId, BindingData>>& bindings_vector,
FixedSizeAllocator::FixedSizeAllocatorData& fixed_size_allocator_data,
std::vector<CompressedBinding>&& compressed_bindings_vector,
const std::vector<std::pair<TypeId, MultibindingData>>& multibindings_vector,
const std::vector<TypeId>& exposed_types,
BindingNormalization::BindingCompressionInfoMap& bindingCompressionInfoMap) {
HashMap<TypeId, BindingData> binding_data_map = createHashMap<TypeId, BindingData>(bindings_vector.size());
for (auto& p : bindings_vector) {
auto itr = binding_data_map.find(p.first);
if (itr != binding_data_map.end()) {
if (!(p.second == itr->second)) {
std::cerr << multipleBindingsError(p.first) << std::endl;
exit(1);
}
// Otherwise ok, duplicate but consistent binding.
} else {
// New binding, add it to the map.
binding_data_map[p.first] = p.second;
}
}
for (const auto& p : bindings_vector) {
if (p.second.needsAllocation()) {
fixed_size_allocator_data.addType(p.first);
} else {
fixed_size_allocator_data.addExternallyAllocatedType(p.first);
}
}
// Remove duplicates from `compressedBindingsVector'.
// CtypeId -> (ItypeId, bindingData)
HashMap<TypeId, std::pair<TypeId, BindingData>> compressed_bindings_map =
createHashMap<TypeId, std::pair<TypeId, BindingData>>(compressed_bindings_vector.size());
// This also removes any duplicates. No need to check for multiple I->C, I2->C mappings, will filter these out later when
// considering deps.
for (CompressedBinding& compressed_binding : compressed_bindings_vector) {
compressed_bindings_map[compressed_binding.class_id] = {compressed_binding.interface_id, compressed_binding.binding_data};
}
// We can't compress the binding if C is a dep of a multibinding.
for (auto p : multibindings_vector) {
const BindingDeps* deps = p.second.deps;
if (deps != nullptr) {
for (std::size_t i = 0; i < deps->num_deps; ++i) {
compressed_bindings_map.erase(deps->deps[i]);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: ignoring compressed binding for " << deps->deps[i] << " because it's a dep of a multibinding." << std::endl;
#endif
}
}
}
// We can't compress the binding if C is an exposed type (but I is likely to be exposed instead).
for (TypeId type : exposed_types) {
compressed_bindings_map.erase(type);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: ignoring compressed binding for " << type << " because it's an exposed type." << std::endl;
#endif
}
// We can't compress the binding if some type X depends on C and X!=I.
for (auto& p : binding_data_map) {
TypeId x_id = p.first;
BindingData binding_data = p.second;
if (!binding_data.isCreated()) {
for (std::size_t i = 0; i < binding_data.getDeps()->num_deps; ++i) {
TypeId c_id = binding_data.getDeps()->deps[i];
auto itr = compressed_bindings_map.find(c_id);
if (itr != compressed_bindings_map.end() && itr->second.first != x_id) {
compressed_bindings_map.erase(itr);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: ignoring compressed binding for " << c_id << " because the type " << x_id << " depends on it." << std::endl;
#endif
}
}
}
}
// Two pairs of compressible bindings (I->C) and (C->X) can not exist (the C of a compressible binding is always bound either
// using constructor binding or provider binding, it can't be a binding itself). So no need to check for that.
bindingCompressionInfoMap =
createHashMap<TypeId, BindingNormalization::BindingCompressionInfo>(compressed_bindings_map.size());
// Now perform the binding compression.
for (auto& p : compressed_bindings_map) {
TypeId c_id = p.first;
TypeId i_id = p.second.first;
BindingData binding_data = p.second.second;
auto i_binding_data = binding_data_map.find(i_id);
auto c_binding_data = binding_data_map.find(c_id);
FruitAssert(i_binding_data != binding_data_map.end());
FruitAssert(c_binding_data != binding_data_map.end());
bindingCompressionInfoMap[c_id] = BindingCompressionInfo{i_id, i_binding_data->second, c_binding_data->second};
// Note that even if I is the one that remains, C is the one that will be allocated, not I.
FruitAssert(!i_binding_data->second.needsAllocation());
i_binding_data->second = binding_data;
binding_data_map.erase(c_binding_data);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: performing binding compression for the edge " << i_id << "->" << c_id << std::endl;
#endif
}
// Copy the normalized bindings into the result vector.
std::vector<std::pair<TypeId, BindingData>> result;
result.reserve(binding_data_map.size());
for (auto& p : binding_data_map) {
result.push_back(p);
}
return result;
}
void BindingNormalization::addMultibindings(std::unordered_map<TypeId, NormalizedMultibindingData>& multibindings,
FixedSizeAllocator::FixedSizeAllocatorData& fixed_size_allocator_data,
const std::vector<std::pair<TypeId, MultibindingData>>& multibindingsVector) {
std::vector<std::pair<TypeId, MultibindingData>> sortedMultibindingsVector = multibindingsVector;
std::sort(sortedMultibindingsVector.begin(), sortedMultibindingsVector.end(),
typeInfoLessThanForMultibindings);
#ifdef FRUIT_EXTRA_DEBUG
std::cout << "InjectorStorage: adding multibindings:" << std::endl;
#endif
// Now we must merge multiple bindings for the same type.
for (auto i = sortedMultibindingsVector.begin(); i != sortedMultibindingsVector.end(); /* no increment */) {
const std::pair<TypeId, MultibindingData>& x = *i;
NormalizedMultibindingData& b = multibindings[x.first];
// Might be set already, but we need to set it if there was no multibinding for this type.
b.get_multibindings_vector = x.second.get_multibindings_vector;
#ifdef FRUIT_EXTRA_DEBUG
std::cout << x.first << " has " << std::distance(i, sortedMultibindingsVector.end()) << " multibindings." << std::endl;
#endif
// Insert all multibindings for this type (note that x is also inserted here).
for (; i != sortedMultibindingsVector.end() && i->first == x.first; ++i) {
b.elems.push_back(NormalizedMultibindingData::Elem(i->second));
if (i->second.needs_allocation) {
fixed_size_allocator_data.addType(x.first);
} else {
fixed_size_allocator_data.addExternallyAllocatedType(x.first);
}
}
#ifdef FRUIT_EXTRA_DEBUG
std::cout << std::endl;
#endif
}
}
} // namespace impl
} // namespace fruit
<|endoftext|> |
<commit_before>/* The MIT License:
Copyright (c) 2012-2015 Ivan Gagis <igagis@gmail.com>
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. */
// Home page: http://morda.googlecode.com
/**
* @author Ivan Gagis <igagis@gmail.com>
*/
#pragma once
#include <string>
#include <set>
#include <ting/Shared.hpp>
#include <ting/util.hpp>
#include "../util/keycodes.hpp"
#include "../util/Matrix4.hpp"
#include "../util/Vector2.hpp"
#include "../util/Rectangle2.hpp"
#include "../util/LayoutParams.hpp"
#include "../config.hpp"
#include <stob/dom.hpp>
namespace morda{
class Container;
class Widget : virtual public ting::Shared{
friend class Container;
friend class App;
public:
typedef std::list<std::shared_ptr<Widget>> T_ChildrenList;
private:
Container* parent = nullptr;
T_ChildrenList::iterator parentIter;
std::set<unsigned> hovered;
bool isVisible;
bool isEnabled;
morda::Rect2r rect;
//cached minimal dimensions needed to show widget's contents normally
mutable morda::Vec2r minDim;
mutable bool minDimNeedsRecomputing = true;
//clip widgets contents by widget's border if set to true
bool clip;
public:
bool Clip()const NOEXCEPT{
return this->clip;
}
void SetClip(bool clip)NOEXCEPT{
this->clip = clip;
}
private:
//logical ID of the widget
std::string name;
bool relayoutNeeded = true;
std::unique_ptr<stob::Node> layout;
std::unique_ptr<LayoutParams> layoutParams;
public:
std::unique_ptr<LayoutParams> ResetLayoutParams(std::unique_ptr<LayoutParams> params = nullptr)NOEXCEPT;
bool NeedsRelayout()const NOEXCEPT{
return this->relayoutNeeded;
}
const std::string& Name()const NOEXCEPT{
return this->name;
}
const Container* Parent()const NOEXCEPT{
return this->parent;
}
Container* Parent()NOEXCEPT{
return this->parent;
}
//NOTE: if only parent holds Ref then object may be deleted
void RemoveFromParent();
/**
* @brief Check if widget is hovered by any pointer.
* @return true if hovered by any pointer.
* @return false otherwise.
*/
bool IsHovered()const NOEXCEPT{
return this->hovered.size() != 0;
}
/**
* @brief Check if widget is hovered by given pointer.
* @param pointerID - pointer ID to check against.
* @return true if widget is hovered by given pointer ID.
* @return false otherwise.
*/
bool IsHovered(unsigned pointerID)const NOEXCEPT{
return this->hovered.find(pointerID) != this->hovered.end();
}
private:
void SetHovered(bool isHovered, unsigned pointerID){
if(isHovered){
if(this->IsHovered(pointerID)){
return;
}
this->hovered.insert(pointerID);
}else{
if(!this->IsHovered(pointerID)){
return;
}
this->hovered.erase(pointerID);
}
this->OnHoverChanged(pointerID);
}
void SetUnhovered(){
this->hovered.clear();
}
public:
const morda::Rect2r& Rect()const NOEXCEPT{
return this->rect;
}
morda::Rect2i ComputeViewportRect(const Matr4r& matrix)const NOEXCEPT;
void MoveTo(const morda::Vec2r& newPos)NOEXCEPT{
this->rect.p = newPos;
}
void MoveBy(const morda::Vec2r& delta)NOEXCEPT{
this->rect.p += delta;
}
void Resize(const morda::Vec2r& newDims);
void ResizeBy(const morda::Vec2r& delta){
this->Resize(this->Rect().d + delta);
}
virtual std::shared_ptr<Widget> FindChildByName(const std::string& name)NOEXCEPT;
template <typename T> std::shared_ptr<T> FindChildByNameAs(const std::string& name)NOEXCEPT{
return std::dynamic_pointer_cast<T>(this->FindChildByName(name));
}
public:
Widget(const stob::Node* chain);
public:
virtual ~Widget()NOEXCEPT{}
virtual void Render(const morda::Matr4r& matrix)const{}
private:
void RenderInternal(const morda::Matr4r& matrix)const;
private:
void OnKeyInternal(bool isDown, EKey keyCode);
private:
bool isFocused = false;
public:
//return true to consume
virtual bool OnKey(bool isDown, morda::EKey keyCode){
return false;
}
void Focus()NOEXCEPT;
void Unfocus()NOEXCEPT;
bool IsFocused()const NOEXCEPT{
return this->isFocused;
}
virtual void OnFocusedChanged(){}
enum class EMouseButton{
LEFT,
RIGHT,
MIDDLE,
WHEEL_UP,
WHEEL_DOWN,
ENUM_SIZE
};
//return true to consume event
virtual bool OnMouseButton(bool isDown, const morda::Vec2r& pos, EMouseButton button, unsigned pointerID){
return false;
}
//return true to consume event
virtual bool OnMouseMove(const morda::Vec2r& pos, unsigned pointerID){
return false;
}
virtual void OnHoverChanged(unsigned pointerID){
// TRACE(<< "Widget::OnHoverChanged(): this->IsHovered() = " << this->IsHovered() << std::endl)
}
virtual void OnResize(){
// TRACE(<< "Widget::OnResize(): invoked" << std::endl)
}
morda::Vec2r Measure(const morda::Vec2r& quotum = morda::Vec2r(-1))const{
if(quotum == morda::Vec2r(-1)){
if(this->minDimNeedsRecomputing){
this->minDim = this->ComputeMinDim(quotum);
this->minDimNeedsRecomputing = false;
}
return this->minDim;
}else{
return this->ComputeMinDim(quotum);
}
}
protected:
virtual morda::Vec2r ComputeMinDim(const Vec2r& quotum)const{
return morda::Vec2r(0, 0);
}
public:
void SetRelayoutNeeded()NOEXCEPT;
void SetVisible(bool visible){
this->isVisible = visible;
if(!this->isVisible){
this->SetUnhovered();
}
}
bool IsVisible()const NOEXCEPT{
return this->isVisible;
}
void SetEnabled(bool enable)NOEXCEPT{
this->isEnabled = enable;
}
bool IsEnabled()const NOEXCEPT{
return this->isEnabled;
}
/**
* @brief Check if point is within the widget bounds.
* @param pos - point to check in widget coordinates.
* @return true if point is inside of the widget boundaries.
* @return false otherwise.
*/
bool Contains(const morda::Vec2r& pos)const NOEXCEPT{
return morda::Rect2r(morda::Vec2r(0, 0), this->Rect().d).Overlaps(pos);
}
virtual void OnTopmostChanged(){}
bool IsTopmost()const NOEXCEPT;
void MakeTopmost();
};
}//~namespace
<commit_msg>cached quotum<commit_after>/* The MIT License:
Copyright (c) 2012-2015 Ivan Gagis <igagis@gmail.com>
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. */
// Home page: http://morda.googlecode.com
/**
* @author Ivan Gagis <igagis@gmail.com>
*/
#pragma once
#include <string>
#include <set>
#include <ting/Shared.hpp>
#include <ting/util.hpp>
#include "../util/keycodes.hpp"
#include "../util/Matrix4.hpp"
#include "../util/Vector2.hpp"
#include "../util/Rectangle2.hpp"
#include "../util/LayoutParams.hpp"
#include "../config.hpp"
#include <stob/dom.hpp>
namespace morda{
class Container;
class Widget : virtual public ting::Shared{
friend class Container;
friend class App;
public:
typedef std::list<std::shared_ptr<Widget>> T_ChildrenList;
private:
Container* parent = nullptr;
T_ChildrenList::iterator parentIter;
std::set<unsigned> hovered;
bool isVisible;
bool isEnabled;
morda::Rect2r rect;
//cached minimal dimensions needed to show widget's contents normally
mutable morda::Vec2r minDim;
mutable bool minDimNeedsRecomputing = true;
mutable Vec2r cachedQuotum;
//clip widgets contents by widget's border if set to true
bool clip;
public:
bool Clip()const NOEXCEPT{
return this->clip;
}
void SetClip(bool clip)NOEXCEPT{
this->clip = clip;
}
private:
//logical ID of the widget
std::string name;
bool relayoutNeeded = true;
std::unique_ptr<stob::Node> layout;
std::unique_ptr<LayoutParams> layoutParams;
public:
std::unique_ptr<LayoutParams> ResetLayoutParams(std::unique_ptr<LayoutParams> params = nullptr)NOEXCEPT;
bool NeedsRelayout()const NOEXCEPT{
return this->relayoutNeeded;
}
const std::string& Name()const NOEXCEPT{
return this->name;
}
const Container* Parent()const NOEXCEPT{
return this->parent;
}
Container* Parent()NOEXCEPT{
return this->parent;
}
//NOTE: if only parent holds Ref then object may be deleted
void RemoveFromParent();
/**
* @brief Check if widget is hovered by any pointer.
* @return true if hovered by any pointer.
* @return false otherwise.
*/
bool IsHovered()const NOEXCEPT{
return this->hovered.size() != 0;
}
/**
* @brief Check if widget is hovered by given pointer.
* @param pointerID - pointer ID to check against.
* @return true if widget is hovered by given pointer ID.
* @return false otherwise.
*/
bool IsHovered(unsigned pointerID)const NOEXCEPT{
return this->hovered.find(pointerID) != this->hovered.end();
}
private:
void SetHovered(bool isHovered, unsigned pointerID){
if(isHovered){
if(this->IsHovered(pointerID)){
return;
}
this->hovered.insert(pointerID);
}else{
if(!this->IsHovered(pointerID)){
return;
}
this->hovered.erase(pointerID);
}
this->OnHoverChanged(pointerID);
}
void SetUnhovered(){
this->hovered.clear();
}
public:
const morda::Rect2r& Rect()const NOEXCEPT{
return this->rect;
}
morda::Rect2i ComputeViewportRect(const Matr4r& matrix)const NOEXCEPT;
void MoveTo(const morda::Vec2r& newPos)NOEXCEPT{
this->rect.p = newPos;
}
void MoveBy(const morda::Vec2r& delta)NOEXCEPT{
this->rect.p += delta;
}
void Resize(const morda::Vec2r& newDims);
void ResizeBy(const morda::Vec2r& delta){
this->Resize(this->Rect().d + delta);
}
virtual std::shared_ptr<Widget> FindChildByName(const std::string& name)NOEXCEPT;
template <typename T> std::shared_ptr<T> FindChildByNameAs(const std::string& name)NOEXCEPT{
return std::dynamic_pointer_cast<T>(this->FindChildByName(name));
}
public:
Widget(const stob::Node* chain);
public:
virtual ~Widget()NOEXCEPT{}
virtual void Render(const morda::Matr4r& matrix)const{}
private:
void RenderInternal(const morda::Matr4r& matrix)const;
private:
void OnKeyInternal(bool isDown, EKey keyCode);
private:
bool isFocused = false;
public:
//return true to consume
virtual bool OnKey(bool isDown, morda::EKey keyCode){
return false;
}
void Focus()NOEXCEPT;
void Unfocus()NOEXCEPT;
bool IsFocused()const NOEXCEPT{
return this->isFocused;
}
virtual void OnFocusedChanged(){}
enum class EMouseButton{
LEFT,
RIGHT,
MIDDLE,
WHEEL_UP,
WHEEL_DOWN,
ENUM_SIZE
};
//return true to consume event
virtual bool OnMouseButton(bool isDown, const morda::Vec2r& pos, EMouseButton button, unsigned pointerID){
return false;
}
//return true to consume event
virtual bool OnMouseMove(const morda::Vec2r& pos, unsigned pointerID){
return false;
}
virtual void OnHoverChanged(unsigned pointerID){
// TRACE(<< "Widget::OnHoverChanged(): this->IsHovered() = " << this->IsHovered() << std::endl)
}
virtual void OnResize(){
// TRACE(<< "Widget::OnResize(): invoked" << std::endl)
}
morda::Vec2r Measure(const morda::Vec2r& quotum = morda::Vec2r(-1))const{
if(!this->minDimNeedsRecomputing && quotum == this->cachedQuotum){
return this->minDim;
}else{
this->minDim = this->ComputeMinDim(quotum);
this->minDimNeedsRecomputing = false;
this->cachedQuotum = quotum;
return this->minDim;
}
}
protected:
virtual morda::Vec2r ComputeMinDim(const Vec2r& quotum)const{
return morda::Vec2r(0, 0);
}
public:
void SetRelayoutNeeded()NOEXCEPT;
void SetVisible(bool visible){
this->isVisible = visible;
if(!this->isVisible){
this->SetUnhovered();
}
}
bool IsVisible()const NOEXCEPT{
return this->isVisible;
}
void SetEnabled(bool enable)NOEXCEPT{
this->isEnabled = enable;
}
bool IsEnabled()const NOEXCEPT{
return this->isEnabled;
}
/**
* @brief Check if point is within the widget bounds.
* @param pos - point to check in widget coordinates.
* @return true if point is inside of the widget boundaries.
* @return false otherwise.
*/
bool Contains(const morda::Vec2r& pos)const NOEXCEPT{
return morda::Rect2r(morda::Vec2r(0, 0), this->Rect().d).Overlaps(pos);
}
virtual void OnTopmostChanged(){}
bool IsTopmost()const NOEXCEPT;
void MakeTopmost();
};
}//~namespace
<|endoftext|> |
<commit_before>/*
* Implementation of a ACME client.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "GlueHttpClient.hxx"
#include "balancer.hxx"
#include "tcp_stock.hxx"
#include "stock/MapStock.hxx"
#include "tcp_balancer.hxx"
#include "address_resolver.hxx"
#include "http_request.hxx"
#include "http_response.hxx"
#include "http_address.hxx"
#include "pool.hxx"
#include "filtered_socket.hxx"
#include "ssl/ssl_client.hxx"
#include "event/Loop.hxx"
#include "async.hxx"
#include "istream/Handler.hxx"
#include "istream/Pointer.hxx"
#include "fb_pool.hxx"
#include "thread_pool.hxx"
#include <stdexcept>
#include <string.h>
#include <netdb.h>
gcc_noreturn
static void
ThrowError(GError *error)
{
std::string msg(error->message);
g_error_free(error);
throw std::runtime_error(std::move(msg));
}
static void
CheckThrowError(GError *error)
{
if (error != nullptr)
ThrowError(error);
}
static AddressList &
ResolveOrThrow(struct pool &p, const char *host_and_port, int default_port)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
GError *error = nullptr;
auto *al = address_list_resolve_new(&p, host_and_port, default_port,
&hints, &error);
if (al == nullptr)
ThrowError(error);
return *al;
}
GlueHttpServerAddress::GlueHttpServerAddress(struct pool &p, bool _ssl,
const char *_host_and_port,
int default_port)
:host_and_port(_host_and_port),
addresses(ResolveOrThrow(p, _host_and_port, default_port)),
ssl(_ssl) {}
GlueHttpClient::GlueHttpClient(struct pool &p, EventLoop &event_loop)
:balancer(balancer_new(p, event_loop)),
tcp_stock(tcp_stock_new(event_loop, 0)),
tcp_balancer(tcp_balancer_new(*tcp_stock, *balancer))
{
fb_pool_init(event_loop, false);
ssl_client_init();
}
GlueHttpClient::~GlueHttpClient()
{
thread_pool_stop();
ssl_client_deinit();
fb_pool_deinit();
tcp_balancer_free(tcp_balancer);
delete tcp_stock;
balancer_free(balancer);
thread_pool_join();
thread_pool_deinit();
}
class SslSocketFilterFactory final : public SocketFilterFactory {
struct pool &pool;
EventLoop &event_loop;
const char *const host;
public:
SslSocketFilterFactory(struct pool &_pool,
EventLoop &_event_loop,
const char *_host)
:pool(_pool), event_loop(_event_loop), host(_host) {}
void *CreateFilter(GError **error_r) override {
return ssl_client_create(&pool, event_loop, host, error_r);
}
};
void
GlueHttpClient::Request(struct pool &p, EventLoop &event_loop,
GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers, Istream *body,
const struct http_response_handler &handler,
void *handler_ctx,
struct async_operation_ref &async_ref)
{
const SocketFilter *filter = nullptr;
SocketFilterFactory *filter_factory = nullptr;
if (server.ssl) {
filter = &ssl_client_get_filter();
filter_factory = NewFromPool<SslSocketFilterFactory>(p, p, event_loop,
/* TODO: only host */
server.host_and_port);
}
auto *address = NewFromPool<HttpAddress>(p,
URI_SCHEME_HTTP, server.ssl,
server.host_and_port, uri);
address->addresses.CopyFrom(&p, server.addresses);
http_request(p, event_loop, *tcp_balancer, 0,
filter, filter_factory,
method, *address,
std::move(headers), body,
handler, handler_ctx, async_ref);
}
class GlueHttpRequest final : IstreamHandler {
http_status_t status;
struct strmap *headers;
IstreamPointer body;
std::string body_string;
GError *error = nullptr;
bool done = false;
public:
GlueHttpRequest():body(nullptr) {}
~GlueHttpRequest() {
if (error != nullptr)
g_error_free(error);
}
bool IsDone() const {
return done;
}
void CheckThrowError() {
GError *_error = error;
error = nullptr;
::CheckThrowError(_error);
}
GlueHttpResponse MoveResponse() {
return {status, *headers, std::move(body_string)};
}
private:
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
body_string.append((const char *)data, length);
return length;
}
void OnEof() override {
done = true;
}
void OnError(GError *_error) override {
error = _error;
done = true;
}
/* virtual methods from struct http_response_handler */
void OnResponse(http_status_t _status, struct strmap *_headers,
Istream *_body) {
assert(error == nullptr);
status = _status;
headers = _headers;
if (_body != nullptr) {
body.Set(*_body, *this);
body.Read();
} else
done = true;
}
void OnResponseError(GError *_error) {
assert(error == nullptr);
error = _error;
done = true;
}
static void OnResponse(http_status_t status, struct strmap *headers,
Istream *body, void *ctx) {
((GlueHttpRequest *)ctx)->OnResponse(status, headers, body);
}
static void OnResponseError(GError *_error, void *ctx) {
((GlueHttpRequest *)ctx)->OnResponseError(_error);
}
public:
static const struct http_response_handler handler;
};
constexpr struct http_response_handler GlueHttpRequest::handler = {
OnResponse,
OnResponseError,
};
GlueHttpResponse
GlueHttpClient::Request(EventLoop &event_loop,
struct pool &p, GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers, Istream *body)
{
struct async_operation_ref async_ref;
GlueHttpRequest request;
Request(p, event_loop, server, method, uri, std::move(headers), body,
GlueHttpRequest::handler, &request, async_ref);
while (!request.IsDone() && event_loop.LoopOnce()) {}
request.CheckThrowError();
return request.MoveResponse();
}
<commit_msg>certdb/GlueHttpClient: use AtScopeExit()<commit_after>/*
* Implementation of a ACME client.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "GlueHttpClient.hxx"
#include "balancer.hxx"
#include "tcp_stock.hxx"
#include "stock/MapStock.hxx"
#include "tcp_balancer.hxx"
#include "address_resolver.hxx"
#include "http_request.hxx"
#include "http_response.hxx"
#include "http_address.hxx"
#include "pool.hxx"
#include "filtered_socket.hxx"
#include "ssl/ssl_client.hxx"
#include "event/Loop.hxx"
#include "async.hxx"
#include "istream/Handler.hxx"
#include "istream/Pointer.hxx"
#include "fb_pool.hxx"
#include "thread_pool.hxx"
#include "util/ScopeExit.hxx"
#include <stdexcept>
#include <string.h>
#include <netdb.h>
gcc_noreturn
static void
ThrowError(GError *error)
{
AtScopeExit(error) { g_error_free(error); };
throw std::runtime_error(error->message);
}
static void
CheckThrowError(GError *error)
{
if (error != nullptr)
ThrowError(error);
}
static AddressList &
ResolveOrThrow(struct pool &p, const char *host_and_port, int default_port)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
GError *error = nullptr;
auto *al = address_list_resolve_new(&p, host_and_port, default_port,
&hints, &error);
if (al == nullptr)
ThrowError(error);
return *al;
}
GlueHttpServerAddress::GlueHttpServerAddress(struct pool &p, bool _ssl,
const char *_host_and_port,
int default_port)
:host_and_port(_host_and_port),
addresses(ResolveOrThrow(p, _host_and_port, default_port)),
ssl(_ssl) {}
GlueHttpClient::GlueHttpClient(struct pool &p, EventLoop &event_loop)
:balancer(balancer_new(p, event_loop)),
tcp_stock(tcp_stock_new(event_loop, 0)),
tcp_balancer(tcp_balancer_new(*tcp_stock, *balancer))
{
fb_pool_init(event_loop, false);
ssl_client_init();
}
GlueHttpClient::~GlueHttpClient()
{
thread_pool_stop();
ssl_client_deinit();
fb_pool_deinit();
tcp_balancer_free(tcp_balancer);
delete tcp_stock;
balancer_free(balancer);
thread_pool_join();
thread_pool_deinit();
}
class SslSocketFilterFactory final : public SocketFilterFactory {
struct pool &pool;
EventLoop &event_loop;
const char *const host;
public:
SslSocketFilterFactory(struct pool &_pool,
EventLoop &_event_loop,
const char *_host)
:pool(_pool), event_loop(_event_loop), host(_host) {}
void *CreateFilter(GError **error_r) override {
return ssl_client_create(&pool, event_loop, host, error_r);
}
};
void
GlueHttpClient::Request(struct pool &p, EventLoop &event_loop,
GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers, Istream *body,
const struct http_response_handler &handler,
void *handler_ctx,
struct async_operation_ref &async_ref)
{
const SocketFilter *filter = nullptr;
SocketFilterFactory *filter_factory = nullptr;
if (server.ssl) {
filter = &ssl_client_get_filter();
filter_factory = NewFromPool<SslSocketFilterFactory>(p, p, event_loop,
/* TODO: only host */
server.host_and_port);
}
auto *address = NewFromPool<HttpAddress>(p,
URI_SCHEME_HTTP, server.ssl,
server.host_and_port, uri);
address->addresses.CopyFrom(&p, server.addresses);
http_request(p, event_loop, *tcp_balancer, 0,
filter, filter_factory,
method, *address,
std::move(headers), body,
handler, handler_ctx, async_ref);
}
class GlueHttpRequest final : IstreamHandler {
http_status_t status;
struct strmap *headers;
IstreamPointer body;
std::string body_string;
GError *error = nullptr;
bool done = false;
public:
GlueHttpRequest():body(nullptr) {}
~GlueHttpRequest() {
if (error != nullptr)
g_error_free(error);
}
bool IsDone() const {
return done;
}
void CheckThrowError() {
GError *_error = error;
error = nullptr;
::CheckThrowError(_error);
}
GlueHttpResponse MoveResponse() {
return {status, *headers, std::move(body_string)};
}
private:
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
body_string.append((const char *)data, length);
return length;
}
void OnEof() override {
done = true;
}
void OnError(GError *_error) override {
error = _error;
done = true;
}
/* virtual methods from struct http_response_handler */
void OnResponse(http_status_t _status, struct strmap *_headers,
Istream *_body) {
assert(error == nullptr);
status = _status;
headers = _headers;
if (_body != nullptr) {
body.Set(*_body, *this);
body.Read();
} else
done = true;
}
void OnResponseError(GError *_error) {
assert(error == nullptr);
error = _error;
done = true;
}
static void OnResponse(http_status_t status, struct strmap *headers,
Istream *body, void *ctx) {
((GlueHttpRequest *)ctx)->OnResponse(status, headers, body);
}
static void OnResponseError(GError *_error, void *ctx) {
((GlueHttpRequest *)ctx)->OnResponseError(_error);
}
public:
static const struct http_response_handler handler;
};
constexpr struct http_response_handler GlueHttpRequest::handler = {
OnResponse,
OnResponseError,
};
GlueHttpResponse
GlueHttpClient::Request(EventLoop &event_loop,
struct pool &p, GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers, Istream *body)
{
struct async_operation_ref async_ref;
GlueHttpRequest request;
Request(p, event_loop, server, method, uri, std::move(headers), body,
GlueHttpRequest::handler, &request, async_ref);
while (!request.IsDone() && event_loop.LoopOnce()) {}
request.CheckThrowError();
return request.MoveResponse();
}
<|endoftext|> |
<commit_before>
#include <QApplication>
#include "cmd.h"
#include "font.h"
#include "wd.h"
#include "../base/bedit.h"
#include "../base/dlog.h"
#include "../base/jsvr.h"
#include "../base/note.h"
#include "../base/state.h"
#include "../base/tedit.h"
#include "../base/term.h"
// sm does its own parsing of the wd command
extern Cmd cmd;
extern int rc;
static string smact();
static string smactive();
static string smclose();
static string smerror(string p);
static string smfocus();
static string smfont();
static string smget();
static string smgetactive();
static string smgetinputlog();
static string smgetscript(string);
static string smgettabs(QString);
static string smgetwin(string);
static string smgetwin1(Bedit *);
static string smgetwin2(Note *n);
static string smgetxywh();
static string smgetxywh1(QWidget *);
static string smopen();
static string smprompt();
static string smreplace();
static string smsave();
static string smsaveactive();
static string smsaveall();
static string smset();
static string smsetscroll(Bedit *,string);
static string smsetinputlog(string,string);
static string smsetselect(Bedit *,string);
static string smsettext(string,string);
static string smsetxywh(string,string);
// ---------------------------------------------------------------------
string sm(string c)
{
rc=0;
if (c=="act")
return smact();
if (c=="active")
return smactive();
if (c=="close")
return smclose();
if (c=="focus")
return smfocus();
if (c=="font")
return smfont();
if (c=="get")
return smget();
if (c=="new")
return smopen();
if (c=="open")
return smopen();
if (c=="replace")
return smreplace();
if (c=="save")
return smsave();
if (c=="set")
return smset();
else if (c=="prompt")
return smprompt();
cmd.getparms();
return smerror("unrecognized sm command: " + c);
}
// ---------------------------------------------------------------------
string smact()
{
cmd.getparms();
term->smact();
return"";
}
// ---------------------------------------------------------------------
string smactive()
{
string p=cmd.getparms();
QStringList opt=qsplit(p);
if (note==0 || note->editIndex()<0)
return smerror ("No active edit window");
if (opt[0]!="tab")
return smerror ("unrecognized sm command parameters: " + p);
int ndx=opt[1].toInt();
if (ndx<0 || ndx>=note->count())
return smerror ("invalid tab index: " + p);
note->setindex(ndx);
return "";
}
// ---------------------------------------------------------------------
string smclose()
{
string c=cmd.getid();
string p=cmd.getparms();
if (c=="tab") {
if (note==0 || note->editIndex()<0)
return smerror ("No active edit window");
int ndx=s2q(p).toInt();
if (ndx<0 || ndx>=note->count())
return smerror ("invalid tab index: " + p);
note->tabclose(ndx);
} else if (c=="edit") {
if (note==0)
return smerror ("No edit window");
note->close();
} else if (c=="edit2") {
if (note2==0)
return smerror ("No edit2 window");
note2->close();
} else
return smerror ("unrecognized sm command parameters: " + p);
return "";
}
// ---------------------------------------------------------------------
string smerror(string p)
{
rc=1;
return p;
}
// ---------------------------------------------------------------------
string smfocus()
{
string p=cmd.getparms();
if (p.empty())
return smerror("sm focus needs additional parameters");
if (p=="term")
term->smact();
else if (p=="edit") {
if (note==0 || note->editIndex()==-1)
return smerror("No active edit window");
note->activateWindow();
note->raise();
note->repaint();
} else if (p=="edit2") {
if (note2==0 || note2->editIndex()==-1)
return smerror("No active edit2 window");
setnote(note2);
note->activateWindow();
note->raise();
note->repaint();
} else
return smerror("unrecognized sm command: focus " + p);
return "";
}
// ---------------------------------------------------------------------
string smfont()
{
string p=cmd.getparms();
if (!p.empty()) {
Font *fnt = new Font(p);
if (fnt->error) {
delete fnt;
return smerror("unrecognized sm command: font " + p);
} else {
config.Font=fnt->font;
delete fnt;
}
}
fontset(config.Font);
return "";
}
// ---------------------------------------------------------------------
string smget()
{
string p=cmd.getparms();
if (p.size()==0)
return smerror("sm get needs additional parameters");
if (p=="active")
return smgetactive();
if (p=="term" || p=="edit" || p=="edit2")
return smgetwin(p);
if (p=="inputlog")
return smgetinputlog();
if (p=="xywh")
return smgetxywh();
QStringList s=qsplit(p);
if (s[0]=="tabs") {
if(s.size()<=1)
return smerror("sm command requires another parameter: get tabs");
else
return smgettabs(s[1]);
}
return smerror("unrecognized sm command: get " + p);
}
// ---------------------------------------------------------------------
string smgetactive()
{
rc=-1;
return (note && ActiveWindows.indexOf(note)<ActiveWindows.indexOf(term))
? "edit" : "term";
}
// ---------------------------------------------------------------------
string smgetinputlog()
{
rc=-1;
return q2s(dlog_get());
}
// ---------------------------------------------------------------------
string smgetscript(string f)
{
return dors(">{.getscripts_j_ '" + f + "'");
}
// ---------------------------------------------------------------------
string smgettabs(QString p)
{
Note *n;
if (p=="edit") {
if (note==0)
return smerror("No active edit window");
n=note;
} else if (p=="edit2") {
if (note2==0)
return smerror("No active edit2 window");
n=note2;
} else
return smerror("sm get tabs needs edit or edit2 parameter");
rc=-2;
return n->gettabstate();
}
// ---------------------------------------------------------------------
string smgetwin(string p)
{
rc=-2;
if (p=="term")
return smgetwin1(tedit);
if (p=="edit") {
if (note==0)
return smerror("No active edit window");
return smgetwin2(note);
}
if (note2==0)
return smerror("No active edit2 window");
return smgetwin2(note2);
}
// ---------------------------------------------------------------------
string smgetwin1(Bedit *t)
{
string r;
if (t==0) {
r+=spair("text",(string)"");
r+=spair("select",(string)"");
} else {
QTextCursor c=t->textCursor();
int b=c.selectionStart();
int e=c.selectionEnd();
r+=spair("text",t->toPlainText());
r+=spair("select",QString::number(b)+" "+QString::number(e));
}
return r;
}
// ---------------------------------------------------------------------
string smgetwin2(Note *n)
{
if (n->editIndex()==-1)
return smgetwin1((Bedit *)0);
string r=smgetwin1((Bedit *)n->editPage());
r+=spair("file",n->editFile());
return r;
}
// ---------------------------------------------------------------------
string smgetxywh()
{
rc=-2;
string r;
r+=spair("text",smgetxywh1(term));
if (note)
r+=spair("edit",smgetxywh1(note));
if (note2)
r+=spair("edit2",smgetxywh1(note2));
return r;
}
// ---------------------------------------------------------------------
string smgetxywh1(QWidget *w)
{
QPoint p=w->pos();
QSize z=w->size();
return q2s(QString::number(p.rx())+" "+QString::number(p.ry())+" "+
QString::number(z.width())+" "+QString::number(z.height()));
}
// ---------------------------------------------------------------------
string smopen()
{
string c=cmd.getid();
string p=cmd.getparms();
if (c=="edit")
term->vieweditor();
if (c=="edit2") {
if (note==0)
return smerror("no edit window open");
note->on_winotherAct_triggered();
}
if (c=="edit" || c=="edit2")
return "";
if (c!="tab") {
return smerror("unrecognized sm command: open " + c);
}
term->vieweditor();
if (p.empty())
note->newtemp();
else {
QString f=s2q(smgetscript(p));
if (!cfexist(f))
return smerror("file not found: " + q2s(f));
note->fileopen(f);
}
rc=-1;
return i2s(note->editIndex());
}
// ---------------------------------------------------------------------
string smprompt()
{
string p=cmd.getparms();
term->smprompt(s2q(p));
return"";
}
// ---------------------------------------------------------------------
string smreplace()
{
string c=cmd.getid();
string p=cmd.getparms();
if (note==0 || note->editIndex()<0)
return smerror ("No active edit window");
if (c!="edit")
return smerror("unrecognized sm command: replace " + c);
if (p.empty())
return smerror("replace needs 2 parameters: edit filename");
QString f=s2q(smgetscript(p));
if (!cfexist(f))
return smerror("file not found: " + q2s(f));
note->filereplace(f);
return"";
}
// ---------------------------------------------------------------------
string smsave()
{
string p=cmd.getparms();
if (note==0)
return smerror("No active edit window");
if (p.empty())
return smerror("sm save parameter not given");
if (p=="edit")
return smsaveactive();
if (p=="tabs")
return smsaveall();
return smerror("sm save parameter should be 'edit' or 'tabs': " + p);
}
// ---------------------------------------------------------------------
string smsaveactive()
{
note->savecurrent();
return "";
}
// ---------------------------------------------------------------------
string smsaveall()
{
note->saveall();
return "";
}
// ---------------------------------------------------------------------
string smset()
{
string p=cmd.getid();
if (p.empty())
return smerror("sm set parameters not given");
string c=cmd.getid();
if (c.empty())
return smerror("sm set " + p + " parameters not given");
string q=cmd.getparms();
Bedit *e;
if (p=="term") {
e=tedit;
} else if (p=="edit") {
if (note==0)
return smerror("No active edit window");
e=(Bedit *)note->editPage();
} else if (p=="edit2") {
if (note2==0)
return smerror("No active edit2 window");
e=(Bedit *)note2->editPage();
} else if (p=="inputlog")
return smsetinputlog(c,q);
else
return smerror("unrecognized sm command: set " + p);
if (e==0 && (c=="scroll" || c=="select" || c=="text"))
return smerror("no edit window for sm command: set " + c);
if (p=="term" && (c=="scroll" || c=="select"))
return smerror("command applies only to an edit window: " + c);
if (c=="scroll")
return smsetscroll(e,q);
if (c=="select")
return smsetselect(e,q);
if (c=="text")
return smsettext(p,q);
if (c=="xywh")
return smsetxywh(p,q);
return smerror("unrecognized sm command: set " + p + " " + q);
}
// ---------------------------------------------------------------------
string smsetinputlog(string c,string q)
{
if (c!="text")
return smerror("unrecognized sm command: set inputlog " + c + "..." );
dlog_set(s2q(q));
return "";
}
// ---------------------------------------------------------------------
// set vertical scroll
string smsetscroll(Bedit *e, string q)
{
QList<int> s=qsl2intlist(qsplit(q));
if (s.size()!= 1)
return smerror("sm set scroll should have a single parameter of scroll size");
e->settop(s[0]);
return"";
}
// ---------------------------------------------------------------------
string smsetselect(Bedit *e, string q)
{
QList<int> s=qsl2intlist(qsplit(q));
if (s.size()!= 2)
return smerror("sm set select should have begin and end parameters");
int m=e->toPlainText().size();
if (s[1]==-1) s[1]=m;
s[1]=qMin(m,s[1]);
s[0]=qMin(s[0],s[1]);
e->setselect(s[0],s[1]-s[0]);
return"";
}
// ---------------------------------------------------------------------
string smsettext(string p,string s)
{
QString t=s2q(s);
if (p=="term")
tedit->setPlainText(t);
else if (p=="edit")
note->settext(t);
else
note2->settext(t);
return"";
}
// ---------------------------------------------------------------------
string smsetxywh(string m,string q)
{
QWidget *w;
if (m=="term")
w=term;
else if (m=="edit")
w=note;
else
w=note2;
QList<int> s=qsl2intlist(qsplit(q));
QPoint p=w->pos();
QSize z=w->size();
if (s[0]==-1) s[0]=p.rx();
if (s[1]==-1) s[1]=p.ry();
if (s[2]==-1) s[2]=z.width();
if (s[3]==-1) s[3]=z.height();
w->move(s[0],s[1]);
w->resize(s[2],s[3]);
return"";
}
<commit_msg>add sm get termcwh for term character width and height<commit_after>
#include <QApplication>
#include "cmd.h"
#include "font.h"
#include "wd.h"
#include "../base/bedit.h"
#include "../base/dlog.h"
#include "../base/jsvr.h"
#include "../base/note.h"
#include "../base/state.h"
#include "../base/tedit.h"
#include "../base/term.h"
// sm does its own parsing of the wd command
extern Cmd cmd;
extern int rc;
static string smact();
static string smactive();
static string smclose();
static string smerror(string p);
static string smfocus();
static string smfont();
static string smget();
static string smgetactive();
static string smgetinputlog();
static string smgetscript(string);
static string smgettabs(QString);
static string smgettermcwh();
static string smgetwin(string);
static string smgetwin1(Bedit *);
static string smgetwin2(Note *n);
static string smgetxywh();
static string smgetxywh1(QWidget *);
static string smopen();
static string smprompt();
static string smreplace();
static string smsave();
static string smsaveactive();
static string smsaveall();
static string smset();
static string smsetscroll(Bedit *,string);
static string smsetinputlog(string,string);
static string smsetselect(Bedit *,string);
static string smsettext(string,string);
static string smsetxywh(string,string);
// ---------------------------------------------------------------------
string sm(string c)
{
rc=0;
if (c=="act")
return smact();
if (c=="active")
return smactive();
if (c=="close")
return smclose();
if (c=="focus")
return smfocus();
if (c=="font")
return smfont();
if (c=="get")
return smget();
if (c=="new")
return smopen();
if (c=="open")
return smopen();
if (c=="replace")
return smreplace();
if (c=="save")
return smsave();
if (c=="set")
return smset();
else if (c=="prompt")
return smprompt();
cmd.getparms();
return smerror("unrecognized sm command: " + c);
}
// ---------------------------------------------------------------------
string smact()
{
cmd.getparms();
term->smact();
return"";
}
// ---------------------------------------------------------------------
string smactive()
{
string p=cmd.getparms();
QStringList opt=qsplit(p);
if (note==0 || note->editIndex()<0)
return smerror ("No active edit window");
if (opt[0]!="tab")
return smerror ("unrecognized sm command parameters: " + p);
int ndx=opt[1].toInt();
if (ndx<0 || ndx>=note->count())
return smerror ("invalid tab index: " + p);
note->setindex(ndx);
return "";
}
// ---------------------------------------------------------------------
string smclose()
{
string c=cmd.getid();
string p=cmd.getparms();
if (c=="tab") {
if (note==0 || note->editIndex()<0)
return smerror ("No active edit window");
int ndx=s2q(p).toInt();
if (ndx<0 || ndx>=note->count())
return smerror ("invalid tab index: " + p);
note->tabclose(ndx);
} else if (c=="edit") {
if (note==0)
return smerror ("No edit window");
note->close();
} else if (c=="edit2") {
if (note2==0)
return smerror ("No edit2 window");
note2->close();
} else
return smerror ("unrecognized sm command parameters: " + p);
return "";
}
// ---------------------------------------------------------------------
string smerror(string p)
{
rc=1;
return p;
}
// ---------------------------------------------------------------------
string smfocus()
{
string p=cmd.getparms();
if (p.empty())
return smerror("sm focus needs additional parameters");
if (p=="term")
term->smact();
else if (p=="edit") {
if (note==0 || note->editIndex()==-1)
return smerror("No active edit window");
note->activateWindow();
note->raise();
note->repaint();
} else if (p=="edit2") {
if (note2==0 || note2->editIndex()==-1)
return smerror("No active edit2 window");
setnote(note2);
note->activateWindow();
note->raise();
note->repaint();
} else
return smerror("unrecognized sm command: focus " + p);
return "";
}
// ---------------------------------------------------------------------
string smfont()
{
string p=cmd.getparms();
if (!p.empty()) {
Font *fnt = new Font(p);
if (fnt->error) {
delete fnt;
return smerror("unrecognized sm command: font " + p);
} else {
config.Font=fnt->font;
delete fnt;
}
}
fontset(config.Font);
return "";
}
// ---------------------------------------------------------------------
string smget()
{
string p=cmd.getparms();
if (p.size()==0)
return smerror("sm get needs additional parameters");
if (p=="active")
return smgetactive();
if (p=="term" || p=="edit" || p=="edit2")
return smgetwin(p);
if (p=="termcwh")
return smgettermcwh();
if (p=="inputlog")
return smgetinputlog();
if (p=="xywh")
return smgetxywh();
QStringList s=qsplit(p);
if (s[0]=="tabs") {
if(s.size()<=1)
return smerror("sm command requires another parameter: get tabs");
else
return smgettabs(s[1]);
}
return smerror("unrecognized sm command: get " + p);
}
// ---------------------------------------------------------------------
string smgetactive()
{
rc=-1;
return (note && ActiveWindows.indexOf(note)<ActiveWindows.indexOf(term))
? "edit" : "term";
}
// ---------------------------------------------------------------------
string smgetinputlog()
{
rc=-1;
return q2s(dlog_get());
}
// ---------------------------------------------------------------------
string smgetscript(string f)
{
return dors(">{.getscripts_j_ '" + f + "'");
}
// ---------------------------------------------------------------------
string smgettabs(QString p)
{
Note *n;
if (p=="edit") {
if (note==0)
return smerror("No active edit window");
n=note;
} else if (p=="edit2") {
if (note2==0)
return smerror("No active edit2 window");
n=note2;
} else
return smerror("sm get tabs needs edit or edit2 parameter");
rc=-2;
return n->gettabstate();
}
// ---------------------------------------------------------------------
string smgettermcwh() {
rc=-1;
QSize z=tedit->size();
QFontMetrics fm=QFontMetrics(config.Font,0);
int sb=app->style()->pixelMetric(QStyle::PM_ScrollBarExtent);
sb+=4; // padding
int fh=fm.height();
int fw=fm.width("X");
int ch=(z.height()-sb)/fh;
int cw=(z.width()-sb)/fw;
return q2s(QString::number(cw)+" "+QString::number(ch));
}
// ---------------------------------------------------------------------
string smgetwin(string p)
{
rc=-2;
if (p=="term")
return smgetwin1(tedit);
if (p=="edit") {
if (note==0)
return smerror("No active edit window");
return smgetwin2(note);
}
if (note2==0)
return smerror("No active edit2 window");
return smgetwin2(note2);
}
// ---------------------------------------------------------------------
string smgetwin1(Bedit *t)
{
string r;
if (t==0) {
r+=spair("text",(string)"");
r+=spair("select",(string)"");
} else {
QTextCursor c=t->textCursor();
int b=c.selectionStart();
int e=c.selectionEnd();
r+=spair("text",t->toPlainText());
r+=spair("select",QString::number(b)+" "+QString::number(e));
}
return r;
}
// ---------------------------------------------------------------------
string smgetwin2(Note *n)
{
if (n->editIndex()==-1)
return smgetwin1((Bedit *)0);
string r=smgetwin1((Bedit *)n->editPage());
r+=spair("file",n->editFile());
return r;
}
// ---------------------------------------------------------------------
string smgetxywh()
{
rc=-2;
string r;
r+=spair("text",smgetxywh1(term));
if (note)
r+=spair("edit",smgetxywh1(note));
if (note2)
r+=spair("edit2",smgetxywh1(note2));
return r;
}
// ---------------------------------------------------------------------
string smgetxywh1(QWidget *w)
{
QPoint p=w->pos();
QSize z=w->size();
return q2s(QString::number(p.rx())+" "+QString::number(p.ry())+" "+
QString::number(z.width())+" "+QString::number(z.height()));
}
// ---------------------------------------------------------------------
string smopen()
{
string c=cmd.getid();
string p=cmd.getparms();
if (c=="edit")
term->vieweditor();
if (c=="edit2") {
if (note==0)
return smerror("no edit window open");
note->on_winotherAct_triggered();
}
if (c=="edit" || c=="edit2")
return "";
if (c!="tab") {
return smerror("unrecognized sm command: open " + c);
}
term->vieweditor();
if (p.empty())
note->newtemp();
else {
QString f=s2q(smgetscript(p));
if (!cfexist(f))
return smerror("file not found: " + q2s(f));
note->fileopen(f);
}
rc=-1;
return i2s(note->editIndex());
}
// ---------------------------------------------------------------------
string smprompt()
{
string p=cmd.getparms();
term->smprompt(s2q(p));
return"";
}
// ---------------------------------------------------------------------
string smreplace()
{
string c=cmd.getid();
string p=cmd.getparms();
if (note==0 || note->editIndex()<0)
return smerror ("No active edit window");
if (c!="edit")
return smerror("unrecognized sm command: replace " + c);
if (p.empty())
return smerror("replace needs 2 parameters: edit filename");
QString f=s2q(smgetscript(p));
if (!cfexist(f))
return smerror("file not found: " + q2s(f));
note->filereplace(f);
return"";
}
// ---------------------------------------------------------------------
string smsave()
{
string p=cmd.getparms();
if (note==0)
return smerror("No active edit window");
if (p.empty())
return smerror("sm save parameter not given");
if (p=="edit")
return smsaveactive();
if (p=="tabs")
return smsaveall();
return smerror("sm save parameter should be 'edit' or 'tabs': " + p);
}
// ---------------------------------------------------------------------
string smsaveactive()
{
note->savecurrent();
return "";
}
// ---------------------------------------------------------------------
string smsaveall()
{
note->saveall();
return "";
}
// ---------------------------------------------------------------------
string smset()
{
string p=cmd.getid();
if (p.empty())
return smerror("sm set parameters not given");
string c=cmd.getid();
if (c.empty())
return smerror("sm set " + p + " parameters not given");
string q=cmd.getparms();
Bedit *e;
if (p=="term") {
e=tedit;
} else if (p=="edit") {
if (note==0)
return smerror("No active edit window");
e=(Bedit *)note->editPage();
} else if (p=="edit2") {
if (note2==0)
return smerror("No active edit2 window");
e=(Bedit *)note2->editPage();
} else if (p=="inputlog")
return smsetinputlog(c,q);
else
return smerror("unrecognized sm command: set " + p);
if (e==0 && (c=="scroll" || c=="select" || c=="text"))
return smerror("no edit window for sm command: set " + c);
if (p=="term" && (c=="scroll" || c=="select"))
return smerror("command applies only to an edit window: " + c);
if (c=="scroll")
return smsetscroll(e,q);
if (c=="select")
return smsetselect(e,q);
if (c=="text")
return smsettext(p,q);
if (c=="xywh")
return smsetxywh(p,q);
return smerror("unrecognized sm command: set " + p + " " + q);
}
// ---------------------------------------------------------------------
string smsetinputlog(string c,string q)
{
if (c!="text")
return smerror("unrecognized sm command: set inputlog " + c + "..." );
dlog_set(s2q(q));
return "";
}
// ---------------------------------------------------------------------
// set vertical scroll
string smsetscroll(Bedit *e, string q)
{
QList<int> s=qsl2intlist(qsplit(q));
if (s.size()!= 1)
return smerror("sm set scroll should have a single parameter of scroll size");
e->settop(s[0]);
return"";
}
// ---------------------------------------------------------------------
string smsetselect(Bedit *e, string q)
{
QList<int> s=qsl2intlist(qsplit(q));
if (s.size()!= 2)
return smerror("sm set select should have begin and end parameters");
int m=e->toPlainText().size();
if (s[1]==-1) s[1]=m;
s[1]=qMin(m,s[1]);
s[0]=qMin(s[0],s[1]);
e->setselect(s[0],s[1]-s[0]);
return"";
}
// ---------------------------------------------------------------------
string smsettext(string p,string s)
{
QString t=s2q(s);
if (p=="term")
tedit->setPlainText(t);
else if (p=="edit")
note->settext(t);
else
note2->settext(t);
return"";
}
// ---------------------------------------------------------------------
string smsetxywh(string m,string q)
{
QWidget *w;
if (m=="term")
w=term;
else if (m=="edit")
w=note;
else
w=note2;
QList<int> s=qsl2intlist(qsplit(q));
QPoint p=w->pos();
QSize z=w->size();
if (s[0]==-1) s[0]=p.rx();
if (s[1]==-1) s[1]=p.ry();
if (s[2]==-1) s[2]=z.width();
if (s[3]==-1) s[3]=z.height();
w->move(s[0],s[1]);
w->resize(s[2],s[3]);
return"";
}
<|endoftext|> |
<commit_before>#include "LLVMCodeGenerator.h"
using namespace std;
using namespace llvm;
using namespace codegen;
void LLVMCodeGenerator::visit(common::Function &Node) {
// Create function and entry block
auto Ty = getFuncType(Node.Signature);
CurFunc = llvm::Function::Create(getFuncType(Node.Signature),
llvm::Function::ExternalLinkage, Node.Id,
Module.get());
CurEntry = BasicBlock::Create(Ctx, "entry", CurFunc);
// Create error block
CurErrBlock = BasicBlock::Create(Ctx, "error", CurFunc);
Builder.SetInsertPoint(CurErrBlock);
Builder.CreateRet(UndefValue::get(CurFunc->getReturnType()));
// Setup return block and phi node
CurRetBlock = BasicBlock::Create(Ctx, "ret", CurFunc);
Builder.SetInsertPoint(CurRetBlock);
if (CurFunc->getReturnType()->getTypeID() != llvm::Type::TypeID::VoidTyID) {
CurPhiNode = Builder.CreatePHI(CurFunc->getReturnType(),
(unsigned) Node.Cases.size(), "rettmp");
// Create ret instruction
Builder.CreateRet(CurPhiNode);
} else {
Builder.CreateRetVoid();
}
// Setup names for arguments
auto ArgId = 0;
for (auto &Arg : CurFunc->args()) {
Arg.setName("_arg" + to_string(ArgId++));
Args.push_back(&Arg);
}
// Setup case and pattern blocks
CaseBlocks.clear();
PatVecBlocks.clear();
int PatId, CaseId = 0;
for (auto &Case : Node.Cases) {
PatId = 0;
auto PatVecBlock = vector<BasicBlock *>();
for (auto &Pattern : Case->Patterns) {
PatVecBlock.push_back(BasicBlock::Create(
Ctx,
"case" + to_string(CaseId) + "_pattern" + to_string(PatId++),
CurFunc));
}
PatVecBlocks.push_back(PatVecBlock);
CaseBlocks.push_back(BasicBlock::Create(
Ctx, "case" + to_string(CaseId++), CurFunc));
}
// Visit cases
for (CurCase = Node.Cases.cbegin(), CurCaseBlock = CaseBlocks.cbegin(),
LastCaseBlock = CaseBlocks.cend(),
CurPatVecBlock = PatVecBlocks.cbegin();
CurCase != Node.Cases.cend();
++CurCase, ++CurCaseBlock, ++CurPatVecBlock) {
(*CurCase)->accept(*this);
}
// Make entry point to first block
Builder.SetInsertPoint(CurEntry);
BasicBlock *FirstBlock;
if (PatVecBlocks[0].empty())
FirstBlock = CaseBlocks[0];
else
FirstBlock = PatVecBlocks[0][0];
Builder.CreateBr(FirstBlock);
verifyFunction(*CurFunc);
}
void LLVMCodeGenerator::visit(common::Case &Node) {
BasicBlock *TrueBlock;
BasicBlock *FalseBlock;
CtxVals.clear();
for (CurPat = Node.Patterns.cbegin(), CurArg = Args.cbegin(),
CurPatBlock = CurPatVecBlock->cbegin(),
LastPatBlock = CurPatVecBlock->cend();
CurPat != Node.Patterns.cend(); ++CurPat, ++CurArg, ++CurPatBlock) {
if (next(CurPatBlock) != LastPatBlock)
TrueBlock = *next(CurPatBlock);
else
TrueBlock = *CurCaseBlock;
if (next(CurCaseBlock) != LastCaseBlock)
FalseBlock = (*next(CurPatVecBlock))[0];
else
FalseBlock = CurErrBlock;
Builder.SetInsertPoint(*CurPatBlock);
(*CurPat)->accept(*this);
// Create condition
Builder.CreateCondBr(CurVal, TrueBlock, FalseBlock);
}
// Generate expression in case block
Builder.SetInsertPoint(*CurCaseBlock);
Node.Expr->accept(*this);
//auto Ty1 = CurPhiNode->getType();
//auto Ty2 = CurVal->getType();
//auto Arr1 = CurVal->getType()->getPointerElementType()->getArrayNumElements();
//auto Arr2 = CurPhiNode->getType()->getPointerElementType()->getArrayNumElements();
// Ignore expression type if function is void
if (CurFunc->getReturnType()->getTypeID() != llvm::Type::TypeID::VoidTyID)
CurPhiNode->addIncoming(CurVal, *CurCaseBlock);
// Add return value to phi node
Builder.CreateBr(CurRetBlock);
}
<commit_msg>llvm: simplify case loop<commit_after>#include "LLVMCodeGenerator.h"
using namespace std;
using namespace llvm;
using namespace codegen;
void LLVMCodeGenerator::visit(common::Function &Node) {
// Create function and entry block
auto Ty = getFuncType(Node.Signature);
CurFunc = llvm::Function::Create(getFuncType(Node.Signature),
llvm::Function::ExternalLinkage, Node.Id,
Module.get());
CurEntry = BasicBlock::Create(Ctx, "entry", CurFunc);
// Create error block
CurErrBlock = BasicBlock::Create(Ctx, "error", CurFunc);
Builder.SetInsertPoint(CurErrBlock);
Builder.CreateRet(UndefValue::get(CurFunc->getReturnType()));
// Setup return block and phi node
CurRetBlock = BasicBlock::Create(Ctx, "ret", CurFunc);
Builder.SetInsertPoint(CurRetBlock);
if (CurFunc->getReturnType()->getTypeID() != llvm::Type::TypeID::VoidTyID) {
CurPhiNode = Builder.CreatePHI(CurFunc->getReturnType(),
(unsigned) Node.Cases.size(), "rettmp");
// Create ret instruction
Builder.CreateRet(CurPhiNode);
} else {
Builder.CreateRetVoid();
}
// Setup names for arguments
auto ArgId = 0;
for (auto &Arg : CurFunc->args()) {
Arg.setName("_arg" + to_string(ArgId++));
Args.push_back(&Arg);
}
// Setup case and pattern blocks
CaseBlocks.clear();
PatVecBlocks.clear();
for (size_t i = 0; i < Node.Cases.size(); ++i) {
auto PatVecBlock = vector<BasicBlock *>();
for (size_t j = 0; j < Node.Cases[i]->Patterns.size(); ++j) {
PatVecBlock.push_back(BasicBlock::Create(
Ctx,
"case" + to_string(i) + "_pattern" + to_string(j),
CurFunc));
}
PatVecBlocks.push_back(PatVecBlock);
CaseBlocks.push_back(BasicBlock::Create(
Ctx, "case" + to_string(i), CurFunc));
}
// Visit cases
for (CurCase = Node.Cases.cbegin(), CurCaseBlock = CaseBlocks.cbegin(),
LastCaseBlock = CaseBlocks.cend(),
CurPatVecBlock = PatVecBlocks.cbegin();
CurCase != Node.Cases.cend();
++CurCase, ++CurCaseBlock, ++CurPatVecBlock) {
(*CurCase)->accept(*this);
}
// Make entry point to first block
Builder.SetInsertPoint(CurEntry);
BasicBlock *FirstBlock;
if (PatVecBlocks[0].empty())
FirstBlock = CaseBlocks[0];
else
FirstBlock = PatVecBlocks[0][0];
Builder.CreateBr(FirstBlock);
verifyFunction(*CurFunc);
}
void LLVMCodeGenerator::visit(common::Case &Node) {
BasicBlock *TrueBlock;
BasicBlock *FalseBlock;
CtxVals.clear();
for (CurPat = Node.Patterns.cbegin(), CurArg = Args.cbegin(),
CurPatBlock = CurPatVecBlock->cbegin(),
LastPatBlock = CurPatVecBlock->cend();
CurPat != Node.Patterns.cend(); ++CurPat, ++CurArg, ++CurPatBlock) {
if (next(CurPatBlock) != LastPatBlock)
TrueBlock = *next(CurPatBlock);
else
TrueBlock = *CurCaseBlock;
if (next(CurCaseBlock) != LastCaseBlock)
FalseBlock = (*next(CurPatVecBlock))[0];
else
FalseBlock = CurErrBlock;
Builder.SetInsertPoint(*CurPatBlock);
(*CurPat)->accept(*this);
// Create condition
Builder.CreateCondBr(CurVal, TrueBlock, FalseBlock);
}
// Generate expression in case block
Builder.SetInsertPoint(*CurCaseBlock);
Node.Expr->accept(*this);
//auto Ty1 = CurPhiNode->getType();
//auto Ty2 = CurVal->getType();
//auto Arr1 = CurVal->getType()->getPointerElementType()->getArrayNumElements();
//auto Arr2 = CurPhiNode->getType()->getPointerElementType()->getArrayNumElements();
// Ignore expression type if function is void
if (CurFunc->getReturnType()->getTypeID() != llvm::Type::TypeID::VoidTyID)
CurPhiNode->addIncoming(CurVal, *CurCaseBlock);
// Add return value to phi node
Builder.CreateBr(CurRetBlock);
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2018 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_vcf2fasta - write a new genome sequence
// by introducing variants from a set of vcf files
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <inttypes.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <algorithm>
#include <sstream>
#include <set>
#include <omp.h>
#include <getopt.h>
#include <fast5.hpp>
#include "htslib/faidx.h"
#include "nanopolish_common.h"
#include "nanopolish_variant.h"
#include "nanopolish_eventalign.h"
#include "nanopolish_haplotype.h"
//
// Getopt
//
#define SUBPROGRAM "vcf2fasta"
static const char *VCF2FASTA_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2018 Ontario Institute for Cancer Research\n";
static const char *VCF2FASTA_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " -g draft.fa segment1.vcf segment2.vcf ...\n"
"Write a new genome sequence by introducing variants from the input files\n"
"\n"
" -v, --verbose display verbose output\n"
" --version display version\n"
" --help display this help and exit\n"
" -g, --genome=FILE the input genome is in FILE\n"
" -f, --fofn=FILE read the list of VCF files to use from FILE\n"
" --skip-checks skip the sanity checks\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose;
static std::vector<std::string> input_vcf_files;
static std::string vcf_fofn;
static std::string genome_file;
static bool skip_checks = false;
}
static const char* shortopts = "g:f:v";
enum { OPT_HELP = 1, OPT_VERSION, OPT_SKIP_CHECKS };
static const struct option longopts[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ "skip-checks", no_argument, NULL, OPT_SKIP_CHECKS },
{ "genome", required_argument, NULL, 'g' },
{ "fofn", required_argument, NULL, 'f' },
{ NULL, 0, NULL, 0 }
};
void parse_vcf2fasta_options(int argc, char** argv)
{
bool die = false;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?': die = true; break;
case 'v': opt::verbose++; break;
case 'g': arg >> opt::genome_file; break;
case 'f': arg >> opt::vcf_fofn; break;
case OPT_SKIP_CHECKS: opt::skip_checks = true; break;
case OPT_HELP:
std::cout << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << VCF2FASTA_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
}
if(opt::genome_file.empty()) {
std::cerr << SUBPROGRAM ": -g/--genome file is required\n";
die = true;
}
if (argc - optind < 1 && opt::vcf_fofn.empty()) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
for(; optind < argc; ++optind) {
opt::input_vcf_files.push_back(argv[optind]);
}
// add files from the fofn
if(!opt::vcf_fofn.empty()) {
std::ifstream infile(opt::vcf_fofn);
std::string line;
while(getline(infile, line)) {
opt::input_vcf_files.push_back(line);
}
}
}
int vcf2fasta_main(int argc, char** argv)
{
parse_vcf2fasta_options(argc, argv);
// Read genome file
faidx_t *fai = fai_load(opt::genome_file.c_str());
// Read VCF files and gather variants for each contig and the polishing window coordinates
std::map<std::string, std::vector<Variant>> variants_by_contig;
std::map<std::string, std::vector<std::pair<int, int>>> windows_by_contig;
for(const auto& filename : opt::input_vcf_files) {
std::string window_str;
std::vector<Variant> out;
std::ifstream infile(filename);
std::string line;
while(getline(infile, line)) {
// parse header
if(line[0] == '#') {
// check for window coordinates
std::string window_key = "nanopolish_window=";
size_t key_pos = line.find(window_key);
if(key_pos != std::string::npos) {
window_str = line.substr(key_pos + window_key.size());
}
} else {
Variant v(line);
variants_by_contig[v.ref_name].push_back(v);
}
}
if(window_str.empty()) {
fprintf(stderr, "error: could not detect polishing window from input file %s\n", filename.c_str());
exit(EXIT_FAILURE);
}
std::string window_contig;
int window_start, window_end;
parse_region_string(window_str, window_contig, window_start, window_end);
windows_by_contig[window_contig].push_back(std::make_pair(window_start, window_end));
}
size_t n_contigs = faidx_nseq(fai);
for(size_t contig_idx = 0; contig_idx < n_contigs; ++contig_idx) {
std::string contig = faidx_iseq(fai, contig_idx);
int contig_length = faidx_seq_len(fai, contig.c_str());
// Confirm that all windows on this contig have been polished
bool window_check_ok = true;
auto& windows = windows_by_contig[contig];
std::sort(windows.begin(), windows.end());
if(!opt::skip_checks) {
if(windows.empty()) {
fprintf(stderr, "error: no polishing windows found for %s\n", contig.c_str());
exit(EXIT_FAILURE);
}
for(size_t window_idx = 1; window_idx < windows.size(); ++window_idx) {
int prev_start = windows[window_idx - 1].first;
int prev_end = windows[window_idx - 1].second;
int curr_start = windows[window_idx].first;
int curr_end = windows[window_idx].second;
if(curr_start > prev_end) {
fprintf(stderr, "error: adjacent polishing windows do not overlap (%d-%d and %d-%d)\n", prev_start, prev_end, curr_start, curr_end);
window_check_ok = false;
}
}
// check the first and last windows of the contig were polished
if(windows[0].first != 0) {
fprintf(stderr, "error: first %d bases are not covered by a polished window for contig %s.\n", windows[0].first, contig.c_str());
window_check_ok = false;
}
int end_gap = contig_length - windows.back().second;
if(end_gap > 500) {
fprintf(stderr, "error: last %d bases are not covered by a polished window for contig %s.\n", end_gap, contig.c_str());
window_check_ok = false;
}
}
if(!window_check_ok) {
fprintf(stderr, "error: one or more polishing windows are missing. Please check that all nanopolish variants --consensus jobs ran to completion\n");
exit(EXIT_FAILURE);
}
int length;
char* seq = fai_fetch(fai, contig.c_str(), &length);
if(length < 0) {
fprintf(stderr, "error: could not fetch contig %s\n", contig.c_str());
exit(EXIT_FAILURE);
}
auto& variants = variants_by_contig[contig];
std::sort(variants.begin(), variants.end(), sortByPosition);
// remove duplicate variants
VariantKeyEqualityComp vkec;
auto last = std::unique(variants.begin(), variants.end(), vkec);
variants.erase(last, variants.end());
assert(variants.size() < (1 << 30));
uint32_t deleted_tag = 1 << 30;
uint32_t variant_tag = 1 << 31;
// make a vector holding either a literal character or an index to the variant that needs to be applied
std::vector<uint32_t> consensus_record(length);
for(size_t i = 0; i < length; ++i) {
consensus_record[i] = seq[i];
}
size_t num_skipped = 0;
size_t num_subs = 0;
size_t num_insertions = 0;
size_t num_deletions = 0;
// update the consensus record according to the variants for this contig
size_t applied_variants = 0;
for(size_t variant_idx = 0; variant_idx < variants.size(); ++variant_idx) {
const Variant& v = variants[variant_idx];
// check if the variant record matches the reference sequence
bool matches_ref = true;
for(size_t i = 0; i < v.ref_seq.length(); ++i) {
matches_ref = matches_ref && v.ref_seq[i] == consensus_record[v.ref_position + i];
}
if(!matches_ref) {
num_skipped += 1;
continue;
}
// mark the first base of the reference sequence as a variant and set the index
consensus_record[v.ref_position] = variant_tag | variant_idx;
// mark the subsequent bases of the reference as deleted
for(size_t i = 1; i < v.ref_seq.length(); ++i) {
consensus_record[v.ref_position + i] = deleted_tag;
}
num_subs += v.ref_seq.length() == v.alt_seq.length();
num_insertions += v.ref_seq.length() < v.alt_seq.length();
num_deletions += v.ref_seq.length() > v.alt_seq.length();
}
// write out the consensus record
std::string out;
out.reserve(length);
for(size_t i = 0; i < length; ++i) {
uint32_t r = consensus_record[i];
if(r & variant_tag) {
out.append(variants[r & ~variant_tag].alt_seq);
} else if(r & ~deleted_tag) {
out.append(1, r);
} else {
assert(r & deleted_tag);
}
}
fprintf(stderr, "[vcf2fasta] rewrote contig %s with %zu subs, %zu ins, %zu dels (%zu skipped)\n", contig.c_str(), num_subs, num_insertions, num_deletions, num_skipped);
fprintf(stdout, ">%s\n%s\n", contig.c_str(), out.c_str());
free(seq);
seq = NULL;
}
return 0;
}
<commit_msg>vcf2fasta: handle lower case input genomes (#676)<commit_after>//---------------------------------------------------------
// Copyright 2018 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_vcf2fasta - write a new genome sequence
// by introducing variants from a set of vcf files
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <inttypes.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <algorithm>
#include <sstream>
#include <set>
#include <omp.h>
#include <getopt.h>
#include <fast5.hpp>
#include "htslib/faidx.h"
#include "nanopolish_common.h"
#include "nanopolish_variant.h"
#include "nanopolish_eventalign.h"
#include "nanopolish_haplotype.h"
//
// Getopt
//
#define SUBPROGRAM "vcf2fasta"
static const char *VCF2FASTA_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2018 Ontario Institute for Cancer Research\n";
static const char *VCF2FASTA_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " -g draft.fa segment1.vcf segment2.vcf ...\n"
"Write a new genome sequence by introducing variants from the input files\n"
"\n"
" -v, --verbose display verbose output\n"
" --version display version\n"
" --help display this help and exit\n"
" -g, --genome=FILE the input genome is in FILE\n"
" -f, --fofn=FILE read the list of VCF files to use from FILE\n"
" --skip-checks skip the sanity checks\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose;
static std::vector<std::string> input_vcf_files;
static std::string vcf_fofn;
static std::string genome_file;
static bool skip_checks = false;
}
static const char* shortopts = "g:f:v";
enum { OPT_HELP = 1, OPT_VERSION, OPT_SKIP_CHECKS };
static const struct option longopts[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ "skip-checks", no_argument, NULL, OPT_SKIP_CHECKS },
{ "genome", required_argument, NULL, 'g' },
{ "fofn", required_argument, NULL, 'f' },
{ NULL, 0, NULL, 0 }
};
void parse_vcf2fasta_options(int argc, char** argv)
{
bool die = false;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?': die = true; break;
case 'v': opt::verbose++; break;
case 'g': arg >> opt::genome_file; break;
case 'f': arg >> opt::vcf_fofn; break;
case OPT_SKIP_CHECKS: opt::skip_checks = true; break;
case OPT_HELP:
std::cout << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << VCF2FASTA_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
}
if(opt::genome_file.empty()) {
std::cerr << SUBPROGRAM ": -g/--genome file is required\n";
die = true;
}
if (argc - optind < 1 && opt::vcf_fofn.empty()) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
for(; optind < argc; ++optind) {
opt::input_vcf_files.push_back(argv[optind]);
}
// add files from the fofn
if(!opt::vcf_fofn.empty()) {
std::ifstream infile(opt::vcf_fofn);
std::string line;
while(getline(infile, line)) {
opt::input_vcf_files.push_back(line);
}
}
}
int vcf2fasta_main(int argc, char** argv)
{
parse_vcf2fasta_options(argc, argv);
// Read genome file
faidx_t *fai = fai_load(opt::genome_file.c_str());
// Read VCF files and gather variants for each contig and the polishing window coordinates
std::map<std::string, std::vector<Variant>> variants_by_contig;
std::map<std::string, std::vector<std::pair<int, int>>> windows_by_contig;
for(const auto& filename : opt::input_vcf_files) {
std::string window_str;
std::vector<Variant> out;
std::ifstream infile(filename);
std::string line;
while(getline(infile, line)) {
// parse header
if(line[0] == '#') {
// check for window coordinates
std::string window_key = "nanopolish_window=";
size_t key_pos = line.find(window_key);
if(key_pos != std::string::npos) {
window_str = line.substr(key_pos + window_key.size());
}
} else {
Variant v(line);
variants_by_contig[v.ref_name].push_back(v);
}
}
if(window_str.empty()) {
fprintf(stderr, "error: could not detect polishing window from input file %s\n", filename.c_str());
exit(EXIT_FAILURE);
}
std::string window_contig;
int window_start, window_end;
parse_region_string(window_str, window_contig, window_start, window_end);
windows_by_contig[window_contig].push_back(std::make_pair(window_start, window_end));
}
size_t n_contigs = faidx_nseq(fai);
for(size_t contig_idx = 0; contig_idx < n_contigs; ++contig_idx) {
std::string contig = faidx_iseq(fai, contig_idx);
int contig_length = faidx_seq_len(fai, contig.c_str());
// Confirm that all windows on this contig have been polished
bool window_check_ok = true;
auto& windows = windows_by_contig[contig];
std::sort(windows.begin(), windows.end());
if(!opt::skip_checks) {
if(windows.empty()) {
fprintf(stderr, "error: no polishing windows found for %s\n", contig.c_str());
exit(EXIT_FAILURE);
}
for(size_t window_idx = 1; window_idx < windows.size(); ++window_idx) {
int prev_start = windows[window_idx - 1].first;
int prev_end = windows[window_idx - 1].second;
int curr_start = windows[window_idx].first;
int curr_end = windows[window_idx].second;
if(curr_start > prev_end) {
fprintf(stderr, "error: adjacent polishing windows do not overlap (%d-%d and %d-%d)\n", prev_start, prev_end, curr_start, curr_end);
window_check_ok = false;
}
}
// check the first and last windows of the contig were polished
if(windows[0].first != 0) {
fprintf(stderr, "error: first %d bases are not covered by a polished window for contig %s.\n", windows[0].first, contig.c_str());
window_check_ok = false;
}
int end_gap = contig_length - windows.back().second;
if(end_gap > 500) {
fprintf(stderr, "error: last %d bases are not covered by a polished window for contig %s.\n", end_gap, contig.c_str());
window_check_ok = false;
}
}
if(!window_check_ok) {
fprintf(stderr, "error: one or more polishing windows are missing. Please check that all nanopolish variants --consensus jobs ran to completion\n");
exit(EXIT_FAILURE);
}
int length;
char* seq = fai_fetch(fai, contig.c_str(), &length);
if(length < 0) {
fprintf(stderr, "error: could not fetch contig %s\n", contig.c_str());
exit(EXIT_FAILURE);
}
auto& variants = variants_by_contig[contig];
std::sort(variants.begin(), variants.end(), sortByPosition);
// remove duplicate variants
VariantKeyEqualityComp vkec;
auto last = std::unique(variants.begin(), variants.end(), vkec);
variants.erase(last, variants.end());
assert(variants.size() < (1 << 30));
uint32_t deleted_tag = 1 << 30;
uint32_t variant_tag = 1 << 31;
// make a vector holding either a literal character or an index to the variant that needs to be applied
std::vector<uint32_t> consensus_record(length);
for(size_t i = 0; i < length; ++i) {
consensus_record[i] = toupper(seq[i]);
}
size_t num_skipped = 0;
size_t num_subs = 0;
size_t num_insertions = 0;
size_t num_deletions = 0;
// update the consensus record according to the variants for this contig
size_t applied_variants = 0;
for(size_t variant_idx = 0; variant_idx < variants.size(); ++variant_idx) {
const Variant& v = variants[variant_idx];
// check if the variant record matches the reference sequence
bool matches_ref = true;
for(size_t i = 0; i < v.ref_seq.length(); ++i) {
matches_ref = matches_ref && v.ref_seq[i] == consensus_record[v.ref_position + i];
}
if(!matches_ref) {
num_skipped += 1;
continue;
}
// mark the first base of the reference sequence as a variant and set the index
consensus_record[v.ref_position] = variant_tag | variant_idx;
// mark the subsequent bases of the reference as deleted
for(size_t i = 1; i < v.ref_seq.length(); ++i) {
consensus_record[v.ref_position + i] = deleted_tag;
}
num_subs += v.ref_seq.length() == v.alt_seq.length();
num_insertions += v.ref_seq.length() < v.alt_seq.length();
num_deletions += v.ref_seq.length() > v.alt_seq.length();
}
// write out the consensus record
std::string out;
out.reserve(length);
for(size_t i = 0; i < length; ++i) {
uint32_t r = consensus_record[i];
if(r & variant_tag) {
out.append(variants[r & ~variant_tag].alt_seq);
} else if(r & ~deleted_tag) {
out.append(1, r);
} else {
assert(r & deleted_tag);
}
}
fprintf(stderr, "[vcf2fasta] rewrote contig %s with %zu subs, %zu ins, %zu dels (%zu skipped)\n", contig.c_str(), num_subs, num_insertions, num_deletions, num_skipped);
fprintf(stdout, ">%s\n%s\n", contig.c_str(), out.c_str());
free(seq);
seq = NULL;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: zoomctrl.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 17:14:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _ZOOMCTRL_HXX
#define _ZOOMCTRL_HXX
#ifndef _SVX_ZOOMCTRL_HXX //autogen
#include <svx/zoomctrl.hxx>
#endif
class SwZoomControl : public SvxZoomStatusBarControl
{
private:
String sPreviewZoom;
public:
virtual void Command( const CommandEvent& rCEvt );
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
virtual void Paint( const UserDrawEvent& rEvt );
SFX_DECL_STATUSBAR_CONTROL();
SwZoomControl( USHORT nId, StatusBar& rStb, SfxBindings& rBind );
~SwZoomControl();
};
#endif
<commit_msg>INTEGRATION: CWS toolbars2 (1.1.1.1.836); FILE MERGED 2004/08/11 10:47:33 cd 1.1.1.1.836.1: #i32219# Adapt statusbar controller to new base class<commit_after>/*************************************************************************
*
* $RCSfile: zoomctrl.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-09-09 15:35:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _ZOOMCTRL_HXX
#define _ZOOMCTRL_HXX
#ifndef _SVX_ZOOMCTRL_HXX //autogen
#include <svx/zoomctrl.hxx>
#endif
class SwZoomControl : public SvxZoomStatusBarControl
{
private:
String sPreviewZoom;
public:
virtual void Command( const CommandEvent& rCEvt );
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
virtual void Paint( const UserDrawEvent& rEvt );
SFX_DECL_STATUSBAR_CONTROL();
SwZoomControl( USHORT nSlotId, USHORT nId, StatusBar& rStb );
~SwZoomControl();
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: generictoolboxcontroller.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2007-09-05 17:39:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef __SVTOOLS_GENERICTOOLBOXCONTROLLER_HXX_
#include <svtools/generictoolboxcontroller.hxx>
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;
namespace svt
{
struct ExecuteInfo
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::util::URL aTargetURL;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
};
GenericToolboxController::GenericToolboxController( const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBox* pToolbox,
USHORT nID,
const ::rtl::OUString& aCommand ) :
svt::ToolboxController( rServiceManager, rFrame, aCommand )
, m_pToolbox( pToolbox )
, m_nID( nID )
{
// Initialization is done through ctor
m_bInitialized = sal_True;
// insert main command to our listener map
if ( m_aCommandURL.getLength() )
m_aListenerMap.insert( URLToDispatchMap::value_type( aCommand, Reference< XDispatch >() ));
}
GenericToolboxController::~GenericToolboxController()
{
}
void SAL_CALL GenericToolboxController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
svt::ToolboxController::dispose();
m_pToolbox = 0;
m_nID = 0;
}
void SAL_CALL GenericToolboxController::execute( sal_Int16 /*KeyModifier*/ )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
::rtl::OUString aCommandURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
aCommandURL = m_aCommandURL;
URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL );
if ( pIter != m_aListenerMap.end() )
xDispatch = pIter->second;
}
}
if ( xDispatch.is() && xURLTransformer.is() )
{
com::sun::star::util::URL aTargetURL;
Sequence<PropertyValue> aArgs;
aTargetURL.Complete = aCommandURL;
xURLTransformer->parseStrict( aTargetURL );
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, GenericToolboxController , ExecuteHdl_Impl), pExecuteInfo );
}
}
void GenericToolboxController::statusChanged( const FeatureStateEvent& Event )
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
return;
if ( m_pToolbox )
{
m_pToolbox->EnableItem( m_nID, Event.IsEnabled );
USHORT nItemBits = m_pToolbox->GetItemBits( m_nID );
nItemBits &= ~TIB_CHECKABLE;
TriState eTri = STATE_NOCHECK;
sal_Bool bValue = sal_Bool();
rtl::OUString aStrValue;
ItemStatus aItemState;
if ( Event.State >>= bValue )
{
// Boolean, treat it as checked/unchecked
m_pToolbox->SetItemBits( m_nID, nItemBits );
m_pToolbox->CheckItem( m_nID, bValue );
if ( bValue )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else if ( Event.State >>= aStrValue )
{
m_pToolbox->SetItemText( m_nID, aStrValue );
}
else if ( Event.State >>= aItemState )
{
eTri = STATE_DONTKNOW;
nItemBits |= TIB_CHECKABLE;
}
m_pToolbox->SetItemState( m_nID, eTri );
m_pToolbox->SetItemBits( m_nID, nItemBits );
}
}
IMPL_STATIC_LINK_NOINSTANCE( GenericToolboxController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
try
{
// Asynchronous execution as this can lead to our own destruction!
// Framework can recycle our current frame and the layout manager disposes all user interface
// elements if a component gets detached from its frame!
pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
}
catch ( Exception& )
{
}
delete pExecuteInfo;
return 0;
}
} // namespace
<commit_msg>INTEGRATION: CWS changefileheader (1.8.170); FILE MERGED 2008/04/01 15:45:31 thb 1.8.170.3: #i85898# Stripping all external header guards 2008/04/01 12:43:57 thb 1.8.170.2: #i85898# Stripping all external header guards 2008/03/31 13:02:37 rt 1.8.170.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: generictoolboxcontroller.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <svtools/generictoolboxcontroller.hxx>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/XDispatchProvider.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/frame/status/ItemStatus.hpp>
#include <com/sun/star/frame/status/ItemState.hpp>
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;
namespace svt
{
struct ExecuteInfo
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::util::URL aTargetURL;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
};
GenericToolboxController::GenericToolboxController( const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBox* pToolbox,
USHORT nID,
const ::rtl::OUString& aCommand ) :
svt::ToolboxController( rServiceManager, rFrame, aCommand )
, m_pToolbox( pToolbox )
, m_nID( nID )
{
// Initialization is done through ctor
m_bInitialized = sal_True;
// insert main command to our listener map
if ( m_aCommandURL.getLength() )
m_aListenerMap.insert( URLToDispatchMap::value_type( aCommand, Reference< XDispatch >() ));
}
GenericToolboxController::~GenericToolboxController()
{
}
void SAL_CALL GenericToolboxController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
svt::ToolboxController::dispose();
m_pToolbox = 0;
m_nID = 0;
}
void SAL_CALL GenericToolboxController::execute( sal_Int16 /*KeyModifier*/ )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
::rtl::OUString aCommandURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
aCommandURL = m_aCommandURL;
URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL );
if ( pIter != m_aListenerMap.end() )
xDispatch = pIter->second;
}
}
if ( xDispatch.is() && xURLTransformer.is() )
{
com::sun::star::util::URL aTargetURL;
Sequence<PropertyValue> aArgs;
aTargetURL.Complete = aCommandURL;
xURLTransformer->parseStrict( aTargetURL );
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, GenericToolboxController , ExecuteHdl_Impl), pExecuteInfo );
}
}
void GenericToolboxController::statusChanged( const FeatureStateEvent& Event )
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
return;
if ( m_pToolbox )
{
m_pToolbox->EnableItem( m_nID, Event.IsEnabled );
USHORT nItemBits = m_pToolbox->GetItemBits( m_nID );
nItemBits &= ~TIB_CHECKABLE;
TriState eTri = STATE_NOCHECK;
sal_Bool bValue = sal_Bool();
rtl::OUString aStrValue;
ItemStatus aItemState;
if ( Event.State >>= bValue )
{
// Boolean, treat it as checked/unchecked
m_pToolbox->SetItemBits( m_nID, nItemBits );
m_pToolbox->CheckItem( m_nID, bValue );
if ( bValue )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else if ( Event.State >>= aStrValue )
{
m_pToolbox->SetItemText( m_nID, aStrValue );
}
else if ( Event.State >>= aItemState )
{
eTri = STATE_DONTKNOW;
nItemBits |= TIB_CHECKABLE;
}
m_pToolbox->SetItemState( m_nID, eTri );
m_pToolbox->SetItemBits( m_nID, nItemBits );
}
}
IMPL_STATIC_LINK_NOINSTANCE( GenericToolboxController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
try
{
// Asynchronous execution as this can lead to our own destruction!
// Framework can recycle our current frame and the layout manager disposes all user interface
// elements if a component gets detached from its frame!
pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
}
catch ( Exception& )
{
}
delete pExecuteInfo;
return 0;
}
} // namespace
<|endoftext|> |
<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Arc-standard transition system.
//
// This transition system has three types of actions:
// - The SHIFT action pushes the next input token to the stack and
// advances to the next input token.
// - The LEFT_ARC action adds a dependency relation from first to second token
// on the stack and removes second one.
// - The RIGHT_ARC action adds a dependency relation from second to first token
// on the stack and removes the first one.
//
// The transition system operates with parser actions encoded as integers:
// - A SHIFT action is encoded as 0.
// - A LEFT_ARC action is encoded as an odd number starting from 1.
// - A RIGHT_ARC action is encoded as an even number starting from 2.
#include <string>
#include "syntaxnet/parser_state.h"
#include "syntaxnet/parser_transitions.h"
#include "syntaxnet/utils.h"
#include "tensorflow/core/lib/strings/strcat.h"
namespace syntaxnet {
class ArcStandardTransitionState : public ParserTransitionState {
public:
// Clones the transition state by returning a new object.
ParserTransitionState *Clone() const override {
return new ArcStandardTransitionState();
}
// Pushes the root on the stack before using the parser state in parsing.
void Init(ParserState *state) override { state->Push(-1); }
// Adds transition state specific annotations to the document.
void AddParseToDocument(const ParserState &state, bool rewrite_root_labels,
Sentence *sentence) const override {
for (int i = 0; i < state.NumTokens(); ++i) {
Token *token = sentence->mutable_token(i);
token->set_label(state.LabelAsString(state.Label(i)));
if (state.Head(i) != -1) {
token->set_head(state.Head(i));
} else {
token->clear_head();
if (rewrite_root_labels) {
token->set_label(state.LabelAsString(state.RootLabel()));
}
}
}
}
// Whether a parsed token should be considered correct for evaluation.
bool IsTokenCorrect(const ParserState &state, int index) const override {
return state.GoldHead(index) == state.Head(index);
}
// Returns a human readable string representation of this state.
string ToString(const ParserState &state) const override {
string str;
str.append("[");
for (int i = state.StackSize() - 1; i >= 0; --i) {
const string &word = state.GetToken(state.Stack(i)).word();
if (i != state.StackSize() - 1) str.append(" ");
if (word == "") {
str.append(ParserState::kRootLabel);
} else {
str.append(word);
}
}
str.append("]");
for (int i = state.Next(); i < state.NumTokens(); ++i) {
tensorflow::strings::StrAppend(&str, " ", state.GetToken(i).word());
}
return str;
}
};
class ArcStandardTransitionSystem : public ParserTransitionSystem {
public:
// Action types for the arc-standard transition system.
enum ParserActionType {
SHIFT = 0,
LEFT_ARC = 1,
RIGHT_ARC = 2,
};
// The SHIFT action uses the same value as the corresponding action type.
static ParserAction ShiftAction() { return SHIFT; }
// The LEFT_ARC action converts the label to an odd number greater or equal
// to 1.
static ParserAction LeftArcAction(int label) { return 1 + (label << 1); }
// The RIGHT_ARC action converts the label to an even number greater or equal
// to 2.
static ParserAction RightArcAction(int label) {
return 1 + ((label << 1) | 1);
}
// Extracts the action type from a given parser action.
static ParserActionType ActionType(ParserAction action) {
return static_cast<ParserActionType>(action < 1 ? action
: 1 + (~action & 1));
}
// Extracts the label from a given parser action. If the action is SHIFT,
// returns -1.
static int Label(ParserAction action) {
return action < 1 ? -1 : (action - 1) >> 1;
}
// Returns the number of action types.
int NumActionTypes() const override { return 3; }
// Returns the number of possible actions.
int NumActions(int num_labels) const override { return 1 + 2 * num_labels; }
// The method returns the default action for a given state.
ParserAction GetDefaultAction(const ParserState &state) const override {
// If there are further tokens available in the input then Shift.
if (!state.EndOfInput()) return ShiftAction();
// Do a "reduce".
return RightArcAction(2);
}
// Returns the next gold action for a given state according to the
// underlying annotated sentence.
ParserAction GetNextGoldAction(const ParserState &state) const override {
// If the stack contains less than 2 tokens, the only valid parser action is
// shift.
if (state.StackSize() < 2) {
// It is illegal to request the gold action if the transition system is
// in a terminal state.
CHECK(!state.EndOfInput());
VLOG(2) << "Gold action: SHIFT (stack < 2 tokens)";
return ShiftAction();
}
// If the second token on the stack is the head of the first one,
// return a right arc action.
if (state.GoldHead(state.Stack(0)) == state.Stack(1) &&
DoneChildrenRightOf(state, state.Stack(0))) {
const int gold_label = state.GoldLabel(state.Stack(0));
VLOG(2) << "Gold action: RIGHT_ARC, label:" << gold_label;
return RightArcAction(gold_label);
}
// If the first token on the stack is the head of the second one,
// return a left arc action.
if (state.GoldHead(state.Stack(1)) == state.Top()) {
const int gold_label = state.GoldLabel(state.Stack(1));
VLOG(2) << "Gold action: LEFT_ARC, label:" << gold_label;
return LeftArcAction(gold_label);
}
// Otherwise, shift.
VLOG(2) << "Gold action: SHIFT (default)";
return ShiftAction();
}
// Determines if a token has any children to the right in the sentence.
// Arc standard is a bottom-up parsing method and has to finish all sub-trees
// first.
static bool DoneChildrenRightOf(const ParserState &state, int head) {
int index = state.Next();
int num_tokens = state.sentence().token_size();
while (index < num_tokens) {
// Check if the token at index is the child of head.
int actual_head = state.GoldHead(index);
if (actual_head == head) return false;
// If the head of the token at index is to the right of it there cannot be
// any children in-between, so we can skip forward to the head. Note this
// is only true for projective trees.
if (actual_head > index) {
index = actual_head;
} else {
++index;
}
}
return true;
}
// Checks if the action is allowed in a given parser state.
bool IsAllowedAction(ParserAction action,
const ParserState &state) const override {
switch (ActionType(action)) {
case SHIFT:
return IsAllowedShift(state);
case LEFT_ARC:
return IsAllowedLeftArc(state);
case RIGHT_ARC:
return IsAllowedRightArc(state);
}
return false;
}
// Returns true if a shift is allowed in the given parser state.
bool IsAllowedShift(const ParserState &state) const {
// We can shift if there are more input tokens.
return !state.EndOfInput();
}
// Returns true if a left-arc is allowed in the given parser state.
bool IsAllowedLeftArc(const ParserState &state) const {
// Left-arc requires two or more tokens on the stack but the first token
// is the root an we do not want and left arc to the root.
return state.StackSize() > 2;
}
// Returns true if a right-arc is allowed in the given parser state.
bool IsAllowedRightArc(const ParserState &state) const {
// Right arc requires three or more tokens on the stack.
return state.StackSize() > 1;
}
// Performs the specified action on a given parser state, without adding the
// action to the state's history.
void PerformActionWithoutHistory(ParserAction action,
ParserState *state) const override {
switch (ActionType(action)) {
case SHIFT:
PerformShift(state);
break;
case LEFT_ARC:
PerformLeftArc(state, Label(action));
break;
case RIGHT_ARC:
PerformRightArc(state, Label(action));
break;
}
}
// Makes a shift by pushing the next input token on the stack and moving to
// the next position.
void PerformShift(ParserState *state) const {
DCHECK(IsAllowedShift(*state));
state->Push(state->Next());
state->Advance();
}
// Makes a left-arc between the two top tokens on stack and pops the second
// token on stack.
void PerformLeftArc(ParserState *state, int label) const {
DCHECK(IsAllowedLeftArc(*state));
int s0 = state->Pop();
state->AddArc(state->Pop(), s0, label);
state->Push(s0);
}
// Makes a right-arc between the two top tokens on stack and pops the stack.
void PerformRightArc(ParserState *state, int label) const {
DCHECK(IsAllowedRightArc(*state));
int s0 = state->Pop();
int s1 = state->Pop();
state->AddArc(s0, s1, label);
state->Push(s1);
}
// We are in a deterministic state when we either reached the end of the input
// or reduced everything from the stack.
bool IsDeterministicState(const ParserState &state) const override {
return state.StackSize() < 2 && !state.EndOfInput();
}
// We are in a final state when we reached the end of the input and the stack
// is empty.
bool IsFinalState(const ParserState &state) const override {
VLOG(2) << "Final state check: EOI: " << state.EndOfInput()
<< " Stack size: " << state.StackSize();
return state.EndOfInput() && state.StackSize() < 2;
}
// Returns a string representation of a parser action.
string ActionAsString(ParserAction action,
const ParserState &state) const override {
switch (ActionType(action)) {
case SHIFT:
return "SHIFT";
case LEFT_ARC:
return "LEFT_ARC(" + state.LabelAsString(Label(action)) + ")";
case RIGHT_ARC:
return "RIGHT_ARC(" + state.LabelAsString(Label(action)) + ")";
}
return "UNKNOWN";
}
// Returns a new transition state to be used to enhance the parser state.
ParserTransitionState *NewTransitionState(bool training_mode) const override {
return new ArcStandardTransitionState();
}
// Meta information API. Returns token indices to link parser actions back
// to positions in the input sentence.
bool SupportsActionMetaData() const override { return true; }
// Returns the child of a new arc for reduce actions.
int ChildIndex(const ParserState &state,
const ParserAction &action) const override {
switch (ActionType(action)) {
case SHIFT:
return -1;
case LEFT_ARC: // left arc pops stack(1)
return state.Stack(1);
case RIGHT_ARC:
return state.Stack(0);
default:
LOG(FATAL) << "Invalid parser action: " << action;
}
}
// Returns the parent of a new arc for reduce actions.
int ParentIndex(const ParserState &state,
const ParserAction &action) const override {
switch (ActionType(action)) {
case SHIFT:
return -1;
case LEFT_ARC: // left arc pops stack(1)
return state.Stack(0);
case RIGHT_ARC:
return state.Stack(1);
default:
LOG(FATAL) << "Invalid parser action: " << action;
}
}
};
REGISTER_TRANSITION_SYSTEM("arc-standard", ArcStandardTransitionSystem);
} // namespace syntaxnet
<commit_msg>improved ArcStandardTransitionSystem.PerformRightArc()<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Arc-standard transition system.
//
// This transition system has three types of actions:
// - The SHIFT action pushes the next input token to the stack and
// advances to the next input token.
// - The LEFT_ARC action adds a dependency relation from first to second token
// on the stack and removes second one.
// - The RIGHT_ARC action adds a dependency relation from second to first token
// on the stack and removes the first one.
//
// The transition system operates with parser actions encoded as integers:
// - A SHIFT action is encoded as 0.
// - A LEFT_ARC action is encoded as an odd number starting from 1.
// - A RIGHT_ARC action is encoded as an even number starting from 2.
#include <string>
#include "syntaxnet/parser_state.h"
#include "syntaxnet/parser_transitions.h"
#include "syntaxnet/utils.h"
#include "tensorflow/core/lib/strings/strcat.h"
namespace syntaxnet {
class ArcStandardTransitionState : public ParserTransitionState {
public:
// Clones the transition state by returning a new object.
ParserTransitionState *Clone() const override {
return new ArcStandardTransitionState();
}
// Pushes the root on the stack before using the parser state in parsing.
void Init(ParserState *state) override { state->Push(-1); }
// Adds transition state specific annotations to the document.
void AddParseToDocument(const ParserState &state, bool rewrite_root_labels,
Sentence *sentence) const override {
for (int i = 0; i < state.NumTokens(); ++i) {
Token *token = sentence->mutable_token(i);
token->set_label(state.LabelAsString(state.Label(i)));
if (state.Head(i) != -1) {
token->set_head(state.Head(i));
} else {
token->clear_head();
if (rewrite_root_labels) {
token->set_label(state.LabelAsString(state.RootLabel()));
}
}
}
}
// Whether a parsed token should be considered correct for evaluation.
bool IsTokenCorrect(const ParserState &state, int index) const override {
return state.GoldHead(index) == state.Head(index);
}
// Returns a human readable string representation of this state.
string ToString(const ParserState &state) const override {
string str;
str.append("[");
for (int i = state.StackSize() - 1; i >= 0; --i) {
const string &word = state.GetToken(state.Stack(i)).word();
if (i != state.StackSize() - 1) str.append(" ");
if (word == "") {
str.append(ParserState::kRootLabel);
} else {
str.append(word);
}
}
str.append("]");
for (int i = state.Next(); i < state.NumTokens(); ++i) {
tensorflow::strings::StrAppend(&str, " ", state.GetToken(i).word());
}
return str;
}
};
class ArcStandardTransitionSystem : public ParserTransitionSystem {
public:
// Action types for the arc-standard transition system.
enum ParserActionType {
SHIFT = 0,
LEFT_ARC = 1,
RIGHT_ARC = 2,
};
// The SHIFT action uses the same value as the corresponding action type.
static ParserAction ShiftAction() { return SHIFT; }
// The LEFT_ARC action converts the label to an odd number greater or equal
// to 1.
static ParserAction LeftArcAction(int label) { return 1 + (label << 1); }
// The RIGHT_ARC action converts the label to an even number greater or equal
// to 2.
static ParserAction RightArcAction(int label) {
return 1 + ((label << 1) | 1);
}
// Extracts the action type from a given parser action.
static ParserActionType ActionType(ParserAction action) {
return static_cast<ParserActionType>(action < 1 ? action
: 1 + (~action & 1));
}
// Extracts the label from a given parser action. If the action is SHIFT,
// returns -1.
static int Label(ParserAction action) {
return action < 1 ? -1 : (action - 1) >> 1;
}
// Returns the number of action types.
int NumActionTypes() const override { return 3; }
// Returns the number of possible actions.
int NumActions(int num_labels) const override { return 1 + 2 * num_labels; }
// The method returns the default action for a given state.
ParserAction GetDefaultAction(const ParserState &state) const override {
// If there are further tokens available in the input then Shift.
if (!state.EndOfInput()) return ShiftAction();
// Do a "reduce".
return RightArcAction(2);
}
// Returns the next gold action for a given state according to the
// underlying annotated sentence.
ParserAction GetNextGoldAction(const ParserState &state) const override {
// If the stack contains less than 2 tokens, the only valid parser action is
// shift.
if (state.StackSize() < 2) {
// It is illegal to request the gold action if the transition system is
// in a terminal state.
CHECK(!state.EndOfInput());
VLOG(2) << "Gold action: SHIFT (stack < 2 tokens)";
return ShiftAction();
}
// If the second token on the stack is the head of the first one,
// return a right arc action.
if (state.GoldHead(state.Stack(0)) == state.Stack(1) &&
DoneChildrenRightOf(state, state.Stack(0))) {
const int gold_label = state.GoldLabel(state.Stack(0));
VLOG(2) << "Gold action: RIGHT_ARC, label:" << gold_label;
return RightArcAction(gold_label);
}
// If the first token on the stack is the head of the second one,
// return a left arc action.
if (state.GoldHead(state.Stack(1)) == state.Top()) {
const int gold_label = state.GoldLabel(state.Stack(1));
VLOG(2) << "Gold action: LEFT_ARC, label:" << gold_label;
return LeftArcAction(gold_label);
}
// Otherwise, shift.
VLOG(2) << "Gold action: SHIFT (default)";
return ShiftAction();
}
// Determines if a token has any children to the right in the sentence.
// Arc standard is a bottom-up parsing method and has to finish all sub-trees
// first.
static bool DoneChildrenRightOf(const ParserState &state, int head) {
int index = state.Next();
int num_tokens = state.sentence().token_size();
while (index < num_tokens) {
// Check if the token at index is the child of head.
int actual_head = state.GoldHead(index);
if (actual_head == head) return false;
// If the head of the token at index is to the right of it there cannot be
// any children in-between, so we can skip forward to the head. Note this
// is only true for projective trees.
if (actual_head > index) {
index = actual_head;
} else {
++index;
}
}
return true;
}
// Checks if the action is allowed in a given parser state.
bool IsAllowedAction(ParserAction action,
const ParserState &state) const override {
switch (ActionType(action)) {
case SHIFT:
return IsAllowedShift(state);
case LEFT_ARC:
return IsAllowedLeftArc(state);
case RIGHT_ARC:
return IsAllowedRightArc(state);
}
return false;
}
// Returns true if a shift is allowed in the given parser state.
bool IsAllowedShift(const ParserState &state) const {
// We can shift if there are more input tokens.
return !state.EndOfInput();
}
// Returns true if a left-arc is allowed in the given parser state.
bool IsAllowedLeftArc(const ParserState &state) const {
// Left-arc requires two or more tokens on the stack but the first token
// is the root an we do not want and left arc to the root.
return state.StackSize() > 2;
}
// Returns true if a right-arc is allowed in the given parser state.
bool IsAllowedRightArc(const ParserState &state) const {
// Right arc requires three or more tokens on the stack.
return state.StackSize() > 1;
}
// Performs the specified action on a given parser state, without adding the
// action to the state's history.
void PerformActionWithoutHistory(ParserAction action,
ParserState *state) const override {
switch (ActionType(action)) {
case SHIFT:
PerformShift(state);
break;
case LEFT_ARC:
PerformLeftArc(state, Label(action));
break;
case RIGHT_ARC:
PerformRightArc(state, Label(action));
break;
}
}
// Makes a shift by pushing the next input token on the stack and moving to
// the next position.
void PerformShift(ParserState *state) const {
DCHECK(IsAllowedShift(*state));
state->Push(state->Next());
state->Advance();
}
// Makes a left-arc between the two top tokens on stack and pops the second
// token on stack.
void PerformLeftArc(ParserState *state, int label) const {
DCHECK(IsAllowedLeftArc(*state));
int s0 = state->Pop();
state->AddArc(state->Pop(), s0, label);
state->Push(s0);
}
// Makes a right-arc between the two top tokens on stack and pops the stack.
void PerformRightArc(ParserState *state, int label) const {
DCHECK(IsAllowedRightArc(*state));
int s0 = state->Pop();
state->AddArc(s0, state->Top(), label);
}
// We are in a deterministic state when we either reached the end of the input
// or reduced everything from the stack.
bool IsDeterministicState(const ParserState &state) const override {
return state.StackSize() < 2 && !state.EndOfInput();
}
// We are in a final state when we reached the end of the input and the stack
// is empty.
bool IsFinalState(const ParserState &state) const override {
VLOG(2) << "Final state check: EOI: " << state.EndOfInput()
<< " Stack size: " << state.StackSize();
return state.EndOfInput() && state.StackSize() < 2;
}
// Returns a string representation of a parser action.
string ActionAsString(ParserAction action,
const ParserState &state) const override {
switch (ActionType(action)) {
case SHIFT:
return "SHIFT";
case LEFT_ARC:
return "LEFT_ARC(" + state.LabelAsString(Label(action)) + ")";
case RIGHT_ARC:
return "RIGHT_ARC(" + state.LabelAsString(Label(action)) + ")";
}
return "UNKNOWN";
}
// Returns a new transition state to be used to enhance the parser state.
ParserTransitionState *NewTransitionState(bool training_mode) const override {
return new ArcStandardTransitionState();
}
// Meta information API. Returns token indices to link parser actions back
// to positions in the input sentence.
bool SupportsActionMetaData() const override { return true; }
// Returns the child of a new arc for reduce actions.
int ChildIndex(const ParserState &state,
const ParserAction &action) const override {
switch (ActionType(action)) {
case SHIFT:
return -1;
case LEFT_ARC: // left arc pops stack(1)
return state.Stack(1);
case RIGHT_ARC:
return state.Stack(0);
default:
LOG(FATAL) << "Invalid parser action: " << action;
}
}
// Returns the parent of a new arc for reduce actions.
int ParentIndex(const ParserState &state,
const ParserAction &action) const override {
switch (ActionType(action)) {
case SHIFT:
return -1;
case LEFT_ARC: // left arc pops stack(1)
return state.Stack(0);
case RIGHT_ARC:
return state.Stack(1);
default:
LOG(FATAL) << "Invalid parser action: " << action;
}
}
};
REGISTER_TRANSITION_SYSTEM("arc-standard", ArcStandardTransitionSystem);
} // namespace syntaxnet
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifdef TENSORFLOW_USE_VERBS
#include "tensorflow/contrib/verbs/rdma_rendezvous_mgr.h"
#include <unordered_set>
#include "tensorflow/contrib/verbs/verbs_util.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/common_runtime/gpu/process_state.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace tensorflow {
class RdmaRemoteRendezvous : public BaseRemoteRendezvous {
public:
RdmaRemoteRendezvous(const WorkerEnv* env, int64 step_id, RdmaMgr* rdma_mgr)
: BaseRemoteRendezvous(env, step_id, true), rdma_mgr_(rdma_mgr) {}
protected:
void RecvFromRemoteAsync(const Rendezvous::ParsedKey& parsed,
const Rendezvous::Args& args,
DoneCallback done) override;
private:
~RdmaRemoteRendezvous() override {}
RdmaMgr* rdma_mgr_;
TF_DISALLOW_COPY_AND_ASSIGN(RdmaRemoteRendezvous);
};
void RdmaRemoteRendezvous::RecvFromRemoteAsync(
const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& recv_args,
DoneCallback done) {
Status s;
// parse src_name and dst_name
string src_name, dst_name, unused;
if (!DeviceNameUtils::SplitDeviceName(parsed.src_device, &src_name,
&unused)) {
s = errors::Internal("Could not parse src name.");
}
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor{}, false);
return;
}
if (!DeviceNameUtils::SplitDeviceName(parsed.dst_device, &dst_name,
&unused)) {
s = errors::Internal("Could not parse dst name.");
}
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor{}, false);
return;
}
CHECK(dst_name.compare(rdma_mgr_->local_worker()) == 0);
RdmaChannel* rc = rdma_mgr_->FindChannel(src_name);
string key(std::move(parsed.FullKey().ToString()));
string key_with_step_id = VerbsUtil::AppendStepidToKey(key, step_id_);
// insert callback
rc->InsertRecvCallback(key_with_step_id, [this, key, key_with_step_id, rc,
recv_args, parsed, done]() {
Status s;
Device* src_dev;
s = env_->device_mgr->LookupDevice("CPU:0", &src_dev);
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor(), true);
return;
}
Device* dst_dev;
s = env_->device_mgr->LookupDevice(parsed.dst_device, &dst_dev);
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor(), true);
return;
}
RdmaBuffer* rb = rc->FindBuffer(key);
RdmaMessage rm;
CHECK(rb->size_ >= RdmaMessage::kMessageTotalBytes);
RdmaMessage::ParseMessage(rm, rb->buffer_);
CHECK(rm.type_ == RDMA_MESSAGE_TENSOR_WRITE);
Tensor val;
if (!rm.is_dead_) {
void* input = static_cast<char*>(rb->buffer_) +
RdmaMessage::kTensorBufferStartIndex;
bool can_memcpy = DataTypeCanUseMemcpy(rm.data_type_);
if (can_memcpy) {
AllocatorAttributes host_alloc_attrs;
host_alloc_attrs.set_gpu_compatible(true);
host_alloc_attrs.set_on_host(true);
if (dst_dev->tensorflow_gpu_device_info() &&
(!recv_args.alloc_attrs.on_host())) {
CHECK(recv_args.device_context)
<< "send dev name: " << src_dev->name()
<< " gpu_info: " << src_dev->tensorflow_gpu_device_info();
Allocator* alloc = ProcessState::singleton()->GetCUDAHostAllocator(0);
Tensor copy(alloc, rm.data_type_, rm.tensor_shape_);
memcpy(DMAHelper::base(©), input, rm.tensor_bytes_);
Allocator* dst_alloc = dst_dev->GetAllocator(host_alloc_attrs);
Tensor gpu_copy(dst_alloc, rm.data_type_, rm.tensor_shape_);
s = VerbsUtil::CopyCPUTensorToGPUSync(©, recv_args.device_context,
dst_dev, &gpu_copy);
CHECK(s.ok()) << "copy tensor to gpu sync";
val = std::move(gpu_copy);
} else {
Allocator* alloc = dst_dev->GetAllocator(host_alloc_attrs);
Tensor copy(alloc, rm.data_type_, rm.tensor_shape_);
memcpy(DMAHelper::base(©), input, rm.tensor_bytes_);
val = std::move(copy);
}
} else {
TensorProto proto;
CHECK(rm.tensor_bytes_ + RdmaMessage::kTensorBufferStartIndex <=
rb->size_);
CHECK(ParseProtoUnlimited(&proto, input, rm.tensor_bytes_))
<< "fail to parse proto from array";
s = dst_dev->MakeTensorFromProto(proto, recv_args.alloc_attrs, &val);
}
}
rc->RemoveRecvCallback(key_with_step_id);
// create message
RdmaMessage br;
br.type_ = RDMA_MESSAGE_BUFFER_IDLE;
br.name_size_ = key.size();
br.name_ = key;
string message = RdmaMessage::CreateMessage(br);
RdmaBuffer* tb = rc->tx_message_buffer_;
tb->EnqueueItem(message);
tb->SendNextItem();
done(s, Args(), recv_args, val, rm.is_dead_);
});
// append key to message queue
RdmaBuffer* rb = rc->tx_message_buffer_;
RdmaMessage rm;
rm.type_ = RDMA_MESSAGE_TENSOR_REQUEST;
rm.name_size_ = key.size();
rm.name_ = key;
rm.step_id_ = step_id_;
string message = RdmaMessage::CreateMessage(rm);
rb->EnqueueItem(message);
rb->SendNextItem();
}
RdmaRendezvousMgr::RdmaRendezvousMgr(const WorkerEnv* env)
: BaseRendezvousMgr(env) {}
BaseRemoteRendezvous* RdmaRendezvousMgr::Create(int64 step_id,
const WorkerEnv* worker_env) {
return new RdmaRemoteRendezvous(worker_env, step_id, rdma_mgr_);
}
} // end namespace tensorflow
#endif
<commit_msg>Fix alloc attributes<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifdef TENSORFLOW_USE_VERBS
#include "tensorflow/contrib/verbs/rdma_rendezvous_mgr.h"
#include <unordered_set>
#include "tensorflow/contrib/verbs/verbs_util.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/common_runtime/gpu/process_state.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace tensorflow {
class RdmaRemoteRendezvous : public BaseRemoteRendezvous {
public:
RdmaRemoteRendezvous(const WorkerEnv* env, int64 step_id, RdmaMgr* rdma_mgr)
: BaseRemoteRendezvous(env, step_id, true), rdma_mgr_(rdma_mgr) {}
protected:
void RecvFromRemoteAsync(const Rendezvous::ParsedKey& parsed,
const Rendezvous::Args& args,
DoneCallback done) override;
private:
~RdmaRemoteRendezvous() override {}
RdmaMgr* rdma_mgr_;
TF_DISALLOW_COPY_AND_ASSIGN(RdmaRemoteRendezvous);
};
void RdmaRemoteRendezvous::RecvFromRemoteAsync(
const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& recv_args,
DoneCallback done) {
Status s;
// parse src_name and dst_name
string src_name, dst_name, unused;
if (!DeviceNameUtils::SplitDeviceName(parsed.src_device, &src_name,
&unused)) {
s = errors::Internal("Could not parse src name.");
}
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor{}, false);
return;
}
if (!DeviceNameUtils::SplitDeviceName(parsed.dst_device, &dst_name,
&unused)) {
s = errors::Internal("Could not parse dst name.");
}
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor{}, false);
return;
}
CHECK(dst_name.compare(rdma_mgr_->local_worker()) == 0);
RdmaChannel* rc = rdma_mgr_->FindChannel(src_name);
string key(std::move(parsed.FullKey().ToString()));
string key_with_step_id = VerbsUtil::AppendStepidToKey(key, step_id_);
// insert callback
rc->InsertRecvCallback(key_with_step_id, [this, key, key_with_step_id, rc,
recv_args, parsed, done]() {
Status s;
Device* src_dev;
s = env_->device_mgr->LookupDevice("CPU:0", &src_dev);
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor(), true);
return;
}
Device* dst_dev;
s = env_->device_mgr->LookupDevice(parsed.dst_device, &dst_dev);
CHECK(s.ok()) << "s is not ok, error code " << s.error_message();
if (!s.ok()) {
done(s, Args(), recv_args, Tensor(), true);
return;
}
RdmaBuffer* rb = rc->FindBuffer(key);
RdmaMessage rm;
CHECK(rb->size_ >= RdmaMessage::kMessageTotalBytes);
RdmaMessage::ParseMessage(rm, rb->buffer_);
CHECK(rm.type_ == RDMA_MESSAGE_TENSOR_WRITE);
Tensor val;
if (!rm.is_dead_) {
void* input = static_cast<char*>(rb->buffer_) +
RdmaMessage::kTensorBufferStartIndex;
bool can_memcpy = DataTypeCanUseMemcpy(rm.data_type_);
if (can_memcpy) {
if (dst_dev->tensorflow_gpu_device_info() &&
(!recv_args.alloc_attrs.on_host())) {
CHECK(recv_args.device_context)
<< "send dev name: " << src_dev->name()
<< " gpu_info: " << src_dev->tensorflow_gpu_device_info();
Allocator* alloc = ProcessState::singleton()->GetCUDAHostAllocator(0);
Tensor copy(alloc, rm.data_type_, rm.tensor_shape_);
memcpy(DMAHelper::base(©), input, rm.tensor_bytes_);
Allocator* dst_alloc = dst_dev->GetAllocator(recv_args.alloc_attrs);
Tensor gpu_copy(dst_alloc, rm.data_type_, rm.tensor_shape_);
s = VerbsUtil::CopyCPUTensorToGPUSync(©, recv_args.device_context,
dst_dev, &gpu_copy);
CHECK(s.ok()) << "copy tensor to gpu sync";
val = std::move(gpu_copy);
} else {
AllocatorAttributes host_alloc_attrs;
host_alloc_attrs.set_gpu_compatible(true);
host_alloc_attrs.set_on_host(true);
Allocator* alloc = dst_dev->GetAllocator(host_alloc_attrs);
Tensor copy(alloc, rm.data_type_, rm.tensor_shape_);
memcpy(DMAHelper::base(©), input, rm.tensor_bytes_);
val = std::move(copy);
}
} else {
TensorProto proto;
CHECK(rm.tensor_bytes_ + RdmaMessage::kTensorBufferStartIndex <=
rb->size_);
CHECK(ParseProtoUnlimited(&proto, input, rm.tensor_bytes_))
<< "fail to parse proto from array";
s = dst_dev->MakeTensorFromProto(proto, recv_args.alloc_attrs, &val);
}
}
rc->RemoveRecvCallback(key_with_step_id);
// create message
RdmaMessage br;
br.type_ = RDMA_MESSAGE_BUFFER_IDLE;
br.name_size_ = key.size();
br.name_ = key;
string message = RdmaMessage::CreateMessage(br);
RdmaBuffer* tb = rc->tx_message_buffer_;
tb->EnqueueItem(message);
tb->SendNextItem();
done(s, Args(), recv_args, val, rm.is_dead_);
});
// append key to message queue
RdmaBuffer* rb = rc->tx_message_buffer_;
RdmaMessage rm;
rm.type_ = RDMA_MESSAGE_TENSOR_REQUEST;
rm.name_size_ = key.size();
rm.name_ = key;
rm.step_id_ = step_id_;
string message = RdmaMessage::CreateMessage(rm);
rb->EnqueueItem(message);
rb->SendNextItem();
}
RdmaRendezvousMgr::RdmaRendezvousMgr(const WorkerEnv* env)
: BaseRendezvousMgr(env) {}
BaseRemoteRendezvous* RdmaRendezvousMgr::Create(int64 step_id,
const WorkerEnv* worker_env) {
return new RdmaRemoteRendezvous(worker_env, step_id, rdma_mgr_);
}
} // end namespace tensorflow
#endif
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <atomic>
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/allocator_registry.h"
#include "tensorflow/core/framework/tracking_allocator.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// If true, cpu allocator collects more stats.
static bool cpu_allocator_collect_stats = false;
void EnableCPUAllocatorStats(bool enable) {
cpu_allocator_collect_stats = enable;
}
bool CPUAllocatorStatsEnabled() { return cpu_allocator_collect_stats; }
static const int kMaxTotalAllocationWarnings = 1;
static const int kMaxSingleAllocationWarnings = 5;
// If cpu_allocator_collect_stats is true, warn when the total allocated memory
// exceeds this threshold.
static const double kTotalAllocationWarningThreshold = 0.5;
// Individual allocations large than this amount will trigger a warning.
static const double kLargeAllocationWarningThreshold = 0.1;
// Cache first invocation to port::AvailableRam, as it can be expensive.
static int64_t LargeAllocationWarningBytes() {
static int64_t value = static_cast<int64>(port::AvailableRam() *
kLargeAllocationWarningThreshold);
return value;
}
static int64_t TotalAllocationWarningBytes() {
static int64_t value = static_cast<int64>(port::AvailableRam() *
kTotalAllocationWarningThreshold);
return value;
}
namespace {
// A default Allocator for CPU devices. ProcessState::GetCPUAllocator() will
// return a different version that may perform better, but may also lack the
// optional stats triggered by the functions above. TODO(tucker): migrate all
// uses of cpu_allocator() except tests to use ProcessState instead.
class CPUAllocator : public Allocator {
public:
CPUAllocator()
: single_allocation_warning_count_(0),
total_allocation_warning_count_(0) {}
~CPUAllocator() override {}
string Name() override { return "cpu"; }
void* AllocateRaw(size_t alignment, size_t num_bytes) override {
if (num_bytes > LargeAllocationWarningBytes() &&
single_allocation_warning_count_ < kMaxSingleAllocationWarnings) {
++single_allocation_warning_count_;
LOG(WARNING) << "Allocation of " << num_bytes << " exceeds "
<< 100 * kLargeAllocationWarningThreshold
<< "% of free system memory.";
}
void* p = port::AlignedMalloc(num_bytes, alignment);
if (cpu_allocator_collect_stats) {
const std::size_t alloc_size = port::MallocExtension_GetAllocatedSize(p);
mutex_lock l(mu_);
++stats_.num_allocs;
stats_.bytes_in_use += alloc_size;
stats_.peak_bytes_in_use =
std::max<int64>(stats_.peak_bytes_in_use, stats_.bytes_in_use);
stats_.largest_alloc_size =
std::max<int64>(stats_.largest_alloc_size, alloc_size);
if (stats_.bytes_in_use > TotalAllocationWarningBytes() &&
total_allocation_warning_count_ < kMaxTotalAllocationWarnings) {
++total_allocation_warning_count_;
LOG(WARNING) << "Total allocated memory " << stats_.bytes_in_use
<< "exceeds " << 100 * kTotalAllocationWarningThreshold
<< "% of free system memory";
}
}
return p;
}
void DeallocateRaw(void* ptr) override {
if (cpu_allocator_collect_stats) {
const std::size_t alloc_size =
port::MallocExtension_GetAllocatedSize(ptr);
mutex_lock l(mu_);
stats_.bytes_in_use -= alloc_size;
}
port::AlignedFree(ptr);
}
absl::optional<AllocatorStats> GetStats() override {
mutex_lock l(mu_);
return stats_;
}
void ClearStats() override {
mutex_lock l(mu_);
stats_.num_allocs = 0;
stats_.peak_bytes_in_use = stats_.bytes_in_use;
stats_.largest_alloc_size = 0;
}
size_t AllocatedSizeSlow(const void* ptr) const override {
return port::MallocExtension_GetAllocatedSize(ptr);
}
private:
mutex mu_;
AllocatorStats stats_ TF_GUARDED_BY(mu_);
// Use <atomic> for single allocations to avoid mutex contention when
// statistics are disabled.
std::atomic<int> single_allocation_warning_count_;
int total_allocation_warning_count_ TF_GUARDED_BY(mu_);
TF_DISALLOW_COPY_AND_ASSIGN(CPUAllocator);
};
class CPUAllocatorFactory : public AllocatorFactory {
public:
Allocator* CreateAllocator() override { return new CPUAllocator; }
SubAllocator* CreateSubAllocator(int numa_node) override {
return new CPUSubAllocator(new CPUAllocator);
}
private:
class CPUSubAllocator : public SubAllocator {
public:
explicit CPUSubAllocator(CPUAllocator* cpu_allocator)
: SubAllocator({}, {}), cpu_allocator_(cpu_allocator) {}
void* Alloc(size_t alignment, size_t num_bytes) override {
return cpu_allocator_->AllocateRaw(alignment, num_bytes);
}
void Free(void* ptr, size_t num_bytes) override {
cpu_allocator_->DeallocateRaw(ptr);
}
private:
CPUAllocator* cpu_allocator_;
};
};
REGISTER_MEM_ALLOCATOR("DefaultCPUAllocator", 100, CPUAllocatorFactory);
} // namespace
} // namespace tensorflow
<commit_msg>in resolution of [Wsign-compare] warning id 10<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <atomic>
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/allocator_registry.h"
#include "tensorflow/core/framework/tracking_allocator.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// If true, cpu allocator collects more stats.
static bool cpu_allocator_collect_stats = false;
void EnableCPUAllocatorStats(bool enable) {
cpu_allocator_collect_stats = enable;
}
bool CPUAllocatorStatsEnabled() { return cpu_allocator_collect_stats; }
static const int kMaxTotalAllocationWarnings = 1;
static const int kMaxSingleAllocationWarnings = 5;
// If cpu_allocator_collect_stats is true, warn when the total allocated memory
// exceeds this threshold.
static const double kTotalAllocationWarningThreshold = 0.5;
// Individual allocations large than this amount will trigger a warning.
static const double kLargeAllocationWarningThreshold = 0.1;
// Cache first invocation to port::AvailableRam, as it can be expensive.
static int64_t LargeAllocationWarningBytes() {
static int64_t value = static_cast<int64>(port::AvailableRam() *
kLargeAllocationWarningThreshold);
return value;
}
static int64_t TotalAllocationWarningBytes() {
static int64_t value = static_cast<int64>(port::AvailableRam() *
kTotalAllocationWarningThreshold);
return value;
}
namespace {
// A default Allocator for CPU devices. ProcessState::GetCPUAllocator() will
// return a different version that may perform better, but may also lack the
// optional stats triggered by the functions above. TODO(tucker): migrate all
// uses of cpu_allocator() except tests to use ProcessState instead.
class CPUAllocator : public Allocator {
public:
CPUAllocator()
: single_allocation_warning_count_(0),
total_allocation_warning_count_(0) {}
~CPUAllocator() override {}
string Name() override { return "cpu"; }
void* AllocateRaw(size_t alignment, size_t num_bytes) override {
if (num_bytes > static_cast<size_t>(LargeAllocationWarningBytes()) &&
single_allocation_warning_count_ < kMaxSingleAllocationWarnings) {
++single_allocation_warning_count_;
LOG(WARNING) << "Allocation of " << num_bytes << " exceeds "
<< 100 * kLargeAllocationWarningThreshold
<< "% of free system memory.";
}
void* p = port::AlignedMalloc(num_bytes, alignment);
if (cpu_allocator_collect_stats) {
const std::size_t alloc_size = port::MallocExtension_GetAllocatedSize(p);
mutex_lock l(mu_);
++stats_.num_allocs;
stats_.bytes_in_use += alloc_size;
stats_.peak_bytes_in_use =
std::max<int64>(stats_.peak_bytes_in_use, stats_.bytes_in_use);
stats_.largest_alloc_size =
std::max<int64>(stats_.largest_alloc_size, alloc_size);
if (stats_.bytes_in_use > TotalAllocationWarningBytes() &&
total_allocation_warning_count_ < kMaxTotalAllocationWarnings) {
++total_allocation_warning_count_;
LOG(WARNING) << "Total allocated memory " << stats_.bytes_in_use
<< "exceeds " << 100 * kTotalAllocationWarningThreshold
<< "% of free system memory";
}
}
return p;
}
void DeallocateRaw(void* ptr) override {
if (cpu_allocator_collect_stats) {
const std::size_t alloc_size =
port::MallocExtension_GetAllocatedSize(ptr);
mutex_lock l(mu_);
stats_.bytes_in_use -= alloc_size;
}
port::AlignedFree(ptr);
}
absl::optional<AllocatorStats> GetStats() override {
mutex_lock l(mu_);
return stats_;
}
void ClearStats() override {
mutex_lock l(mu_);
stats_.num_allocs = 0;
stats_.peak_bytes_in_use = stats_.bytes_in_use;
stats_.largest_alloc_size = 0;
}
size_t AllocatedSizeSlow(const void* ptr) const override {
return port::MallocExtension_GetAllocatedSize(ptr);
}
private:
mutex mu_;
AllocatorStats stats_ TF_GUARDED_BY(mu_);
// Use <atomic> for single allocations to avoid mutex contention when
// statistics are disabled.
std::atomic<int> single_allocation_warning_count_;
int total_allocation_warning_count_ TF_GUARDED_BY(mu_);
TF_DISALLOW_COPY_AND_ASSIGN(CPUAllocator);
};
class CPUAllocatorFactory : public AllocatorFactory {
public:
Allocator* CreateAllocator() override { return new CPUAllocator; }
SubAllocator* CreateSubAllocator(int numa_node) override {
return new CPUSubAllocator(new CPUAllocator);
}
private:
class CPUSubAllocator : public SubAllocator {
public:
explicit CPUSubAllocator(CPUAllocator* cpu_allocator)
: SubAllocator({}, {}), cpu_allocator_(cpu_allocator) {}
void* Alloc(size_t alignment, size_t num_bytes) override {
return cpu_allocator_->AllocateRaw(alignment, num_bytes);
}
void Free(void* ptr, size_t num_bytes) override {
cpu_allocator_->DeallocateRaw(ptr);
}
private:
CPUAllocator* cpu_allocator_;
};
};
REGISTER_MEM_ALLOCATOR("DefaultCPUAllocator", 100, CPUAllocatorFactory);
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/kernel_def.pb.h"
namespace tensorflow {
KernelDefBuilder::KernelDefBuilder(const char* op_name) {
kernel_def_ = new KernelDef;
kernel_def_->set_op(op_name);
}
KernelDefBuilder::~KernelDefBuilder() {
DCHECK(kernel_def_ == nullptr) << "Did not call Build()";
}
KernelDefBuilder& KernelDefBuilder::Device(const char* device_type) {
kernel_def_->set_device_type(device_type);
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<int64>(
const char* attr_name, gtl::ArraySlice<int64> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (const int64 integer : allowed) {
LOG(INFO) << integer;
allowed_values->add_i(integer);
}
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<int64>(const char* attr_name,
int64 allowed) {
return AttrConstraint(
attr_name,
gtl::ArraySlice<int64>(std::initializer_list<int64>({allowed})));
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<string>(
const char* attr_name, gtl::ArraySlice<string> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (const auto& str : allowed) {
allowed_values->add_s(str);
}
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<string>(
const char* attr_name, string allowed) {
return AttrConstraint(
attr_name,
gtl::ArraySlice<string>(std::initializer_list<string>({allowed})));
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<const char*>(
const char* attr_name, gtl::ArraySlice<const char*> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (const auto& str : allowed) {
allowed_values->add_s(str);
}
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<const char*>(
const char* attr_name, const char* allowed) {
return AttrConstraint(attr_name,
gtl::ArraySlice<const char*>(
std::initializer_list<const char*>({allowed})));
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<bool>(const char* attr_name,
bool allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
allowed_values->add_b(allowed);
return *this;
}
KernelDefBuilder& KernelDefBuilder::TypeConstraint(
const char* attr_name, gtl::ArraySlice<DataType> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (DataType dt : allowed) {
allowed_values->add_type(dt);
}
return *this;
}
KernelDefBuilder& KernelDefBuilder::TypeConstraint(const char* attr_name,
DataType allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
constraint->mutable_allowed_values()->mutable_list()->add_type(allowed);
return *this;
}
KernelDefBuilder& KernelDefBuilder::HostMemory(const char* arg_name) {
kernel_def_->add_host_memory_arg(arg_name);
return *this;
}
KernelDefBuilder& KernelDefBuilder::Label(const char* label) {
CHECK_EQ(kernel_def_->label(), "")
<< "Trying to set a kernel's label a second time: '" << label
<< "' in: " << kernel_def_->DebugString();
kernel_def_->set_label(label);
return *this;
}
KernelDefBuilder& KernelDefBuilder::Priority(int32 priority) {
kernel_def_->set_priority(priority);
return *this;
}
const KernelDef* KernelDefBuilder::Build() {
KernelDef* r = kernel_def_;
kernel_def_ = nullptr;
return r;
}
} // namespace tensorflow
<commit_msg>Remove meaningless log in KernelDefBuilder<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/kernel_def.pb.h"
namespace tensorflow {
KernelDefBuilder::KernelDefBuilder(const char* op_name) {
kernel_def_ = new KernelDef;
kernel_def_->set_op(op_name);
}
KernelDefBuilder::~KernelDefBuilder() {
DCHECK(kernel_def_ == nullptr) << "Did not call Build()";
}
KernelDefBuilder& KernelDefBuilder::Device(const char* device_type) {
kernel_def_->set_device_type(device_type);
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<int64>(
const char* attr_name, gtl::ArraySlice<int64> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (const int64 integer : allowed) {
allowed_values->add_i(integer);
}
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<int64>(const char* attr_name,
int64 allowed) {
return AttrConstraint(
attr_name,
gtl::ArraySlice<int64>(std::initializer_list<int64>({allowed})));
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<string>(
const char* attr_name, gtl::ArraySlice<string> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (const auto& str : allowed) {
allowed_values->add_s(str);
}
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<string>(
const char* attr_name, string allowed) {
return AttrConstraint(
attr_name,
gtl::ArraySlice<string>(std::initializer_list<string>({allowed})));
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<const char*>(
const char* attr_name, gtl::ArraySlice<const char*> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (const auto& str : allowed) {
allowed_values->add_s(str);
}
return *this;
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<const char*>(
const char* attr_name, const char* allowed) {
return AttrConstraint(attr_name,
gtl::ArraySlice<const char*>(
std::initializer_list<const char*>({allowed})));
}
template <>
KernelDefBuilder& KernelDefBuilder::AttrConstraint<bool>(const char* attr_name,
bool allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
allowed_values->add_b(allowed);
return *this;
}
KernelDefBuilder& KernelDefBuilder::TypeConstraint(
const char* attr_name, gtl::ArraySlice<DataType> allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
auto* allowed_values = constraint->mutable_allowed_values()->mutable_list();
for (DataType dt : allowed) {
allowed_values->add_type(dt);
}
return *this;
}
KernelDefBuilder& KernelDefBuilder::TypeConstraint(const char* attr_name,
DataType allowed) {
auto* constraint = kernel_def_->add_constraint();
constraint->set_name(attr_name);
constraint->mutable_allowed_values()->mutable_list()->add_type(allowed);
return *this;
}
KernelDefBuilder& KernelDefBuilder::HostMemory(const char* arg_name) {
kernel_def_->add_host_memory_arg(arg_name);
return *this;
}
KernelDefBuilder& KernelDefBuilder::Label(const char* label) {
CHECK_EQ(kernel_def_->label(), "")
<< "Trying to set a kernel's label a second time: '" << label
<< "' in: " << kernel_def_->DebugString();
kernel_def_->set_label(label);
return *this;
}
KernelDefBuilder& KernelDefBuilder::Priority(int32 priority) {
kernel_def_->set_priority(priority);
return *this;
}
const KernelDef* KernelDefBuilder::Build() {
KernelDef* r = kernel_def_;
kernel_def_ = nullptr;
return r;
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scenwnd.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2008-03-18 14:52:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
//------------------------------------------------------------------
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/slstitm.hxx>
#include <svtools/stritem.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/svapp.hxx>
#include "navipi.hxx"
#include "popmenu.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include "globstr.hrc"
//------------------------------------------------------------------------
//========================================================================
// class ScScenarioWindow ------------------------------------------------
//========================================================================
// -----------------------------------------------------------------------
ScScenarioListBox::ScScenarioListBox( Window* pParent )
: ListBox ( pParent, WB_BORDER ),
rParent ( (ScScenarioWindow&)*pParent ),
pAccel ( NULL )
{
Font aFont( GetFont() );
aFont.SetTransparent( TRUE );
aFont.SetWeight( WEIGHT_LIGHT );
SetFont( aFont );
}
// -----------------------------------------------------------------------
__EXPORT ScScenarioListBox::~ScScenarioListBox()
{
ClearEntryList();
delete pAccel;
}
// -----------------------------------------------------------------------
void ScScenarioListBox::UpdateEntries( List* pNewEntryList )
{
ClearEntryList();
Clear();
if ( pNewEntryList )
{
if ( pNewEntryList->Count() > 1 )
{
CopyEntryList( *pNewEntryList );
SetUpdateMode( FALSE );
String* pEntry = (String*)aEntryList.First();
while ( pEntry )
{
InsertEntry( *pEntry, LISTBOX_APPEND );
aEntryList.Next(); // Skip the comment
aEntryList.Next(); // Skip the protection
pEntry = (String*)aEntryList.Next();
}
SetUpdateMode( TRUE );
SetNoSelection();
rParent.SetComment( EMPTY_STRING );
}
else if ( pNewEntryList->Count() == 1 )
// Tabelle ist Scenario-Tabelle: nur Kommentar
rParent.SetComment( *((String*)pNewEntryList->First()) );
else
rParent.SetComment( EMPTY_STRING ); // normale Tabelle ohne Szenarien
}
}
// -----------------------------------------------------------------------
void ScScenarioListBox::ClearEntryList()
{
String* pEntry = (String*)aEntryList.First();
while ( pEntry )
{
delete pEntry;
pEntry = (String*)aEntryList.Next();
}
aEntryList.Clear();
}
// -----------------------------------------------------------------------
void ScScenarioListBox::CopyEntryList( List& rNewList )
{
if ( aEntryList.Count() > 0 )
ClearEntryList();
String* pEntry = (String*)rNewList.First();
while ( pEntry )
{
aEntryList.Insert( new String( *pEntry ), LIST_APPEND );
pEntry = (String*)rNewList.Next();
}
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::Select()
{
String* pEntry = (String*)aEntryList.GetObject( (GetSelectEntryPos()*3)+1 );
if ( pEntry )
rParent.SetComment( *pEntry );
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::DoubleClick()
{
SfxStringItem aStringItem( SID_SELECT_SCENARIO, GetSelectEntry() );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
pViewFrm->GetDispatcher()->Execute( SID_SELECT_SCENARIO,
SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD,
&aStringItem, 0L, 0L );
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::GetFocus()
{
pAccel = new Accelerator;
pAccel->InsertItem( 1, KeyCode( KEY_RETURN ) );
pAccel->InsertItem( 2, KeyCode( KEY_ESCAPE ) );
pAccel->SetSelectHdl( LINK( this, ScScenarioListBox, AccelSelectHdl ) );
Application::InsertAccel( pAccel );
aCurText = GetText();
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::LoseFocus()
{
Application::RemoveAccel( pAccel );
delete pAccel;
pAccel = NULL;
}
// -----------------------------------------------------------------------
IMPL_LINK( ScScenarioListBox, AccelSelectHdl, Accelerator *, pSelAccel )
{
if ( !pSelAccel ) return 0;
switch ( pSelAccel->GetCurKeyCode().GetCode() )
{
case KEY_RETURN:
Select();
break;
case KEY_ESCAPE:
SelectEntry( aCurText );
Select();
break;
default:
break;
}
return 0;
}
//---------------------------------------------------------------
long ScScenarioListBox::Notify( NotifyEvent& rNEvt )
{
bool bHandled = false;
if( rNEvt.GetType() == EVENT_KEYINPUT )
{
KeyCode aCode = rNEvt.GetKeyEvent()->GetKeyCode();
if( KEY_RETURN == aCode.GetCode() )
{
DoubleClick();
bHandled = true;
}
}
else if ( rNEvt.GetType() == EVENT_COMMAND && GetSelectEntryCount() )
{
const CommandEvent* pCEvt = rNEvt.GetCommandEvent();
if ( pCEvt && pCEvt->GetCommand() == COMMAND_CONTEXTMENU )
{
String* pProtect = (String*)aEntryList.GetObject( (GetSelectEntryPos()*3)+2 );
if(pProtect && pProtect->GetChar(0) == '0')
{
ScPopupMenu aPopup( ScResId( RID_POPUP_NAVIPI_SCENARIO ) );
aPopup.Execute( this, pCEvt->GetMousePosPixel() );
if (aPopup.WasHit())
{
String aName = GetSelectEntry();
USHORT nId = aPopup.GetSelected();
if ( nId == RID_NAVIPI_SCENARIO_DELETE )
{
short nRes = QueryBox( NULL, WinBits( WB_YES_NO | WB_DEF_YES ),
ScGlobal::GetRscString(STR_QUERY_DELSCENARIO) ).Execute();
if ( nRes == RET_YES )
{
SfxStringItem aStringItem( SID_DELETE_SCENARIO, aName );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
pViewFrm->GetDispatcher()->Execute( SID_DELETE_SCENARIO,
SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD,
&aStringItem, 0L, 0L );
}
}
else if ( nId == RID_NAVIPI_SCENARIO_EDIT )
{
SfxStringItem aStringItem( SID_EDIT_SCENARIO, aName );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
pViewFrm->GetDispatcher()->Execute( SID_EDIT_SCENARIO,
SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD,
&aStringItem, 0L, 0L );
}
}
}
bHandled = true;
}
}
return bHandled ? 1 : ListBox::Notify( rNEvt );
}
//========================================================================
// class ScScenarioWindow ------------------------------------------------
//========================================================================
ScScenarioWindow::ScScenarioWindow( Window* pParent,const String& aQH_List,
const String& aQH_Comment)
: Window ( pParent ),
aLbScenario ( this ),
aEdComment ( this, WB_BORDER | WB_LEFT
| WB_READONLY | WB_VSCROLL )
{
Font aFont( GetFont() );
aFont.SetTransparent( TRUE );
aFont.SetWeight( WEIGHT_LIGHT );
aEdComment.SetFont( aFont );
aEdComment.SetMaxTextLen( 512 );
aLbScenario.SetPosPixel( Point(0,0) );
aLbScenario.SetHelpId(HID_SC_SCENWIN_TOP);
aEdComment.SetHelpId(HID_SC_SCENWIN_BOTTOM);
aLbScenario.Show();
aEdComment.Show();
aLbScenario.SetQuickHelpText(aQH_List);
aEdComment.SetQuickHelpText(aQH_Comment);
aEdComment.SetBackground( Color( COL_LIGHTGRAY ) );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
{
SfxBindings& rBindings = pViewFrm->GetBindings();
rBindings.Invalidate( SID_SELECT_SCENARIO );
rBindings.Update( SID_SELECT_SCENARIO );
}
}
// -----------------------------------------------------------------------
__EXPORT ScScenarioWindow::~ScScenarioWindow()
{
}
void ScScenarioWindow::Paint( const Rectangle& rRec )
{
const StyleSettings& rStyleSettings = Application::GetSettings().GetStyleSettings();
Color aBgColor = rStyleSettings.GetFaceColor();
SetBackground( aBgColor );
Window::Paint( rRec );
}
// -----------------------------------------------------------------------
void ScScenarioWindow::NotifyState( const SfxPoolItem* pState )
{
if( pState )
{
aLbScenario.Enable();
if ( pState->ISA(SfxStringItem) )
{
String aNewEntry( ((const SfxStringItem*)pState)->GetValue() );
if ( aNewEntry.Len() > 0 )
aLbScenario.SelectEntry( aNewEntry );
else
aLbScenario.SetNoSelection();
}
else if ( pState->ISA(SfxStringListItem) )
{
aLbScenario.UpdateEntries( ((SfxStringListItem*)pState)->GetList() );
}
}
else
{
aLbScenario.Disable();
aLbScenario.SetNoSelection();
}
}
// -----------------------------------------------------------------------
void ScScenarioWindow::SetSizePixel( const Size& rNewSize )
{
Size aSize( rNewSize );
long nHeight = aSize.Height() / 2;
Window::SetSizePixel( aSize );
aSize.Height() = nHeight;
aLbScenario.SetSizePixel( aSize );
aSize.Height() -= 4;
aEdComment.SetPosSizePixel( Point( 0, nHeight+4 ), aSize );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.10); FILE MERGED 2008/03/31 17:16:14 rt 1.8.10.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scenwnd.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
//------------------------------------------------------------------
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/slstitm.hxx>
#include <svtools/stritem.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/svapp.hxx>
#include "navipi.hxx"
#include "popmenu.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include "globstr.hrc"
//------------------------------------------------------------------------
//========================================================================
// class ScScenarioWindow ------------------------------------------------
//========================================================================
// -----------------------------------------------------------------------
ScScenarioListBox::ScScenarioListBox( Window* pParent )
: ListBox ( pParent, WB_BORDER ),
rParent ( (ScScenarioWindow&)*pParent ),
pAccel ( NULL )
{
Font aFont( GetFont() );
aFont.SetTransparent( TRUE );
aFont.SetWeight( WEIGHT_LIGHT );
SetFont( aFont );
}
// -----------------------------------------------------------------------
__EXPORT ScScenarioListBox::~ScScenarioListBox()
{
ClearEntryList();
delete pAccel;
}
// -----------------------------------------------------------------------
void ScScenarioListBox::UpdateEntries( List* pNewEntryList )
{
ClearEntryList();
Clear();
if ( pNewEntryList )
{
if ( pNewEntryList->Count() > 1 )
{
CopyEntryList( *pNewEntryList );
SetUpdateMode( FALSE );
String* pEntry = (String*)aEntryList.First();
while ( pEntry )
{
InsertEntry( *pEntry, LISTBOX_APPEND );
aEntryList.Next(); // Skip the comment
aEntryList.Next(); // Skip the protection
pEntry = (String*)aEntryList.Next();
}
SetUpdateMode( TRUE );
SetNoSelection();
rParent.SetComment( EMPTY_STRING );
}
else if ( pNewEntryList->Count() == 1 )
// Tabelle ist Scenario-Tabelle: nur Kommentar
rParent.SetComment( *((String*)pNewEntryList->First()) );
else
rParent.SetComment( EMPTY_STRING ); // normale Tabelle ohne Szenarien
}
}
// -----------------------------------------------------------------------
void ScScenarioListBox::ClearEntryList()
{
String* pEntry = (String*)aEntryList.First();
while ( pEntry )
{
delete pEntry;
pEntry = (String*)aEntryList.Next();
}
aEntryList.Clear();
}
// -----------------------------------------------------------------------
void ScScenarioListBox::CopyEntryList( List& rNewList )
{
if ( aEntryList.Count() > 0 )
ClearEntryList();
String* pEntry = (String*)rNewList.First();
while ( pEntry )
{
aEntryList.Insert( new String( *pEntry ), LIST_APPEND );
pEntry = (String*)rNewList.Next();
}
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::Select()
{
String* pEntry = (String*)aEntryList.GetObject( (GetSelectEntryPos()*3)+1 );
if ( pEntry )
rParent.SetComment( *pEntry );
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::DoubleClick()
{
SfxStringItem aStringItem( SID_SELECT_SCENARIO, GetSelectEntry() );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
pViewFrm->GetDispatcher()->Execute( SID_SELECT_SCENARIO,
SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD,
&aStringItem, 0L, 0L );
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::GetFocus()
{
pAccel = new Accelerator;
pAccel->InsertItem( 1, KeyCode( KEY_RETURN ) );
pAccel->InsertItem( 2, KeyCode( KEY_ESCAPE ) );
pAccel->SetSelectHdl( LINK( this, ScScenarioListBox, AccelSelectHdl ) );
Application::InsertAccel( pAccel );
aCurText = GetText();
}
// -----------------------------------------------------------------------
void __EXPORT ScScenarioListBox::LoseFocus()
{
Application::RemoveAccel( pAccel );
delete pAccel;
pAccel = NULL;
}
// -----------------------------------------------------------------------
IMPL_LINK( ScScenarioListBox, AccelSelectHdl, Accelerator *, pSelAccel )
{
if ( !pSelAccel ) return 0;
switch ( pSelAccel->GetCurKeyCode().GetCode() )
{
case KEY_RETURN:
Select();
break;
case KEY_ESCAPE:
SelectEntry( aCurText );
Select();
break;
default:
break;
}
return 0;
}
//---------------------------------------------------------------
long ScScenarioListBox::Notify( NotifyEvent& rNEvt )
{
bool bHandled = false;
if( rNEvt.GetType() == EVENT_KEYINPUT )
{
KeyCode aCode = rNEvt.GetKeyEvent()->GetKeyCode();
if( KEY_RETURN == aCode.GetCode() )
{
DoubleClick();
bHandled = true;
}
}
else if ( rNEvt.GetType() == EVENT_COMMAND && GetSelectEntryCount() )
{
const CommandEvent* pCEvt = rNEvt.GetCommandEvent();
if ( pCEvt && pCEvt->GetCommand() == COMMAND_CONTEXTMENU )
{
String* pProtect = (String*)aEntryList.GetObject( (GetSelectEntryPos()*3)+2 );
if(pProtect && pProtect->GetChar(0) == '0')
{
ScPopupMenu aPopup( ScResId( RID_POPUP_NAVIPI_SCENARIO ) );
aPopup.Execute( this, pCEvt->GetMousePosPixel() );
if (aPopup.WasHit())
{
String aName = GetSelectEntry();
USHORT nId = aPopup.GetSelected();
if ( nId == RID_NAVIPI_SCENARIO_DELETE )
{
short nRes = QueryBox( NULL, WinBits( WB_YES_NO | WB_DEF_YES ),
ScGlobal::GetRscString(STR_QUERY_DELSCENARIO) ).Execute();
if ( nRes == RET_YES )
{
SfxStringItem aStringItem( SID_DELETE_SCENARIO, aName );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
pViewFrm->GetDispatcher()->Execute( SID_DELETE_SCENARIO,
SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD,
&aStringItem, 0L, 0L );
}
}
else if ( nId == RID_NAVIPI_SCENARIO_EDIT )
{
SfxStringItem aStringItem( SID_EDIT_SCENARIO, aName );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
pViewFrm->GetDispatcher()->Execute( SID_EDIT_SCENARIO,
SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD,
&aStringItem, 0L, 0L );
}
}
}
bHandled = true;
}
}
return bHandled ? 1 : ListBox::Notify( rNEvt );
}
//========================================================================
// class ScScenarioWindow ------------------------------------------------
//========================================================================
ScScenarioWindow::ScScenarioWindow( Window* pParent,const String& aQH_List,
const String& aQH_Comment)
: Window ( pParent ),
aLbScenario ( this ),
aEdComment ( this, WB_BORDER | WB_LEFT
| WB_READONLY | WB_VSCROLL )
{
Font aFont( GetFont() );
aFont.SetTransparent( TRUE );
aFont.SetWeight( WEIGHT_LIGHT );
aEdComment.SetFont( aFont );
aEdComment.SetMaxTextLen( 512 );
aLbScenario.SetPosPixel( Point(0,0) );
aLbScenario.SetHelpId(HID_SC_SCENWIN_TOP);
aEdComment.SetHelpId(HID_SC_SCENWIN_BOTTOM);
aLbScenario.Show();
aEdComment.Show();
aLbScenario.SetQuickHelpText(aQH_List);
aEdComment.SetQuickHelpText(aQH_Comment);
aEdComment.SetBackground( Color( COL_LIGHTGRAY ) );
SfxViewFrame* pViewFrm = SfxViewFrame::Current();
if (pViewFrm)
{
SfxBindings& rBindings = pViewFrm->GetBindings();
rBindings.Invalidate( SID_SELECT_SCENARIO );
rBindings.Update( SID_SELECT_SCENARIO );
}
}
// -----------------------------------------------------------------------
__EXPORT ScScenarioWindow::~ScScenarioWindow()
{
}
void ScScenarioWindow::Paint( const Rectangle& rRec )
{
const StyleSettings& rStyleSettings = Application::GetSettings().GetStyleSettings();
Color aBgColor = rStyleSettings.GetFaceColor();
SetBackground( aBgColor );
Window::Paint( rRec );
}
// -----------------------------------------------------------------------
void ScScenarioWindow::NotifyState( const SfxPoolItem* pState )
{
if( pState )
{
aLbScenario.Enable();
if ( pState->ISA(SfxStringItem) )
{
String aNewEntry( ((const SfxStringItem*)pState)->GetValue() );
if ( aNewEntry.Len() > 0 )
aLbScenario.SelectEntry( aNewEntry );
else
aLbScenario.SetNoSelection();
}
else if ( pState->ISA(SfxStringListItem) )
{
aLbScenario.UpdateEntries( ((SfxStringListItem*)pState)->GetList() );
}
}
else
{
aLbScenario.Disable();
aLbScenario.SetNoSelection();
}
}
// -----------------------------------------------------------------------
void ScScenarioWindow::SetSizePixel( const Size& rNewSize )
{
Size aSize( rNewSize );
long nHeight = aSize.Height() / 2;
Window::SetSizePixel( aSize );
aSize.Height() = nHeight;
aLbScenario.SetSizePixel( aSize );
aSize.Height() -= 4;
aEdComment.SetPosSizePixel( Point( 0, nHeight+4 ), aSize );
}
<|endoftext|> |
<commit_before>
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "openMVG/image/image_io.hpp"
#include "openMVG/stl/stl.hpp"
#include "third_party/progress/progress.hpp"
namespace openMVG {
namespace sfm {
using namespace openMVG::geometry;
using namespace openMVG::cameras;
using namespace openMVG::image;
/// Find the color of the SfM_Data Landmarks/structure
void ColorizeTracks( SfM_Data & sfm_data )
{
// Colorize each track
// Start with the most representative image
// and iterate to provide a color to each 3D point
{
std::vector<Vec3> vec_3dPoints;
std::vector<Vec3> vec_tracksColor;
C_Progress_display my_progress_bar(sfm_data.GetLandmarks().size(),
std::cout,
"\nCompute scene structure color\n");
vec_3dPoints.resize(sfm_data.GetLandmarks().size());
//Build a list of contiguous index for the trackIds
std::map<IndexT, IndexT> trackIds_to_contiguousIndexes;
IndexT cpt = 0;
for (Landmarks::const_iterator it = sfm_data.GetLandmarks().begin();
it != sfm_data.GetLandmarks().end(); ++it, ++cpt)
{
trackIds_to_contiguousIndexes[it->first] = cpt;
vec_3dPoints[cpt] = it->second.X;
}
// The track list that will be colored (point removed during the process)
std::set<IndexT> remainingTrackToColor;
std::transform(sfm_data.GetLandmarks().begin(), sfm_data.GetLandmarks().end(),
std::inserter(remainingTrackToColor, remainingTrackToColor.begin()),
stl::RetrieveKey());
while( !remainingTrackToColor.empty() )
{
// Find the most representative image (for the remaining 3D points)
// a. Count the number of observation per view for each 3Dpoint Index
// b. Sort to find the most representative view index
std::map<IndexT, IndexT> map_IndexCardinal; // ViewId, Cardinal
for (std::set<IndexT>::const_iterator
iterT = remainingTrackToColor.begin();
iterT != remainingTrackToColor.end();
++iterT)
{
const size_t trackId = *iterT;
const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;
for( Observations::const_iterator iterObs = obs.begin();
iterObs != obs.end(); ++iterObs)
{
const size_t viewId = iterObs->first;
if (map_IndexCardinal.find(viewId) == map_IndexCardinal.end())
map_IndexCardinal[viewId] = 1;
else
++map_IndexCardinal[viewId];
}
}
// Find the View index that is the most represented
std::vector<IndexT> vec_cardinal;
std::transform(map_IndexCardinal.begin(),
map_IndexCardinal.end(),
std::back_inserter(vec_cardinal),
stl::RetrieveValue());
using namespace stl::indexed_sort;
std::vector< sort_index_packet_descend< IndexT, IndexT> > packet_vec(vec_cardinal.size());
sort_index_helper(packet_vec, &vec_cardinal[0], 1);
// First image index with the most of occurence
std::map<IndexT, IndexT>::const_iterator iterTT = map_IndexCardinal.begin();
std::advance(iterTT, packet_vec[0].index);
const size_t view_index = iterTT->first;
const View * view = sfm_data.GetViews().at(view_index).get();
const std::string sView_filename = stlplus::create_filespec(sfm_data.s_root_path,
view->s_Img_path);
Image<RGBColor> image;
ReadImage(sView_filename.c_str(), &image);
// Iterate through the remaining track to color
// - look if the current view is present to color the track
std::set<IndexT> set_toRemove;
for (std::set<IndexT>::const_iterator
iterT = remainingTrackToColor.begin();
iterT != remainingTrackToColor.end();
++iterT)
{
const size_t trackId = *iterT;
const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;
Observations::const_iterator it = obs.find(view_index);
if (it != obs.end())
{
// Color the track
const Vec2 & pt = it->second.x;
sfm_data.structure.at(trackId).rgb = image(pt.y(), pt.x());
set_toRemove.insert(trackId);
++my_progress_bar;
}
}
// Remove colored track
for (std::set<IndexT>::const_iterator iter = set_toRemove.begin();
iter != set_toRemove.end(); ++iter)
{
remainingTrackToColor.erase(*iter);
}
}
}
}
} // namespace sfm
} // namespace openMVG
<commit_msg>[sfm] bugfix ColorizeTracks: avoid infinite loop when an image is missing<commit_after>
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "openMVG/image/image_io.hpp"
#include "openMVG/stl/stl.hpp"
#include "third_party/progress/progress.hpp"
namespace openMVG {
namespace sfm {
using namespace openMVG::geometry;
using namespace openMVG::cameras;
using namespace openMVG::image;
/// Find the color of the SfM_Data Landmarks/structure
void ColorizeTracks( SfM_Data & sfm_data )
{
// Colorize each track
// Start with the most representative image
// and iterate to provide a color to each 3D point
{
std::vector<Vec3> vec_3dPoints;
std::vector<Vec3> vec_tracksColor;
C_Progress_display my_progress_bar(sfm_data.GetLandmarks().size(),
std::cout,
"\nCompute scene structure color\n");
vec_3dPoints.resize(sfm_data.GetLandmarks().size());
//Build a list of contiguous index for the trackIds
std::map<IndexT, IndexT> trackIds_to_contiguousIndexes;
IndexT cpt = 0;
for (Landmarks::const_iterator it = sfm_data.GetLandmarks().begin();
it != sfm_data.GetLandmarks().end(); ++it, ++cpt)
{
trackIds_to_contiguousIndexes[it->first] = cpt;
vec_3dPoints[cpt] = it->second.X;
}
// The track list that will be colored (point removed during the process)
std::set<IndexT> remainingTrackToColor;
std::transform(sfm_data.GetLandmarks().begin(), sfm_data.GetLandmarks().end(),
std::inserter(remainingTrackToColor, remainingTrackToColor.begin()),
stl::RetrieveKey());
while( !remainingTrackToColor.empty() )
{
// Find the most representative image (for the remaining 3D points)
// a. Count the number of observation per view for each 3Dpoint Index
// b. Sort to find the most representative view index
std::map<IndexT, IndexT> map_IndexCardinal; // ViewId, Cardinal
for (std::set<IndexT>::const_iterator
iterT = remainingTrackToColor.begin();
iterT != remainingTrackToColor.end();
++iterT)
{
const size_t trackId = *iterT;
const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;
for( Observations::const_iterator iterObs = obs.begin();
iterObs != obs.end(); ++iterObs)
{
const size_t viewId = iterObs->first;
if (map_IndexCardinal.find(viewId) == map_IndexCardinal.end())
map_IndexCardinal[viewId] = 1;
else
++map_IndexCardinal[viewId];
}
}
// Find the View index that is the most represented
std::vector<IndexT> vec_cardinal;
std::transform(map_IndexCardinal.begin(),
map_IndexCardinal.end(),
std::back_inserter(vec_cardinal),
stl::RetrieveValue());
using namespace stl::indexed_sort;
std::vector< sort_index_packet_descend< IndexT, IndexT> > packet_vec(vec_cardinal.size());
sort_index_helper(packet_vec, &vec_cardinal[0], 1);
// First image index with the most of occurrence
std::map<IndexT, IndexT>::const_iterator iterTT = map_IndexCardinal.begin();
std::advance(iterTT, packet_vec[0].index);
const size_t view_index = iterTT->first;
const View * view = sfm_data.GetViews().at(view_index).get();
const std::string sView_filename = stlplus::create_filespec(sfm_data.s_root_path,
view->s_Img_path);
Image<RGBColor> image;
if(!ReadImage(sView_filename.c_str(), &image))
{
std::cerr << "Unable to read image: " << sView_filename << std::endl;
return;
}
// Iterate through the remaining track to color
// - look if the current view is present to color the track
std::set<IndexT> set_toRemove;
for (std::set<IndexT>::const_iterator
iterT = remainingTrackToColor.begin();
iterT != remainingTrackToColor.end();
++iterT)
{
const size_t trackId = *iterT;
const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;
Observations::const_iterator it = obs.find(view_index);
if (it != obs.end())
{
// Color the track
const Vec2 & pt = it->second.x;
sfm_data.structure.at(trackId).rgb = image(pt.y(), pt.x());
set_toRemove.insert(trackId);
++my_progress_bar;
}
}
// Remove colored track
for (std::set<IndexT>::const_iterator iter = set_toRemove.begin();
iter != set_toRemove.end(); ++iter)
{
remainingTrackToColor.erase(*iter);
}
}
}
}
} // namespace sfm
} // namespace openMVG
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/UnfoldSelect.h"
#include "compiler/InfoSink.h"
#include "compiler/OutputHLSL.h"
namespace sh
{
UnfoldSelect::UnfoldSelect(TParseContext &context, OutputHLSL *outputHLSL) : mContext(context), mOutputHLSL(outputHLSL)
{
mTemporaryIndex = 0;
}
void UnfoldSelect::traverse(TIntermNode *node)
{
mTemporaryIndex++;
node->traverse(this);
}
bool UnfoldSelect::visitSelection(Visit visit, TIntermSelection *node)
{
TInfoSinkBase &out = mOutputHLSL->getBodyStream();
if (node->usesTernaryOperator())
{
int i = mTemporaryIndex++;
out << mOutputHLSL->typeString(node->getType()) << " t" << i << ";\n";
node->getCondition()->traverse(this);
out << "if(";
node->getCondition()->traverse(mOutputHLSL);
out << ")\n"
"{\n";
node->getTrueBlock()->traverse(this);
out << " t" << i << " = ";
node->getTrueBlock()->traverse(mOutputHLSL);
out << ";\n"
"}\n"
"else\n"
"{\n";
node->getCondition()->traverse(this);
out << " t" << i << " = ";
node->getFalseBlock()->traverse(mOutputHLSL);
out << ";\n"
"}\n";
mTemporaryIndex--;
}
return false;
}
int UnfoldSelect::getTemporaryIndex()
{
return mTemporaryIndex;
}
}
<commit_msg>Fix ternary operator unfolding TRAC #14155 Issue=70 Signed-off-by: Daniel Koch<commit_after>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/UnfoldSelect.h"
#include "compiler/InfoSink.h"
#include "compiler/OutputHLSL.h"
namespace sh
{
UnfoldSelect::UnfoldSelect(TParseContext &context, OutputHLSL *outputHLSL) : mContext(context), mOutputHLSL(outputHLSL)
{
mTemporaryIndex = 0;
}
void UnfoldSelect::traverse(TIntermNode *node)
{
mTemporaryIndex++;
node->traverse(this);
}
bool UnfoldSelect::visitSelection(Visit visit, TIntermSelection *node)
{
TInfoSinkBase &out = mOutputHLSL->getBodyStream();
if (node->usesTernaryOperator())
{
int i = mTemporaryIndex++;
out << mOutputHLSL->typeString(node->getType()) << " t" << i << ";\n";
node->getCondition()->traverse(this);
out << "if(";
node->getCondition()->traverse(mOutputHLSL);
out << ")\n"
"{\n";
node->getTrueBlock()->traverse(this);
out << " t" << i << " = ";
node->getTrueBlock()->traverse(mOutputHLSL);
out << ";\n"
"}\n"
"else\n"
"{\n";
node->getFalseBlock()->traverse(this);
out << " t" << i << " = ";
node->getFalseBlock()->traverse(mOutputHLSL);
out << ";\n"
"}\n";
mTemporaryIndex--;
}
return false;
}
int UnfoldSelect::getTemporaryIndex()
{
return mTemporaryIndex;
}
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2016 by Contributors
* \file infer_shape.cc
* \brief Inference the shapes given existin information.
*/
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/graph_attr_types.h>
namespace nnvm {
namespace pass {
namespace {
template<typename AttrType, typename IsNone, typename FDefault>
Graph InferAttr(Graph &&ret,
const AttrType empty_val,
const char* infer_name,
const char* input_name,
const char* attr_key_name,
const char* attr_name,
const char* unknown_name,
IsNone fis_none,
FDefault fdefault) {
using AttrVector = std::vector<AttrType>;
const IndexedGraph& idx = ret.indexed_graph();
static auto& finfer_shape =
Op::GetAttr<FInferNodeEntryAttr<AttrType> >(infer_name);
static auto& backward_map =
Op::GetAttr<FBackwardOutToInIndex>("FBackwardOutToInIndex");
static auto& backward_in_grad =
Op::GetAttr<FBackwardInGradIndex>("FBackwardInGradIndex");
// reshape shape vector
AttrVector rshape;
if (ret.attrs.count(attr_name) != 0) {
rshape = ret.MoveCopyAttr<AttrVector>(attr_name);
} else {
rshape.resize(idx.num_node_entries(), empty_val);
}
if (ret.attrs.count(input_name) != 0) {
const AttrVector& shape_args = ret.GetAttr<AttrVector>(input_name);
CHECK_LE(shape_args.size(), idx.input_nodes().size())
<< "More provided shapes than number of arguments.";
for (size_t i = 0; i < shape_args.size(); ++i) {
rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i];
}
// erase the provided arguments
ret.attrs.erase(input_name);
}
std::string shape_attr_key;
if (ret.attrs.count(attr_key_name) != 0) {
shape_attr_key = ret.GetAttr<std::string>(attr_key_name);
// erase the provided arguments
ret.attrs.erase(attr_key_name);
}
// Temp space for shape inference.
std::vector<AttrType> ishape, oshape;
// inference step function for nid
auto infer_step = [&](uint32_t nid) {
const auto& inode = idx[nid];
const uint32_t num_inputs = inode.inputs.size();
const uint32_t num_outputs = inode.source->num_outputs();
if (inode.source->is_variable()) {
// Variable node. No operator. Only one output entry.
CHECK(inode.source->op() == nullptr);
CHECK_EQ(num_outputs, 1);
const uint32_t out_ent_id = idx.entry_id(nid, 0);
if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) {
auto it = inode.source->attrs.dict.find(shape_attr_key);
if (it != inode.source->attrs.dict.end()) {
std::istringstream is(it->second);
CHECK(is >> rshape[out_ent_id]) << "Invalid attribute";
}
}
} else if (backward_map.count(inode.source->op())) {
// Backward operator inference.
CHECK_GE(inode.control_deps.size(), 1)
<< "BackwardOp need to have control_deps to its forward op";
const IndexedGraph::Node& fnode = idx[inode.control_deps[0]];
// Inference the outputs of backward operator (equal to the inputs
// of its corresponding forward operator).
std::vector<uint32_t> out_map =
backward_map[inode.source->op()](inode.source->attrs);
for (size_t i = 0; i < out_map.size(); ++i) {
uint32_t in_id = out_map[i];
CHECK_LT(in_id, fnode.inputs.size());
rshape[idx.entry_id(nid, i)] =
rshape[idx.entry_id(fnode.inputs[in_id])];
}
if (backward_in_grad.count(inode.source->op())) {
std::vector<uint32_t> in_grad =
backward_in_grad[inode.source->op()](inode.source->attrs);
CHECK_LE(in_grad.size(), fnode.source->num_outputs());
for (size_t i = 0; i < in_grad.size(); ++i) {
uint32_t eid = idx.entry_id(inode.inputs[in_grad[i]]);
if (fis_none(rshape[eid])) {
rshape[eid] = rshape[idx.entry_id(inode.control_deps[0], i)];
}
}
}
} else {
bool forward_known = true;
// Forward operator inference.
ishape.resize(num_inputs, empty_val);
for (uint32_t i = 0; i < ishape.size(); ++i) {
ishape[i] = rshape[idx.entry_id(inode.inputs[i])];
if (fis_none(ishape[i])) forward_known = false;
}
oshape.resize(num_outputs, empty_val);
for (uint32_t i = 0; i < oshape.size(); ++i) {
oshape[i] = rshape[idx.entry_id(nid, i)];
if (fis_none(oshape[i])) forward_known = false;
}
if (!forward_known) {
auto finfer = finfer_shape.get(inode.source->op(), fdefault);
CHECK(finfer != nullptr)
<< "Attribute " << infer_name
<< " is not registed by op " << inode.source->op()->name;
// Call inference function of the operator.
forward_known = finfer(inode.source->attrs, &ishape, &oshape);
}
// Save to the result map.
for (uint32_t i = 0; i < num_inputs; ++i) {
rshape[idx.entry_id(inode.inputs[i])] = ishape[i];
}
for (uint32_t i = 0; i < num_outputs; ++i) {
rshape[idx.entry_id(nid, i)] = oshape[i];
}
}
};
size_t num_unknown = 0;
const int kMaxStep = 3;
for (int i = 0; i < kMaxStep; ++i) {
if (i % 2 == 0) {
for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
infer_step(nid);
}
} else {
// backward inference
for (uint32_t i = idx.num_nodes(); i != 0; --i) {
infer_step(i - 1);
}
}
num_unknown = 0;
for (size_t i = 0; i < idx.num_node_entries(); ++i) {
if (fis_none(rshape[i])) ++num_unknown;
}
if (num_unknown == 0) break;
}
// set the shapes
ret.attrs[attr_name] = std::make_shared<any>(std::move(rshape));
// number of nodes who knows the shape.
ret.attrs[unknown_name] = std::make_shared<any>(num_unknown);
return ret;
}
NNVM_REGISTER_PASS(InferShape)
.describe("Infer the shape of each node entries.")
.set_body([](Graph ret) {
return InferAttr<TShape>(
std::move(ret), TShape(),
"FInferShape", "shape_inputs", "shape_attr_key",
"shape", "shape_num_unknown_nodes",
[](const TShape& s) { return s.ndim() == 0; },
nullptr);
})
.set_change_graph(false)
.provide_graph_attr("shape");
// inference fucntion for same type
inline bool SameType(const NodeAttrs& attrs,
std::vector<int> *iattr,
std::vector<int> *oattr) {
int def_v = -1;
for (int v : *oattr) {
if (v != -1) {
def_v = v; break;
}
}
if (def_v == -1) {
for (int v : *iattr) {
if (v != -1) {
def_v = v; break;
}
}
}
if (def_v == -1) return false;
for (int& v : *oattr) {
v = def_v;
}
for (int& v : *iattr) {
v = def_v;
}
return true;
}
NNVM_REGISTER_PASS(InferType)
.describe("Infer the dtype of each node entries.")
.set_body([](Graph ret) {
return InferAttr<int>(
std::move(ret), -1,
"FInferType", "dtype_inputs", "dtype_attr_key",
"dtype", "dtype_num_unknown_nodes",
[](const int t) { return t == -1; },
SameType);
})
.set_change_graph(false)
.provide_graph_attr("dtype");
DMLC_JSON_ENABLE_ANY(ShapeVector, list_shape);
DMLC_JSON_ENABLE_ANY(DTypeVector, list_int);
DMLC_JSON_ENABLE_ANY(size_t, size_t);
} // namespace
} // namespace pass
} // namespace nnvm
<commit_msg>error info (#69)<commit_after>/*!
* Copyright (c) 2016 by Contributors
* \file infer_shape.cc
* \brief Inference the shapes given existin information.
*/
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/graph_attr_types.h>
namespace nnvm {
namespace pass {
namespace {
template<typename AttrType, typename IsNone, typename FDefault>
Graph InferAttr(Graph &&ret,
const AttrType empty_val,
const char* infer_name,
const char* input_name,
const char* attr_key_name,
const char* attr_name,
const char* unknown_name,
IsNone fis_none,
FDefault fdefault) {
using AttrVector = std::vector<AttrType>;
const IndexedGraph& idx = ret.indexed_graph();
static auto& finfer_shape =
Op::GetAttr<FInferNodeEntryAttr<AttrType> >(infer_name);
static auto& backward_map =
Op::GetAttr<FBackwardOutToInIndex>("FBackwardOutToInIndex");
static auto& backward_in_grad =
Op::GetAttr<FBackwardInGradIndex>("FBackwardInGradIndex");
// reshape shape vector
AttrVector rshape;
if (ret.attrs.count(attr_name) != 0) {
rshape = ret.MoveCopyAttr<AttrVector>(attr_name);
} else {
rshape.resize(idx.num_node_entries(), empty_val);
}
if (ret.attrs.count(input_name) != 0) {
const AttrVector& shape_args = ret.GetAttr<AttrVector>(input_name);
CHECK_LE(shape_args.size(), idx.input_nodes().size())
<< "More provided shapes than number of arguments.";
for (size_t i = 0; i < shape_args.size(); ++i) {
rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i];
}
// erase the provided arguments
ret.attrs.erase(input_name);
}
std::string shape_attr_key;
if (ret.attrs.count(attr_key_name) != 0) {
shape_attr_key = ret.GetAttr<std::string>(attr_key_name);
// erase the provided arguments
ret.attrs.erase(attr_key_name);
}
// Temp space for shape inference.
std::vector<AttrType> ishape, oshape;
// inference step function for nid
auto infer_step = [&](uint32_t nid) {
const auto& inode = idx[nid];
const uint32_t num_inputs = inode.inputs.size();
const uint32_t num_outputs = inode.source->num_outputs();
if (inode.source->is_variable()) {
// Variable node. No operator. Only one output entry.
CHECK(inode.source->op() == nullptr);
CHECK_EQ(num_outputs, 1);
const uint32_t out_ent_id = idx.entry_id(nid, 0);
if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) {
auto it = inode.source->attrs.dict.find(shape_attr_key);
if (it != inode.source->attrs.dict.end()) {
std::istringstream is(it->second);
CHECK(is >> rshape[out_ent_id]) << "Invalid attribute";
}
}
} else if (backward_map.count(inode.source->op())) {
// Backward operator inference.
CHECK_GE(inode.control_deps.size(), 1)
<< "BackwardOp need to have control_deps to its forward op";
const IndexedGraph::Node& fnode = idx[inode.control_deps[0]];
// Inference the outputs of backward operator (equal to the inputs
// of its corresponding forward operator).
std::vector<uint32_t> out_map =
backward_map[inode.source->op()](inode.source->attrs);
for (size_t i = 0; i < out_map.size(); ++i) {
uint32_t in_id = out_map[i];
CHECK_LT(in_id, fnode.inputs.size());
rshape[idx.entry_id(nid, i)] =
rshape[idx.entry_id(fnode.inputs[in_id])];
}
if (backward_in_grad.count(inode.source->op())) {
std::vector<uint32_t> in_grad =
backward_in_grad[inode.source->op()](inode.source->attrs);
CHECK_LE(in_grad.size(), fnode.source->num_outputs());
for (size_t i = 0; i < in_grad.size(); ++i) {
uint32_t eid = idx.entry_id(inode.inputs[in_grad[i]]);
if (fis_none(rshape[eid])) {
rshape[eid] = rshape[idx.entry_id(inode.control_deps[0], i)];
}
}
}
} else {
bool forward_known = true;
// Forward operator inference.
ishape.resize(num_inputs, empty_val);
for (uint32_t i = 0; i < ishape.size(); ++i) {
ishape[i] = rshape[idx.entry_id(inode.inputs[i])];
if (fis_none(ishape[i])) forward_known = false;
}
oshape.resize(num_outputs, empty_val);
for (uint32_t i = 0; i < oshape.size(); ++i) {
oshape[i] = rshape[idx.entry_id(nid, i)];
if (fis_none(oshape[i])) forward_known = false;
}
if (!forward_known) {
auto finfer = finfer_shape.get(inode.source->op(), fdefault);
CHECK(finfer != nullptr)
<< "Attribute " << infer_name
<< " is not registed by op " << inode.source->op()->name;
// Call inference function of the operator.
try {
forward_known = finfer(inode.source->attrs, &ishape, &oshape);
} catch (const std::exception& e) {
throw dmlc::Error(e.what() + std::string(" with ") + inode.source->attrs.name);
}
}
// Save to the result map.
for (uint32_t i = 0; i < num_inputs; ++i) {
rshape[idx.entry_id(inode.inputs[i])] = ishape[i];
}
for (uint32_t i = 0; i < num_outputs; ++i) {
rshape[idx.entry_id(nid, i)] = oshape[i];
}
}
};
size_t num_unknown = 0;
const int kMaxStep = 3;
for (int i = 0; i < kMaxStep; ++i) {
if (i % 2 == 0) {
for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
infer_step(nid);
}
} else {
// backward inference
for (uint32_t i = idx.num_nodes(); i != 0; --i) {
infer_step(i - 1);
}
}
num_unknown = 0;
for (size_t i = 0; i < idx.num_node_entries(); ++i) {
if (fis_none(rshape[i])) ++num_unknown;
}
if (num_unknown == 0) break;
}
// set the shapes
ret.attrs[attr_name] = std::make_shared<any>(std::move(rshape));
// number of nodes who knows the shape.
ret.attrs[unknown_name] = std::make_shared<any>(num_unknown);
return ret;
}
NNVM_REGISTER_PASS(InferShape)
.describe("Infer the shape of each node entries.")
.set_body([](Graph ret) {
return InferAttr<TShape>(
std::move(ret), TShape(),
"FInferShape", "shape_inputs", "shape_attr_key",
"shape", "shape_num_unknown_nodes",
[](const TShape& s) { return s.ndim() == 0; },
nullptr);
})
.set_change_graph(false)
.provide_graph_attr("shape");
// inference fucntion for same type
inline bool SameType(const NodeAttrs& attrs,
std::vector<int> *iattr,
std::vector<int> *oattr) {
int def_v = -1;
for (int v : *oattr) {
if (v != -1) {
def_v = v; break;
}
}
if (def_v == -1) {
for (int v : *iattr) {
if (v != -1) {
def_v = v; break;
}
}
}
if (def_v == -1) return false;
for (int& v : *oattr) {
v = def_v;
}
for (int& v : *iattr) {
v = def_v;
}
return true;
}
NNVM_REGISTER_PASS(InferType)
.describe("Infer the dtype of each node entries.")
.set_body([](Graph ret) {
return InferAttr<int>(
std::move(ret), -1,
"FInferType", "dtype_inputs", "dtype_attr_key",
"dtype", "dtype_num_unknown_nodes",
[](const int t) { return t == -1; },
SameType);
})
.set_change_graph(false)
.provide_graph_attr("dtype");
DMLC_JSON_ENABLE_ANY(ShapeVector, list_shape);
DMLC_JSON_ENABLE_ANY(DTypeVector, list_int);
DMLC_JSON_ENABLE_ANY(size_t, size_t);
} // namespace
} // namespace pass
} // namespace nnvm
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include "hpp/core/path-projector/global.hh"
#include <hpp/util/debug.hh>
#include <hpp/model/configuration.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/interpolated-path.hh>
#include <hpp/core/config-projector.hh>
#include <limits>
#include <queue>
#include <stack>
namespace hpp {
namespace core {
namespace pathProjector {
Global::Global (const DistancePtr_t& distance,
const SteeringMethodPtr_t& steeringMethod,
value_type step) :
PathProjector (distance, steeringMethod), step_ (step),
alphaMin (0.2), alphaMax (0.95)
{}
bool Global::impl_apply (const PathPtr_t& path,
PathPtr_t& proj) const
{
assert (path);
bool success = false;
PathVectorPtr_t pv = HPP_DYNAMIC_PTR_CAST (PathVector, path);
if (!pv) {
if (!path->constraints()
|| !path->constraints()->configProjector()) {
proj = path;
success = true;
} else {
success = project (path, proj);
}
} else {
PathVectorPtr_t res = PathVector::create
(pv->outputSize (), pv->outputDerivativeSize ());
PathPtr_t part;
success = true;
for (size_t i = 0; i < pv->numberPaths (); i++) {
if (!apply (pv->pathAtRank (i), part)) {
// We add the path only if part is not NULL and:
// - either its length is not zero,
// - or it's not the first one.
if (part && (part->length () > 0 || i == 0)) {
res->appendPath (part);
}
success = false;
break;
}
res->appendPath (part);
}
proj = res;
}
assert (proj);
assert ((proj->initial () - path->initial ()).isZero());
assert (!success || (proj->end () - path->end ()).isZero());
return success;
}
bool Global::project (const PathPtr_t& path, PathPtr_t& proj) const
{
Configs_t cfgs;
ConfigProjector& p = *path->constraints ()->configProjector ();
initialConfigList (path, cfgs);
if (cfgs.size() == 2) { // Shorter than step_
proj = path;
return true;
}
assert ((cfgs.back () - path->end ()).isZero ());
Bools_t projected (cfgs.size () - 2, false);
Alphas_t alphas (cfgs.size () - 2, alphaMin);
Lengths_t lengths (cfgs.size () - 1, 0);
Configs_t::iterator last = --(cfgs.end());
std::size_t nbIter = 0;
const std::size_t maxIter = p.maxIterations ();
const std::size_t maxCfgNum =
2 + (std::size_t)(10 * path->length() / step_);
hppDout (info, "start with " << cfgs.size () << " configs");
while (!projectOneStep (p, cfgs, last, projected, lengths, alphas)) {
assert ((cfgs.back () - path->end ()).isZero ());
if (cfgs.size() < maxCfgNum) {
const size_type newCs =
reinterpolate (p.robot(), cfgs, last, projected, lengths, alphas,
step_);
if (newCs > 0) {
nbIter = 0;
hppDout (info, "Added " << newCs << " configs. Cur / Max = "
<< cfgs.size() << '/' << maxCfgNum);
} else if (newCs < 0) {
hppDout (info, "Removed " << -newCs << " configs. Cur / Max = "
<< cfgs.size() << '/' << maxCfgNum);
}
}
nbIter++;
if (nbIter > maxIter) break;
}
// Build the projection
return createPath (p.robot(), path->constraints(),
cfgs, projected, lengths, proj);
}
bool Global::projectOneStep (ConfigProjector& p,
Configs_t& q, Configs_t::iterator& last,
Bools_t& b, Lengths_t& l, Alphas_t& a) const
{
/// First and last should not be updated
const Configs_t::iterator begin = ++(q.begin ());
const Configs_t::iterator end = --(q.end ());
Bools_t ::iterator itB = (b.begin ());
Alphas_t ::iterator itA = (a.begin ());
Lengths_t::iterator itL = (l.begin ());
Configs_t::iterator itCp = (q.begin ());
bool allAreSatisfied = true;
bool curUpdated = false, prevUpdated = false;
/// Eigen matrices storage order defaults to column major.
Eigen::Matrix <value_type, Eigen::Dynamic, 2>
oldQ (p.robot()->configSize(),2);
Eigen::Matrix <value_type, Eigen::Dynamic, 2>
dq (p.robot()->numberDof(),2);
dq.setZero();
vector_t qMinusQPrev (p.robot()->numberDof());
size_type iCol = 0;
size_type iNCol = (iCol+1)%2;
for (Configs_t::iterator it = begin; it != last; ++it) {
if (!*itB) {
oldQ.col(iCol) = *it;
*itB = p.oneStep (*it, dq.col(iCol),*itA);
*itA = alphaMax - 0.8 * (alphaMax - *itA);
allAreSatisfied = allAreSatisfied && *itB;
curUpdated = true;
if (prevUpdated) {
/// Detect large increase in size
hpp::model::difference (p.robot(), oldQ.col(iCol), oldQ.col(iNCol), qMinusQPrev);
const vector_t deltaDQ = dq.col(iCol) - dq.col(iNCol);
const value_type N2 = qMinusQPrev.squaredNorm();
if (sqrt(N2) < Eigen::NumTraits<value_type>::dummy_precision ()) {
hppDout (error, "The two config should be removed:"
<< "\noldQ = " << oldQ.transpose()
<< "\nqMinusQPrev = " << qMinusQPrev.transpose()
<< "\nDistance is " << d (oldQ.col(iCol), oldQ.col(iNCol))
<< "\nand in mem " << *itL
);
} else {
const value_type alphaSquare = 1 - 2 * qMinusQPrev.dot(deltaDQ) / N2 + qMinusQPrev.squaredNorm() / N2;
// alpha > 4 => the distance between the two points has been
// mutiplied by more than 4.
if (alphaSquare > 16) {
hppDout (error, "alpha^2 = " << alphaSquare
<< "\nqMinusQPrev = " << qMinusQPrev.transpose()
<< "\ndeltaDQ = " << deltaDQ.transpose());
last = it; --last;
return false;
}
}
const value_type limitCos = 0.5;
vector_t dots = dq.colwise().normalized ().transpose() * qMinusQPrev.normalized();
// Check if both updates are pointing outward
if (dots[iCol] > limitCos && dots[iNCol] < - limitCos) {
hppDout (error, "Descent step is going in opposite direction: "
<< dots << ". It is likely a discontinuity.");
last = it; --last;
return false;
}
iNCol = iCol;
iCol = (iCol+1)%2;
}
}
if (prevUpdated || curUpdated)
*itL = d (*itCp, *it);
prevUpdated = curUpdated;
curUpdated = false;
++itCp;
++itB;
++itL;
}
if (prevUpdated)
*itL = d (*itCp, *end);
return allAreSatisfied;
}
size_type Global::reinterpolate (const DevicePtr_t& robot,
Configs_t& q, const Configs_t::iterator& last,
Bools_t& b, Lengths_t& l, Alphas_t& a,
const value_type& maxDist) const
{
Configs_t::iterator begin = ++(q.begin ());
Configs_t::iterator end = last; ++end;
Bools_t ::iterator itB = (b.begin ());
Alphas_t ::iterator itA = (a.begin ());
Lengths_t::iterator itL = (l.begin ());
Configs_t::iterator itCp = (q.begin ());
Configuration_t newQ (robot->configSize ());
size_type nbNewC = 0;
for (Configs_t::iterator it = begin; it != last; ++it) {
if (*itL > maxDist) {
++nbNewC;
hpp::model::interpolate (robot, *itCp, *it, 0.5, newQ);
// FIXME: make sure the iterator are valid after insertion
// Insert new respective elements
it = q.insert (it, newQ);
itB = b.insert (itB, false);
itA = a.insert (itA, alphaMin);
itL = l.insert (itL, d (*itCp, *it));
// Update length after
Configs_t::iterator itNC = it; ++itNC;
Lengths_t::iterator itNL = itL; ++itNL;
*itNL = d (*it, *itNC);
// FIXME: End has changed ?
end = q.end();
it = itCp;
continue;
} else if (*itL < maxDist * 1e-2) {
nbNewC--;
hppDout (warning, "Removing configuration: " << it->transpose()
<< "\nToo close to: " << itCp->transpose()
);
// The distance to the previous point is very small.
// This point can safely be removed.
it = q.erase (it);
itB = b.erase (itB);
itA = a.erase (itA);
itL = l.erase (itL);
// Update length
*itL = d (*itCp, *it);
it = itCp;
continue;
}
++itCp;
++itB;
++itA;
++itL;
}
return nbNewC;
}
bool Global::createPath (const DevicePtr_t& robot,
const ConstraintSetPtr_t& constraint,
const Configs_t& q, const Configs_t::iterator&,
const Bools_t& b, const Lengths_t& l, PathPtr_t& result) const
{
/// Compute total length
value_type length = 0;
Lengths_t::const_iterator itL = (l.begin ());
Bools_t ::const_iterator itB = (b.begin ());
Configs_t::const_iterator itCl = (q.begin ());
bool fullyProjected = true;
for (; itB != b.end (); ++itB) {
if (!*itB || *itL > step_) {
fullyProjected = false;
break;
}
length += *itL;
++itCl;
++itL;
}
if (fullyProjected) {
length += *itL;
++itCl;
++itL;
assert (itL == l.end ());
}
InterpolatedPathPtr_t out = InterpolatedPath::create
(robot, q.front(), *itCl, length, constraint);
if (itCl != q.begin ()) {
length = 0;
Lengths_t::const_iterator itL = (l.begin ());
Configs_t::const_iterator begin = ++(q.begin ());
for (Configs_t::const_iterator it = begin; it != itCl; ++it) {
length += *itL;
out->insert (length, *it);
++itL;
}
} else {
hppDout (info, "Path of length 0");
assert (!fullyProjected);
}
result = out;
hppDout (info, "Projection succeeded ? " << fullyProjected);
return fullyProjected;
}
void Global::initialConfigList (const PathPtr_t& path,
Configs_t& cfgs) const
{
InterpolatedPathPtr_t ip =
HPP_DYNAMIC_PTR_CAST (InterpolatedPath, path);
if (ip) {
// Get the waypoint of ip
const InterpolatedPath::InterpolationPoints_t& ips =
ip->interpolationPoints();
for (InterpolatedPath::InterpolationPoints_t::const_iterator it =
ips.begin (); it != ips.end (); ++it) {
cfgs.push_back (it->second);
}
} else {
const value_type L = path->length ();
Configuration_t q (path->outputSize ());
cfgs.push_back (path->initial ());
// Factor 0.99 is to ensure that the distance between two consecutives
// configurations will be smaller that step_
for (value_type t = step_; t < L; t += step_*0.99) {
// Interpolate without taking care of the constraints
// FIXME: Path must not be a PathVector otherwise the constraints
// are applied.
path->at (t, q);
cfgs.push_back (q);
}
cfgs.push_back (path->end ());
}
}
} // namespace pathProjector
} // namespace core
} // namespace hpp
<commit_msg>Add banchmark output to pathProjector::Global<commit_after>// Copyright (c) 2015, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include "hpp/core/path-projector/global.hh"
#include <hpp/util/debug.hh>
#include <hpp/util/timer.hh>
#include <hpp/model/configuration.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/interpolated-path.hh>
#include <hpp/core/config-projector.hh>
#include <limits>
#include <queue>
#include <stack>
namespace hpp {
namespace core {
namespace pathProjector {
namespace {
HPP_DEFINE_TIMECOUNTER (globalPathProjector_initCfgList);
HPP_DEFINE_TIMECOUNTER (globalPathProjector_projOneStep);
HPP_DEFINE_TIMECOUNTER (globalPathProjector_reinterpolate);
HPP_DEFINE_TIMECOUNTER (globalPathProjector_createPath);
}
Global::Global (const DistancePtr_t& distance,
const SteeringMethodPtr_t& steeringMethod,
value_type step) :
PathProjector (distance, steeringMethod), step_ (step),
alphaMin (0.2), alphaMax (0.95)
{}
bool Global::impl_apply (const PathPtr_t& path,
PathPtr_t& proj) const
{
assert (path);
bool success = false;
PathVectorPtr_t pv = HPP_DYNAMIC_PTR_CAST (PathVector, path);
if (!pv) {
if (!path->constraints()
|| !path->constraints()->configProjector()) {
proj = path;
success = true;
} else {
success = project (path, proj);
}
} else {
PathVectorPtr_t res = PathVector::create
(pv->outputSize (), pv->outputDerivativeSize ());
PathPtr_t part;
success = true;
for (size_t i = 0; i < pv->numberPaths (); i++) {
if (!apply (pv->pathAtRank (i), part)) {
// We add the path only if part is not NULL and:
// - either its length is not zero,
// - or it's not the first one.
if (part && (part->length () > 0 || i == 0)) {
res->appendPath (part);
}
success = false;
break;
}
res->appendPath (part);
}
proj = res;
}
assert (proj);
assert ((proj->initial () - path->initial ()).isZero());
assert (!success || (proj->end () - path->end ()).isZero());
return success;
}
bool Global::project (const PathPtr_t& path, PathPtr_t& proj) const
{
Configs_t cfgs;
ConfigProjector& p = *path->constraints ()->configProjector ();
HPP_START_TIMECOUNTER(globalPathProjector_initCfgList);
initialConfigList (path, cfgs);
if (cfgs.size() == 2) { // Shorter than step_
proj = path;
return true;
}
assert ((cfgs.back () - path->end ()).isZero ());
HPP_STOP_AND_DISPLAY_TIMECOUNTER(globalPathProjector_initCfgList);
Bools_t projected (cfgs.size () - 2, false);
Alphas_t alphas (cfgs.size () - 2, alphaMin);
Lengths_t lengths (cfgs.size () - 1, 0);
Configs_t::iterator last = --(cfgs.end());
std::size_t nbIter = 0;
const std::size_t maxIter = p.maxIterations ();
const std::size_t maxCfgNum =
2 + (std::size_t)(10 * path->length() / step_);
hppDout (info, "start with " << cfgs.size () << " configs");
while (!projectOneStep (p, cfgs, last, projected, lengths, alphas)) {
assert ((cfgs.back () - path->end ()).isZero ());
if (cfgs.size() < maxCfgNum) {
const size_type newCs =
reinterpolate (p.robot(), cfgs, last, projected, lengths, alphas,
step_);
if (newCs > 0) {
nbIter = 0;
hppDout (info, "Added " << newCs << " configs. Cur / Max = "
<< cfgs.size() << '/' << maxCfgNum);
} else if (newCs < 0) {
hppDout (info, "Removed " << -newCs << " configs. Cur / Max = "
<< cfgs.size() << '/' << maxCfgNum);
}
}
nbIter++;
if (nbIter > maxIter) break;
}
HPP_DISPLAY_TIMECOUNTER(globalPathProjector_projOneStep);
HPP_DISPLAY_TIMECOUNTER(globalPathProjector_reinterpolate);
// Build the projection
HPP_START_TIMECOUNTER (globalPathProjector_createPath);
bool ret = createPath (p.robot(), path->constraints(),
cfgs, last, projected, lengths, proj);
HPP_STOP_AND_DISPLAY_TIMECOUNTER (globalPathProjector_createPath);
return ret;
}
bool Global::projectOneStep (ConfigProjector& p,
Configs_t& q, Configs_t::iterator& last,
Bools_t& b, Lengths_t& l, Alphas_t& a) const
{
HPP_START_TIMECOUNTER(globalPathProjector_projOneStep);
/// First and last should not be updated
const Configs_t::iterator begin = ++(q.begin ());
const Configs_t::iterator end = --(q.end ());
Bools_t ::iterator itB = (b.begin ());
Alphas_t ::iterator itA = (a.begin ());
Lengths_t::iterator itL = (l.begin ());
Configs_t::iterator itCp = (q.begin ());
bool allAreSatisfied = true;
bool curUpdated = false, prevUpdated = false;
/// Eigen matrices storage order defaults to column major.
Eigen::Matrix <value_type, Eigen::Dynamic, 2>
oldQ (p.robot()->configSize(),2);
Eigen::Matrix <value_type, Eigen::Dynamic, 2>
dq (p.robot()->numberDof(),2);
dq.setZero();
vector_t qMinusQPrev (p.robot()->numberDof());
size_type iCol = 0;
size_type iNCol = (iCol+1)%2;
for (Configs_t::iterator it = begin; it != last; ++it) {
if (!*itB) {
oldQ.col(iCol) = *it;
*itB = p.oneStep (*it, dq.col(iCol),*itA);
*itA = alphaMax - 0.8 * (alphaMax - *itA);
allAreSatisfied = allAreSatisfied && *itB;
curUpdated = true;
if (prevUpdated) {
/// Detect large increase in size
hpp::model::difference (p.robot(), oldQ.col(iCol), oldQ.col(iNCol), qMinusQPrev);
const vector_t deltaDQ = dq.col(iCol) - dq.col(iNCol);
const value_type N2 = qMinusQPrev.squaredNorm();
if (sqrt(N2) < Eigen::NumTraits<value_type>::dummy_precision ()) {
hppDout (error, "The two config should be removed:"
<< "\noldQ = " << oldQ.transpose()
<< "\nqMinusQPrev = " << qMinusQPrev.transpose()
<< "\nDistance is " << d (oldQ.col(iCol), oldQ.col(iNCol))
<< "\nand in mem " << *itL
);
} else {
const value_type alphaSquare = 1 - 2 * qMinusQPrev.dot(deltaDQ) / N2 + qMinusQPrev.squaredNorm() / N2;
// alpha > 4 => the distance between the two points has been
// mutiplied by more than 4.
if (alphaSquare > 16) {
hppDout (error, "alpha^2 = " << alphaSquare
<< "\nqMinusQPrev = " << qMinusQPrev.transpose()
<< "\ndeltaDQ = " << deltaDQ.transpose());
last = it; --last;
return false;
}
}
const value_type limitCos = 0.5;
vector_t dots = dq.colwise().normalized ().transpose() * qMinusQPrev.normalized();
// Check if both updates are pointing outward
if (dots[iCol] > limitCos && dots[iNCol] < - limitCos) {
hppDout (error, "Descent step is going in opposite direction: "
<< dots << ". It is likely a discontinuity.");
last = it; --last;
return false;
}
iNCol = iCol;
iCol = (iCol+1)%2;
}
}
if (prevUpdated || curUpdated)
*itL = d (*itCp, *it);
prevUpdated = curUpdated;
curUpdated = false;
++itCp;
++itB;
++itL;
}
if (prevUpdated)
*itL = d (*itCp, *end);
HPP_STOP_TIMECOUNTER(globalPathProjector_projOneStep);
return allAreSatisfied;
}
size_type Global::reinterpolate (const DevicePtr_t& robot,
Configs_t& q, const Configs_t::iterator& last,
Bools_t& b, Lengths_t& l, Alphas_t& a,
const value_type& maxDist) const
{
HPP_START_TIMECOUNTER(globalPathProjector_reinterpolate);
Configs_t::iterator begin = ++(q.begin ());
Configs_t::iterator end = last; ++end;
Bools_t ::iterator itB = (b.begin ());
Alphas_t ::iterator itA = (a.begin ());
Lengths_t::iterator itL = (l.begin ());
Configs_t::iterator itCp = (q.begin ());
Configuration_t newQ (robot->configSize ());
size_type nbNewC = 0;
for (Configs_t::iterator it = begin; it != last; ++it) {
if (*itL > maxDist) {
++nbNewC;
hpp::model::interpolate (robot, *itCp, *it, 0.5, newQ);
// FIXME: make sure the iterator are valid after insertion
// Insert new respective elements
it = q.insert (it, newQ);
itB = b.insert (itB, false);
itA = a.insert (itA, alphaMin);
itL = l.insert (itL, d (*itCp, *it));
// Update length after
Configs_t::iterator itNC = it; ++itNC;
Lengths_t::iterator itNL = itL; ++itNL;
*itNL = d (*it, *itNC);
// FIXME: End has changed ?
end = q.end();
it = itCp;
continue;
} else if (*itL < maxDist * 1e-2) {
nbNewC--;
hppDout (warning, "Removing configuration: " << it->transpose()
<< "\nToo close to: " << itCp->transpose()
);
// The distance to the previous point is very small.
// This point can safely be removed.
it = q.erase (it);
itB = b.erase (itB);
itA = a.erase (itA);
itL = l.erase (itL);
// Update length
*itL = d (*itCp, *it);
it = itCp;
continue;
}
++itCp;
++itB;
++itA;
++itL;
}
HPP_STOP_TIMECOUNTER(globalPathProjector_reinterpolate);
return nbNewC;
}
bool Global::createPath (const DevicePtr_t& robot,
const ConstraintSetPtr_t& constraint,
const Configs_t& q, const Configs_t::iterator&,
const Bools_t& b, const Lengths_t& l, PathPtr_t& result) const
{
/// Compute total length
value_type length = 0;
Lengths_t::const_iterator itL = (l.begin ());
Bools_t ::const_iterator itB = (b.begin ());
Configs_t::const_iterator itCl = (q.begin ());
bool fullyProjected = true;
for (; itB != b.end (); ++itB) {
if (!*itB || *itL > step_) {
fullyProjected = false;
break;
}
length += *itL;
++itCl;
++itL;
}
if (fullyProjected) {
length += *itL;
++itCl;
++itL;
assert (itL == l.end ());
}
InterpolatedPathPtr_t out = InterpolatedPath::create
(robot, q.front(), *itCl, length, constraint);
if (itCl != q.begin ()) {
length = 0;
Lengths_t::const_iterator itL = (l.begin ());
Configs_t::const_iterator begin = ++(q.begin ());
for (Configs_t::const_iterator it = begin; it != itCl; ++it) {
length += *itL;
out->insert (length, *it);
++itL;
}
} else {
hppDout (info, "Path of length 0");
assert (!fullyProjected);
}
result = out;
hppDout (info, "Projection succeeded ? " << fullyProjected);
return fullyProjected;
}
void Global::initialConfigList (const PathPtr_t& path,
Configs_t& cfgs) const
{
InterpolatedPathPtr_t ip =
HPP_DYNAMIC_PTR_CAST (InterpolatedPath, path);
if (ip) {
// Get the waypoint of ip
const InterpolatedPath::InterpolationPoints_t& ips =
ip->interpolationPoints();
for (InterpolatedPath::InterpolationPoints_t::const_iterator it =
ips.begin (); it != ips.end (); ++it) {
cfgs.push_back (it->second);
}
} else {
const value_type L = path->length ();
Configuration_t q (path->outputSize ());
cfgs.push_back (path->initial ());
// Factor 0.99 is to ensure that the distance between two consecutives
// configurations will be smaller that step_
for (value_type t = step_; t < L; t += step_*0.99) {
// Interpolate without taking care of the constraints
// FIXME: Path must not be a PathVector otherwise the constraints
// are applied.
path->at (t, q);
cfgs.push_back (q);
}
cfgs.push_back (path->end ());
}
}
} // namespace pathProjector
} // namespace core
} // namespace hpp
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/***********************************************************************
*
* Print declarations from the condor config files, condor_config and
* condor_config.local. Declarations in files specified by
* LOCAL_CONFIG_FILE override those in the global config file, so this
* prints the same declarations found by condor programs using the
* config() routine.
*
* In addition, the configuration of remote machines can be queried.
* You can specify either a name or sinful string you want to connect
* to, what kind of daemon you want to query, and what pool to query to
* find the specified daemon.
*
***********************************************************************/
#include "condor_common.h"
#include "condor_config.h"
#include "condor_io.h"
#include "condor_uid.h"
#include "match_prefix.h"
#include "string_list.h"
#include "get_daemon_addr.h"
#include "daemon_types.h"
char *MyName;
char *mySubSystem = NULL;
StringList params;
daemonType dt = DT_MASTER;
// The pure-tools (PureCoverage, Purify, etc) spit out a bunch of
// stuff to stderr, which is where we normally put our error
// messages. To enable config_val.test to produce easily readable
// output, even with pure-tools, we just write everything to stdout.
#if defined( PURE_DEBUG )
# define stderr stdout
#endif
enum PrintType {CONDOR_OWNER, CONDOR_TILDE, CONDOR_NONE};
// On some systems, the output from config_val sometimes doesn't show
// up unless we explicitly flush before we exit.
void
my_exit( int status )
{
fflush( stdout );
fflush( stderr );
exit( status );
}
void
usage()
{
fprintf( stderr, "Usage: %s [options] variable [variable] ...\n", MyName );
fprintf( stderr, " Valid options are:\n" );
fprintf( stderr, " -name daemon_name\t(query the specified daemon for its configuration)\n" );
fprintf( stderr, " -pool hostname\t(use the given central manager to find daemons)\n" );
fprintf( stderr, " -address <ip:port>\t(connect to the given ip/port)\n" );
fprintf( stderr, " -master\t\t(query the master [default])\n" );
fprintf( stderr, " -schedd\t\t(query the schedd)\n" );
fprintf( stderr, " -startd\t\t(query the startd)\n" );
fprintf( stderr, " -collector\t\t(query the collector)\n" );
fprintf( stderr, " -negotiator\t\t(query the negotiator)\n" );
my_exit( 1 );
}
char* GetRemoteParam( char*, char*, char*, char* );
main( int argc, char* argv[] )
{
char *value, *tmp, *host = NULL;
char *addr = NULL, *name = NULL, *pool = NULL;
int i;
PrintType pt = CONDOR_NONE;
MyName = argv[0];
for( i=1; i<argc; i++ ) {
if( match_prefix( argv[i], "-host" ) ) {
if( argv[i + 1] ) {
host = strdup( argv[++i] );
} else {
usage();
}
} else if( match_prefix( argv[i], "-name" ) ) {
if( argv[i + 1] ) {
i++;
if( (tmp = get_daemon_name(argv[i])) ) {
name = strdup( tmp );
} else {
fprintf( stderr, "%s: unknown host %s\n", MyName,
get_host_part(argv[i]) );
my_exit( 1 );
}
} else {
usage();
}
} else if( match_prefix( argv[i], "-address" ) ) {
if( argv[i + 1] ) {
i++;
if( is_valid_sinful(argv[i]) ) {
addr = strdup( argv[i] );
} else {
fprintf( stderr, "%s: invalid address %s\n"
"Address must be of the form \"<111.222.333.444:555>\n"
" where 111.222.333.444 is the ip address and"
"555 is the port\n you wish to connect to (the"
"punctuation is important.\n", MyName, argv[i] );
my_exit( 1 );
}
} else {
usage();
}
} else if( match_prefix( argv[i], "-pool" ) ) {
if( argv[i + 1] ) {
i++;
if( (tmp = get_daemon_name(argv[i])) ) {
pool = strdup( tmp );
} else {
fprintf( stderr, "%s: unknown host %s\n", MyName,
get_host_part(argv[i]) );
my_exit( 1 );
}
} else {
usage();
}
} else if( match_prefix( argv[i], "-owner" ) ) {
pt = CONDOR_OWNER;
} else if( match_prefix( argv[i], "-tilde" ) ) {
pt = CONDOR_TILDE;
} else if( match_prefix( argv[i], "-master" ) ) {
dt = DT_MASTER;
} else if( match_prefix( argv[i], "-schedd" ) ) {
dt = DT_SCHEDD;
} else if( match_prefix( argv[i], "-startd" ) ) {
dt = DT_STARTD;
} else if( match_prefix( argv[i], "-collector" ) ) {
dt = DT_COLLECTOR;
} else if( match_prefix( argv[i], "-negotiator" ) ) {
dt = DT_NEGOTIATOR;
} else if( match_prefix( argv[i], "-" ) ) {
usage();
} else {
params.append( strdup( argv[i] ) );
}
}
// If we didn't get told what subsystem we should use, set it
// to "TOOL".
if( !mySubSystem ) {
mySubSystem = strdup( "TOOL" );
}
// Want to do this before we try to find the address of a
// remote daemon, since if there's no -pool option, we need to
// param() for the COLLECTOR_HOST to contact.
if( host ) {
config_host( 0, host );
} else {
config( 0 );
}
if( name || pool ) {
addr = get_daemon_addr( dt, name, pool );
if( ! addr ) {
fprintf( stderr, "Can't find address for %s %s\n",
daemon_string(dt), name );
fprintf( stderr, "Perhaps you need to query another pool.\n" );
my_exit( 1 );
}
}
if( pt == CONDOR_TILDE ) {
if( (tmp = get_tilde()) ) {
printf( "%s\n", tmp );
my_exit( 0 );
} else {
fprintf( stderr,
"Error: Specified -tilde but can't find %s\n",
"condor's home directory." );
my_exit( 1 );
}
}
if( pt == CONDOR_OWNER ) {
printf( "%s\n", get_condor_username() );
my_exit( 0 );
}
params.rewind();
if( ! params.number() ) {
usage();
}
while( (tmp = params.next()) ) {
if( name || pool || addr ) {
value = GetRemoteParam( name, addr, pool, tmp );
} else {
value = param( tmp );
}
if( value == NULL ) {
fprintf(stderr, "Not defined: %s\n", tmp);
my_exit( 1 );
} else {
printf("%s\n", value);
free( value );
}
}
my_exit( 0 );
}
char*
GetRemoteParam( char* name, char* addr, char* pool, char* param_name )
{
ReliSock s;
s.timeout( 30 );
char *val = NULL;
int cmd = CONFIG_VAL;
if( !name ) {
name = "";
}
if( ! s.connect( addr, 0 ) ) {
fprintf( stderr, "Can't connect to %s on %s %s\n",
daemon_string(dt), name, addr );
my_exit(1);
}
s.encode();
if( !s.code(cmd) ) {
fprintf( stderr, "Can't send command CONFIG_VAL (%d)\n", cmd );
return NULL;
}
if( !s.code(param_name) ) {
fprintf( stderr, "Can't send request (%s)\n", param_name );
return NULL;
}
if( !s.end_of_message() ) {
fprintf( stderr, "Can't send end of message\n" );
return NULL;
}
s.decode();
if( !s.code(val) ) {
fprintf( stderr, "Can't receive reply from %s on %s %s\n",
daemon_string(dt), name, addr );
return NULL;
}
if( !s.end_of_message() ) {
fprintf( stderr, "Can't receive end of message\n" );
return NULL;
}
return val;
}
<commit_msg>Added -set, -unset, -rset, and -runset options. See condor_daemon_core.V6/README.config for more details.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/***********************************************************************
*
* Print declarations from the condor config files, condor_config and
* condor_config.local. Declarations in files specified by
* LOCAL_CONFIG_FILE override those in the global config file, so this
* prints the same declarations found by condor programs using the
* config() routine.
*
* In addition, the configuration of remote machines can be queried.
* You can specify either a name or sinful string you want to connect
* to, what kind of daemon you want to query, and what pool to query to
* find the specified daemon.
*
***********************************************************************/
#include "condor_common.h"
#include "condor_config.h"
#include "condor_io.h"
#include "condor_uid.h"
#include "match_prefix.h"
#include "string_list.h"
#include "get_daemon_addr.h"
#include "daemon_types.h"
char *MyName;
char *mySubSystem = NULL;
StringList params;
daemonType dt = DT_MASTER;
// The pure-tools (PureCoverage, Purify, etc) spit out a bunch of
// stuff to stderr, which is where we normally put our error
// messages. To enable config_val.test to produce easily readable
// output, even with pure-tools, we just write everything to stdout.
#if defined( PURE_DEBUG )
# define stderr stdout
#endif
enum PrintType {CONDOR_OWNER, CONDOR_TILDE, CONDOR_NONE};
enum ModeType {CONDOR_QUERY, CONDOR_SET, CONDOR_UNSET,
CONDOR_RUNTIME_SET, CONDOR_RUNTIME_UNSET};
// On some systems, the output from config_val sometimes doesn't show
// up unless we explicitly flush before we exit.
void
my_exit( int status )
{
fflush( stdout );
fflush( stderr );
exit( status );
}
void
usage()
{
fprintf( stderr, "Usage: %s [options] variable [variable] ...\n", MyName );
fprintf( stderr, " or: %s [options] -set variable value ...\n",
MyName );
fprintf( stderr, " or: %s [options] -rset variable value ...\n",
MyName );
fprintf( stderr, " or: %s [options] -unset variable ...\n",
MyName );
fprintf( stderr, " or: %s [options] -runset variable ...\n",
MyName );
fprintf( stderr, " or: %s [options] -tilde\n", MyName );
fprintf( stderr, " or: %s [options] -owner\n", MyName );
fprintf( stderr, "\n Valid options are:\n" );
fprintf( stderr, " -name daemon_name\t(query the specified daemon for its configuration)\n" );
fprintf( stderr, " -pool hostname\t(use the given central manager to find daemons)\n" );
fprintf( stderr, " -address <ip:port>\t(connect to the given ip/port)\n" );
fprintf( stderr, " -host hostname\t(connect to the given hostname)\n" );
fprintf( stderr, " -set\t\t\t(set a persistent config file expression)\n" );
fprintf( stderr, " -rset\t\t(set a runtime config file expression\n" );
fprintf( stderr, " -unset\t\t(unset a persistent config file expression)\n" );
fprintf( stderr, " -runset\t\t(unset a runtime config file expression)\n" );
fprintf( stderr, " -master\t\t(query the master [default])\n" );
fprintf( stderr, " -schedd\t\t(query the schedd)\n" );
fprintf( stderr, " -startd\t\t(query the startd)\n" );
fprintf( stderr, " -collector\t\t(query the collector)\n" );
fprintf( stderr, " -negotiator\t\t(query the negotiator)\n" );
fprintf( stderr, " -tilde\t\t(return the path to the Condor home directory)\n" );
fprintf( stderr, " -owner\t\t(return the owner of the condor_config_val process)\n" );
my_exit( 1 );
}
char* GetRemoteParam( char*, char*, char*, char* );
void SetRemoteParam( char*, char*, char*, char*, char*, ModeType );
main( int argc, char* argv[] )
{
char *value, *tmp, *host = NULL;
char *addr = NULL, *name = NULL, *pool = NULL;
int i;
PrintType pt = CONDOR_NONE;
ModeType mt = CONDOR_QUERY;
MyName = argv[0];
for( i=1; i<argc; i++ ) {
if( match_prefix( argv[i], "-host" ) ) {
if( argv[i + 1] ) {
host = strdup( argv[++i] );
} else {
usage();
}
} else if( match_prefix( argv[i], "-name" ) ) {
if( argv[i + 1] ) {
i++;
if( (tmp = get_daemon_name(argv[i])) ) {
name = strdup( tmp );
} else {
fprintf( stderr, "%s: unknown host %s\n", MyName,
get_host_part(argv[i]) );
my_exit( 1 );
}
} else {
usage();
}
} else if( match_prefix( argv[i], "-address" ) ) {
if( argv[i + 1] ) {
i++;
if( is_valid_sinful(argv[i]) ) {
addr = strdup( argv[i] );
} else {
fprintf( stderr, "%s: invalid address %s\n"
"Address must be of the form \"<111.222.333.444:555>\n"
" where 111.222.333.444 is the ip address and"
"555 is the port\n you wish to connect to (the"
"punctuation is important.\n", MyName, argv[i] );
my_exit( 1 );
}
} else {
usage();
}
} else if( match_prefix( argv[i], "-pool" ) ) {
if( argv[i + 1] ) {
i++;
if( (tmp = get_daemon_name(argv[i])) ) {
pool = strdup( tmp );
} else {
fprintf( stderr, "%s: unknown host %s\n", MyName,
get_host_part(argv[i]) );
my_exit( 1 );
}
} else {
usage();
}
} else if( match_prefix( argv[i], "-owner" ) ) {
pt = CONDOR_OWNER;
} else if( match_prefix( argv[i], "-tilde" ) ) {
pt = CONDOR_TILDE;
} else if( match_prefix( argv[i], "-master" ) ) {
dt = DT_MASTER;
} else if( match_prefix( argv[i], "-schedd" ) ) {
dt = DT_SCHEDD;
} else if( match_prefix( argv[i], "-startd" ) ) {
dt = DT_STARTD;
} else if( match_prefix( argv[i], "-collector" ) ) {
dt = DT_COLLECTOR;
} else if( match_prefix( argv[i], "-negotiator" ) ) {
dt = DT_NEGOTIATOR;
} else if( match_prefix( argv[i], "-set" ) ) {
mt = CONDOR_SET;
} else if( match_prefix( argv[i], "-unset" ) ) {
mt = CONDOR_UNSET;
} else if( match_prefix( argv[i], "-rset" ) ) {
mt = CONDOR_RUNTIME_SET;
} else if( match_prefix( argv[i], "-runset" ) ) {
mt = CONDOR_RUNTIME_UNSET;
} else if( match_prefix( argv[i], "-" ) ) {
usage();
} else {
params.append( strdup( argv[i] ) );
}
}
// If we didn't get told what subsystem we should use, set it
// to "TOOL".
if( !mySubSystem ) {
mySubSystem = strdup( "TOOL" );
}
// Want to do this before we try to find the address of a
// remote daemon, since if there's no -pool option, we need to
// param() for the COLLECTOR_HOST to contact.
if( host ) {
config_host( 0, host );
} else {
config( 0 );
}
if( name || pool || mt != CONDOR_QUERY ) {
addr = get_daemon_addr( dt, name, pool );
if( ! addr ) {
fprintf( stderr, "Can't find address for %s %s\n",
daemon_string(dt), name );
fprintf( stderr, "Perhaps you need to query another pool.\n" );
my_exit( 1 );
}
}
if( pt == CONDOR_TILDE ) {
if( (tmp = get_tilde()) ) {
printf( "%s\n", tmp );
my_exit( 0 );
} else {
fprintf( stderr,
"Error: Specified -tilde but can't find %s\n",
"condor's home directory." );
my_exit( 1 );
}
}
if( pt == CONDOR_OWNER ) {
printf( "%s\n", get_condor_username() );
my_exit( 0 );
}
params.rewind();
if( ! params.number() ) {
usage();
}
while( (tmp = params.next()) ) {
if( mt == CONDOR_SET || mt == CONDOR_RUNTIME_SET ) {
value = params.next();
SetRemoteParam( name, addr, pool, tmp, value, mt );
} else if( mt == CONDOR_UNSET || mt == CONDOR_RUNTIME_UNSET ) {
SetRemoteParam( name, addr, pool, tmp, "", mt );
} else {
if( name || pool || addr ) {
value = GetRemoteParam( name, addr, pool, tmp );
} else {
value = param( tmp );
}
if( value == NULL ) {
fprintf(stderr, "Not defined: %s\n", tmp);
my_exit( 1 );
} else {
printf("%s\n", value);
free( value );
}
}
}
my_exit( 0 );
}
char*
GetRemoteParam( char* name, char* addr, char* pool, char* param_name )
{
ReliSock s;
s.timeout( 30 );
char *val = NULL;
int cmd = CONFIG_VAL;
if( !name ) {
name = "";
}
if( ! s.connect( addr, 0 ) ) {
fprintf( stderr, "Can't connect to %s on %s %s\n",
daemon_string(dt), name, addr );
my_exit(1);
}
s.encode();
if( !s.code(cmd) ) {
fprintf( stderr, "Can't send command CONFIG_VAL (%d)\n", cmd );
return NULL;
}
if( !s.code(param_name) ) {
fprintf( stderr, "Can't send request (%s)\n", param_name );
return NULL;
}
if( !s.end_of_message() ) {
fprintf( stderr, "Can't send end of message\n" );
return NULL;
}
s.decode();
if( !s.code(val) ) {
fprintf( stderr, "Can't receive reply from %s on %s %s\n",
daemon_string(dt), name, addr );
return NULL;
}
if( !s.end_of_message() ) {
fprintf( stderr, "Can't receive end of message\n" );
return NULL;
}
return val;
}
void
SetRemoteParam( char* name, char* addr, char* pool, char* param_name,
char* param_value, ModeType mt )
{
int cmd, rval;
ReliSock s;
s.timeout( 30 );
switch (mt) {
case CONDOR_SET:
case CONDOR_UNSET:
cmd = DC_CONFIG_PERSIST;
break;
case CONDOR_RUNTIME_SET:
case CONDOR_RUNTIME_UNSET:
cmd = DC_CONFIG_RUNTIME;
break;
default:
fprintf( stderr, "Unknown command type %d\n", (int)mt );
my_exit( 1 );
}
if( !name ) {
name = "";
}
if( ! s.connect( addr, 0 ) ) {
fprintf( stderr, "Can't connect to %s on %s %s\n",
daemon_string(dt), name, addr );
my_exit(1);
}
s.encode();
if( !s.code(cmd) ) {
fprintf( stderr, "Can't send DC_CONFIG command (%d)\n", cmd );
my_exit(1);
}
if( !s.code(param_name) ) {
fprintf( stderr, "Can't send param name (%s)\n", param_name );
my_exit(1);
}
char *buf = NULL;
if (param_value && param_value[0]) {
buf = (char *)malloc(strlen(param_name)+strlen(param_value)+5);
sprintf(buf, "%s : %s\n", param_name, param_value);
if( !s.code(buf) ) {
fprintf( stderr, "Can't send config setting (%s)\n", buf );
free(buf);
my_exit(1);
}
} else {
if( !s.put("") ) {
fprintf( stderr, "Can't send config setting\n" );
my_exit(1);
}
}
if( !s.end_of_message() ) {
fprintf( stderr, "Can't send end of message\n" );
if (buf) free(buf);
my_exit(1);
}
s.decode();
if( !s.code(rval) ) {
fprintf( stderr, "Can't receive reply from %s on %s %s\n",
daemon_string(dt), name, addr );
if (buf) free(buf);
my_exit(1);
}
if( !s.end_of_message() ) {
fprintf( stderr, "Can't receive end of message\n" );
if (buf) free(buf);
my_exit(1);
}
if (buf) buf[strlen(buf)-1] = '\0'; // remove newline
if (rval < 0) {
if (buf) {
fprintf( stderr, "Attempt to set configuration \"%s\" on %s %s "
"%s failed.\n",
buf, daemon_string(dt), name, addr );
free(buf);
} else {
fprintf( stderr, "Attempt to unset configuration \"%s\" on %s %s "
"%s failed.\n",
param_name, daemon_string(dt), name, addr );
}
my_exit(1);
}
if (buf) {
fprintf( stderr, "Successfully set configuration \"%s\" on %s %s "
"%s.\n",
buf, daemon_string(dt), name, addr );
free(buf);
} else {
fprintf( stderr, "Successfully unset configuration \"%s\" on %s %s "
"%s.\n",
param_name, daemon_string(dt), name, addr );
}
}
<|endoftext|> |
<commit_before>#ifdef _WIN32
#include "win_fsnotifier.h"
using namespace std;
//
// WatchPoint
//
WatchPoint::WatchPoint(Server* server, size_t bufferSize, const u16string& path)
: path(path)
, status(NOT_LISTENING) {
wstring pathW(path.begin(), path.end());
HANDLE directoryHandle = CreateFileW(
pathW.c_str(), // pointer to the file name
FILE_LIST_DIRECTORY, // access (read/write) mode
CREATE_SHARE, // share mode
NULL, // security descriptor
OPEN_EXISTING, // how to create
CREATE_FLAGS, // file attributes
NULL // file with attributes to copy
);
if (directoryHandle == INVALID_HANDLE_VALUE) {
throw FileWatcherException("Couldn't add watch", path, GetLastError());
}
this->directoryHandle = directoryHandle;
this->server = server;
this->buffer.reserve(bufferSize);
ZeroMemory(&this->overlapped, sizeof(OVERLAPPED));
this->overlapped.hEvent = this;
switch (listen()) {
case SUCCESS:
break;
case DELETED:
throw FileWatcherException("Couldn't start watching because path is not a directory", path);
}
}
bool WatchPoint::cancel() {
if (status == LISTENING) {
logToJava(FINE, "Cancelling %s", utf16ToUtf8String(path).c_str());
status = CANCELLED;
bool cancelled = (bool) CancelIoEx(directoryHandle, &overlapped);
if (!cancelled) {
DWORD cancelError = GetLastError();
close();
if (cancelError == ERROR_NOT_FOUND) {
// Do nothing, looks like this is a typical scenario
logToJava(FINE, "Watch point already finished %s", utf16ToUtf8String(path).c_str());
} else {
throw FileWatcherException("Couldn't cancel watch point", path, cancelError);
}
}
return cancelled;
}
return false;
}
WatchPoint::~WatchPoint() {
try {
if (cancel()) {
SleepEx(0, true);
}
close();
} catch (const exception& ex) {
logToJava(WARNING, "Couldn't cancel watch point %s: %s", utf16ToUtf8String(path).c_str(), ex.what());
}
}
static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) {
WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent;
watchPoint->handleEventsInBuffer(errorCode, bytesTransferred);
}
bool WatchPoint::isValidDirectory() {
wstring pathW(path.begin(), path.end());
DWORD attrib = GetFileAttributesW(pathW.c_str());
return (attrib != INVALID_FILE_ATTRIBUTES)
&& ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0);
}
ListenResult WatchPoint::listen() {
BOOL success = ReadDirectoryChangesW(
directoryHandle, // handle to directory
&buffer[0], // read results buffer
(DWORD) buffer.capacity(), // length of buffer
TRUE, // include children
EVENT_MASK, // filter conditions
NULL, // bytes returned
&overlapped, // overlapped buffer
&handleEventCallback // completion routine
);
if (success) {
status = LISTENING;
return SUCCESS;
} else {
DWORD listenError = GetLastError();
close();
if (listenError == ERROR_ACCESS_DENIED && !isValidDirectory()) {
return DELETED;
} else {
throw FileWatcherException("Couldn't start watching", path, listenError);
}
}
}
void WatchPoint::close() {
if (status != FINISHED) {
BOOL ret = CloseHandle(directoryHandle);
if (!ret) {
logToJava(SEVERE, "Couldn't close handle %p for '%ls': %d", directoryHandle, utf16ToUtf8String(path).c_str(), GetLastError());
}
status = FINISHED;
}
}
void WatchPoint::handleEventsInBuffer(DWORD errorCode, DWORD bytesTransferred) {
if (errorCode == ERROR_OPERATION_ABORTED) {
logToJava(FINE, "Finished watching '%s', status = %d", utf16ToUtf8String(path).c_str(), status);
close();
return;
}
if (status != LISTENING) {
logToJava(FINE, "Ignoring incoming events for %s as watch-point is not listening (%d bytes, errorCode = %d, status = %d)",
utf16ToUtf8String(path).c_str(), bytesTransferred, errorCode, status);
return;
}
status = NOT_LISTENING;
server->handleEvents(this, errorCode, buffer, bytesTransferred);
}
void Server::handleEvents(WatchPoint* watchPoint, DWORD errorCode, const vector<BYTE>& buffer, DWORD bytesTransferred) {
unique_lock<mutex> lock(mutationMutex);
JNIEnv* env = getThreadEnv();
const u16string& path = watchPoint->path;
try {
if (errorCode != ERROR_SUCCESS) {
if (errorCode == ERROR_ACCESS_DENIED && !watchPoint->isValidDirectory()) {
reportChange(env, REMOVED, path);
watchPoint->close();
return;
} else {
throw FileWatcherException("Error received when handling events", path, errorCode);
}
}
if (terminated) {
logToJava(FINE, "Ignoring incoming events for %s because server is terminating (%d bytes, status = %d)",
utf16ToUtf8String(path).c_str(), bytesTransferred, watchPoint->status);
return;
}
if (bytesTransferred == 0) {
// This is what the documentation has to say about a zero-length dataset:
//
// If the number of bytes transferred is zero, the buffer was either too large
// for the system to allocate or too small to provide detailed information on
// all the changes that occurred in the directory or subtree. In this case,
// you should compute the changes by enumerating the directory or subtree.
//
// (See https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw)
//
// We'll handle this as a simple overflow and report it as such.
logToJava(INFO, "Detected overflow for %s", utf16ToUtf8String(path).c_str());
reportChange(env, OVERFLOWED, path);
} else {
int index = 0;
for (;;) {
FILE_NOTIFY_INFORMATION* current = (FILE_NOTIFY_INFORMATION*) &buffer[index];
handleEvent(env, path, current);
if (current->NextEntryOffset == 0) {
break;
}
index += current->NextEntryOffset;
}
}
switch (watchPoint->listen()) {
case SUCCESS:
break;
case DELETED:
logToJava(FINE, "Watched directory removed for %s", utf16ToUtf8String(path).c_str());
reportChange(env, REMOVED, path);
break;
}
} catch (const exception& ex) {
reportError(env, ex);
}
}
bool isAbsoluteLocalPath(const u16string& path) {
if (path.length() < 3) {
return false;
}
return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z'))
&& path[1] == u':'
&& path[2] == u'\\';
}
bool isAbsoluteUncPath(const u16string& path) {
if (path.length() < 3) {
return false;
}
return path[0] == u'\\' && path[1] == u'\\';
}
bool isLongPath(const u16string& path) {
return path.length() >= 4 && path.substr(0, 4) == u"\\\\?\\";
}
bool isUncLongPath(const u16string& path) {
return path.length() >= 8 && path.substr(0, 8) == u"\\\\?\\UNC\\";
}
// TODO How can this be done nicer, wihtout both unnecessary copy and in-place mutation?
void convertToLongPathIfNeeded(u16string& path) {
// Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related
// to working with directory paths are actually limited to 240. It is just
// safer/simpler to cover both cases in one code path.
if (path.length() <= 240) {
return;
}
// It is already a long path, nothing to do here
if (isLongPath(path)) {
return;
}
if (isAbsoluteLocalPath(path)) {
// Format: C:\... -> \\?\C:\...
path.insert(0, u"\\\\?\\");
} else if (isAbsoluteUncPath(path)) {
// In this case, we need to skip the first 2 characters:
// Format: \\server\share\... -> \\?\UNC\server\share\...
path.erase(0, 2);
path.insert(0, u"\\\\?\\UNC\\");
} else {
// It is some sort of unknown format, don't mess with it
}
}
void Server::handleEvent(JNIEnv* env, const u16string& path, FILE_NOTIFY_INFORMATION* info) {
wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t));
u16string changedPath(changedPathW.begin(), changedPathW.end());
if (!changedPath.empty()) {
changedPath.insert(0, 1, u'\\');
}
changedPath.insert(0, path);
// TODO Remove long prefix for path once?
if (isLongPath(changedPath)) {
if (isUncLongPath(changedPath)) {
changedPath.erase(0, 8).insert(0, u"\\\\");
} else {
changedPath.erase(0, 4);
}
}
logToJava(FINE, "Change detected: 0x%x '%s'", info->Action, utf16ToUtf8String(changedPath).c_str());
FileWatchEventType type;
if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
type = CREATED;
} else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
type = REMOVED;
} else if (info->Action == FILE_ACTION_MODIFIED) {
type = MODIFIED;
} else {
logToJava(WARNING, "Unknown event 0x%x for %s", info->Action, utf16ToUtf8String(changedPath).c_str());
type = UNKNOWN;
}
reportChange(env, type, changedPath);
}
//
// Server
//
Server::Server(JNIEnv* env, size_t bufferSize, jobject watcherCallback)
: AbstractServer(env, watcherCallback)
, bufferSize(bufferSize) {
}
void Server::initializeRunLoop() {
// TODO For some reason GetCurrentThread() returns a thread that doesn't accept APCs
threadHandle = OpenThread(
THREAD_ALL_ACCESS, // dwDesiredAccess
false, // bInheritHandle
GetCurrentThreadId() // dwThreadId
);
if (threadHandle == NULL) {
throw FileWatcherException("Couldn't open current thread", GetLastError());
}
}
void Server::terminateRunLoop() {
executeOnRunLoop([this]() {
terminated = true;
return true;
});
}
void Server::runLoop() {
while (!terminated) {
SleepEx(INFINITE, true);
}
// We have received termination, cancel all watchers
unique_lock<mutex> lock(mutationMutex);
logToJava(FINE, "Finished with run loop, now cancelling remaining watch points", NULL);
int pendingWatchPoints = 0;
for (auto& it : watchPoints) {
auto& watchPoint = it.second;
switch (watchPoint.status) {
case LISTENING:
try {
if (watchPoint.cancel()) {
pendingWatchPoints++;
}
} catch (const exception& ex) {
logToJava(SEVERE, "%s", ex.what());
}
break;
case CANCELLED:
pendingWatchPoints++;
break;
default:
break;
}
}
// If there are any pending watchers, wait for them to finish
if (pendingWatchPoints > 0) {
logToJava(FINE, "Waiting for %d pending watch points to finish", pendingWatchPoints);
SleepEx(0, true);
}
// Warn about any unfinished watchpoints
for (auto& it : watchPoints) {
auto& watchPoint = it.second;
switch (watchPoint.status) {
case NOT_LISTENING:
case FINISHED:
break;
default:
logToJava(WARNING, "Watch point %s did not finish before termination timeout (status = %d)",
utf16ToUtf8String(watchPoint.path).c_str(), watchPoint.status);
break;
}
}
CloseHandle(threadHandle);
}
struct Command {
Server* server;
function<bool()> function;
condition_variable executed;
bool result;
exception_ptr failure;
};
static void CALLBACK executeOnRunLoopCallback(_In_ ULONG_PTR info) {
Command* command = (Command*) info;
try {
command->result = command->function();
} catch (const exception&) {
command->failure = current_exception();
}
unique_lock<mutex> lock(command->server->executionMutex);
command->executed.notify_all();
}
bool Server::executeOnRunLoop(function<bool()> function) {
Command command;
command.function = function;
command.server = this;
unique_lock<mutex> lock(executionMutex);
DWORD ret = QueueUserAPC(executeOnRunLoopCallback, threadHandle, (ULONG_PTR) &command);
if (ret == 0) {
throw FileWatcherException("Received error while queuing APC", GetLastError());
}
auto status = command.executed.wait_for(lock, THREAD_TIMEOUT);
if (status == cv_status::timeout) {
throw FileWatcherException("Execution timed out");
} else if (command.failure) {
rethrow_exception(command.failure);
} else {
return command.result;
}
}
void Server::registerPaths(const vector<u16string>& paths) {
executeOnRunLoop([this, paths]() {
AbstractServer::registerPaths(paths);
return true;
});
}
bool Server::unregisterPaths(const vector<u16string>& paths) {
return executeOnRunLoop([this, paths]() {
return AbstractServer::unregisterPaths(paths);
});
}
void Server::registerPath(const u16string& path) {
u16string longPath = path;
convertToLongPathIfNeeded(longPath);
auto it = watchPoints.find(longPath);
if (it != watchPoints.end()) {
if (it->second.status != FINISHED) {
throw FileWatcherException("Already watching path", path);
}
watchPoints.erase(it);
}
watchPoints.emplace(piecewise_construct,
forward_as_tuple(longPath),
forward_as_tuple(this, bufferSize, longPath));
}
bool Server::unregisterPath(const u16string& path) {
u16string longPath = path;
convertToLongPathIfNeeded(longPath);
if (watchPoints.erase(longPath) == 0) {
logToJava(INFO, "Path is not watched: %s", utf16ToUtf8String(path).c_str());
return false;
}
return true;
}
//
// JNI calls
//
JNIEXPORT jobject JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatcher0(JNIEnv* env, jclass target, jint bufferSize, jobject javaCallback) {
return wrapServer(env, new Server(env, bufferSize, javaCallback));
}
#endif
<commit_msg>Polish cancel state change<commit_after>#ifdef _WIN32
#include "win_fsnotifier.h"
using namespace std;
//
// WatchPoint
//
WatchPoint::WatchPoint(Server* server, size_t bufferSize, const u16string& path)
: path(path)
, status(NOT_LISTENING) {
wstring pathW(path.begin(), path.end());
HANDLE directoryHandle = CreateFileW(
pathW.c_str(), // pointer to the file name
FILE_LIST_DIRECTORY, // access (read/write) mode
CREATE_SHARE, // share mode
NULL, // security descriptor
OPEN_EXISTING, // how to create
CREATE_FLAGS, // file attributes
NULL // file with attributes to copy
);
if (directoryHandle == INVALID_HANDLE_VALUE) {
throw FileWatcherException("Couldn't add watch", path, GetLastError());
}
this->directoryHandle = directoryHandle;
this->server = server;
this->buffer.reserve(bufferSize);
ZeroMemory(&this->overlapped, sizeof(OVERLAPPED));
this->overlapped.hEvent = this;
switch (listen()) {
case SUCCESS:
break;
case DELETED:
throw FileWatcherException("Couldn't start watching because path is not a directory", path);
}
}
bool WatchPoint::cancel() {
if (status == LISTENING) {
logToJava(FINE, "Cancelling %s", utf16ToUtf8String(path).c_str());
bool cancelled = (bool) CancelIoEx(directoryHandle, &overlapped);
if (cancelled) {
status = CANCELLED;
} else {
DWORD cancelError = GetLastError();
close();
if (cancelError == ERROR_NOT_FOUND) {
// Do nothing, looks like this is a typical scenario
logToJava(FINE, "Watch point already finished %s", utf16ToUtf8String(path).c_str());
} else {
throw FileWatcherException("Couldn't cancel watch point", path, cancelError);
}
}
return cancelled;
}
return false;
}
WatchPoint::~WatchPoint() {
try {
if (cancel()) {
SleepEx(0, true);
}
close();
} catch (const exception& ex) {
logToJava(WARNING, "Couldn't cancel watch point %s: %s", utf16ToUtf8String(path).c_str(), ex.what());
}
}
static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) {
WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent;
watchPoint->handleEventsInBuffer(errorCode, bytesTransferred);
}
bool WatchPoint::isValidDirectory() {
wstring pathW(path.begin(), path.end());
DWORD attrib = GetFileAttributesW(pathW.c_str());
return (attrib != INVALID_FILE_ATTRIBUTES)
&& ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0);
}
ListenResult WatchPoint::listen() {
BOOL success = ReadDirectoryChangesW(
directoryHandle, // handle to directory
&buffer[0], // read results buffer
(DWORD) buffer.capacity(), // length of buffer
TRUE, // include children
EVENT_MASK, // filter conditions
NULL, // bytes returned
&overlapped, // overlapped buffer
&handleEventCallback // completion routine
);
if (success) {
status = LISTENING;
return SUCCESS;
} else {
DWORD listenError = GetLastError();
close();
if (listenError == ERROR_ACCESS_DENIED && !isValidDirectory()) {
return DELETED;
} else {
throw FileWatcherException("Couldn't start watching", path, listenError);
}
}
}
void WatchPoint::close() {
if (status != FINISHED) {
BOOL ret = CloseHandle(directoryHandle);
if (!ret) {
logToJava(SEVERE, "Couldn't close handle %p for '%ls': %d", directoryHandle, utf16ToUtf8String(path).c_str(), GetLastError());
}
status = FINISHED;
}
}
void WatchPoint::handleEventsInBuffer(DWORD errorCode, DWORD bytesTransferred) {
if (errorCode == ERROR_OPERATION_ABORTED) {
logToJava(FINE, "Finished watching '%s', status = %d", utf16ToUtf8String(path).c_str(), status);
close();
return;
}
if (status != LISTENING) {
logToJava(FINE, "Ignoring incoming events for %s as watch-point is not listening (%d bytes, errorCode = %d, status = %d)",
utf16ToUtf8String(path).c_str(), bytesTransferred, errorCode, status);
return;
}
status = NOT_LISTENING;
server->handleEvents(this, errorCode, buffer, bytesTransferred);
}
void Server::handleEvents(WatchPoint* watchPoint, DWORD errorCode, const vector<BYTE>& buffer, DWORD bytesTransferred) {
unique_lock<mutex> lock(mutationMutex);
JNIEnv* env = getThreadEnv();
const u16string& path = watchPoint->path;
try {
if (errorCode != ERROR_SUCCESS) {
if (errorCode == ERROR_ACCESS_DENIED && !watchPoint->isValidDirectory()) {
reportChange(env, REMOVED, path);
watchPoint->close();
return;
} else {
throw FileWatcherException("Error received when handling events", path, errorCode);
}
}
if (terminated) {
logToJava(FINE, "Ignoring incoming events for %s because server is terminating (%d bytes, status = %d)",
utf16ToUtf8String(path).c_str(), bytesTransferred, watchPoint->status);
return;
}
if (bytesTransferred == 0) {
// This is what the documentation has to say about a zero-length dataset:
//
// If the number of bytes transferred is zero, the buffer was either too large
// for the system to allocate or too small to provide detailed information on
// all the changes that occurred in the directory or subtree. In this case,
// you should compute the changes by enumerating the directory or subtree.
//
// (See https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw)
//
// We'll handle this as a simple overflow and report it as such.
logToJava(INFO, "Detected overflow for %s", utf16ToUtf8String(path).c_str());
reportChange(env, OVERFLOWED, path);
} else {
int index = 0;
for (;;) {
FILE_NOTIFY_INFORMATION* current = (FILE_NOTIFY_INFORMATION*) &buffer[index];
handleEvent(env, path, current);
if (current->NextEntryOffset == 0) {
break;
}
index += current->NextEntryOffset;
}
}
switch (watchPoint->listen()) {
case SUCCESS:
break;
case DELETED:
logToJava(FINE, "Watched directory removed for %s", utf16ToUtf8String(path).c_str());
reportChange(env, REMOVED, path);
break;
}
} catch (const exception& ex) {
reportError(env, ex);
}
}
bool isAbsoluteLocalPath(const u16string& path) {
if (path.length() < 3) {
return false;
}
return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z'))
&& path[1] == u':'
&& path[2] == u'\\';
}
bool isAbsoluteUncPath(const u16string& path) {
if (path.length() < 3) {
return false;
}
return path[0] == u'\\' && path[1] == u'\\';
}
bool isLongPath(const u16string& path) {
return path.length() >= 4 && path.substr(0, 4) == u"\\\\?\\";
}
bool isUncLongPath(const u16string& path) {
return path.length() >= 8 && path.substr(0, 8) == u"\\\\?\\UNC\\";
}
// TODO How can this be done nicer, wihtout both unnecessary copy and in-place mutation?
void convertToLongPathIfNeeded(u16string& path) {
// Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related
// to working with directory paths are actually limited to 240. It is just
// safer/simpler to cover both cases in one code path.
if (path.length() <= 240) {
return;
}
// It is already a long path, nothing to do here
if (isLongPath(path)) {
return;
}
if (isAbsoluteLocalPath(path)) {
// Format: C:\... -> \\?\C:\...
path.insert(0, u"\\\\?\\");
} else if (isAbsoluteUncPath(path)) {
// In this case, we need to skip the first 2 characters:
// Format: \\server\share\... -> \\?\UNC\server\share\...
path.erase(0, 2);
path.insert(0, u"\\\\?\\UNC\\");
} else {
// It is some sort of unknown format, don't mess with it
}
}
void Server::handleEvent(JNIEnv* env, const u16string& path, FILE_NOTIFY_INFORMATION* info) {
wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t));
u16string changedPath(changedPathW.begin(), changedPathW.end());
if (!changedPath.empty()) {
changedPath.insert(0, 1, u'\\');
}
changedPath.insert(0, path);
// TODO Remove long prefix for path once?
if (isLongPath(changedPath)) {
if (isUncLongPath(changedPath)) {
changedPath.erase(0, 8).insert(0, u"\\\\");
} else {
changedPath.erase(0, 4);
}
}
logToJava(FINE, "Change detected: 0x%x '%s'", info->Action, utf16ToUtf8String(changedPath).c_str());
FileWatchEventType type;
if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
type = CREATED;
} else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
type = REMOVED;
} else if (info->Action == FILE_ACTION_MODIFIED) {
type = MODIFIED;
} else {
logToJava(WARNING, "Unknown event 0x%x for %s", info->Action, utf16ToUtf8String(changedPath).c_str());
type = UNKNOWN;
}
reportChange(env, type, changedPath);
}
//
// Server
//
Server::Server(JNIEnv* env, size_t bufferSize, jobject watcherCallback)
: AbstractServer(env, watcherCallback)
, bufferSize(bufferSize) {
}
void Server::initializeRunLoop() {
// TODO For some reason GetCurrentThread() returns a thread that doesn't accept APCs
threadHandle = OpenThread(
THREAD_ALL_ACCESS, // dwDesiredAccess
false, // bInheritHandle
GetCurrentThreadId() // dwThreadId
);
if (threadHandle == NULL) {
throw FileWatcherException("Couldn't open current thread", GetLastError());
}
}
void Server::terminateRunLoop() {
executeOnRunLoop([this]() {
terminated = true;
return true;
});
}
void Server::runLoop() {
while (!terminated) {
SleepEx(INFINITE, true);
}
// We have received termination, cancel all watchers
unique_lock<mutex> lock(mutationMutex);
logToJava(FINE, "Finished with run loop, now cancelling remaining watch points", NULL);
int pendingWatchPoints = 0;
for (auto& it : watchPoints) {
auto& watchPoint = it.second;
switch (watchPoint.status) {
case LISTENING:
try {
if (watchPoint.cancel()) {
pendingWatchPoints++;
}
} catch (const exception& ex) {
logToJava(SEVERE, "%s", ex.what());
}
break;
case CANCELLED:
pendingWatchPoints++;
break;
default:
break;
}
}
// If there are any pending watchers, wait for them to finish
if (pendingWatchPoints > 0) {
logToJava(FINE, "Waiting for %d pending watch points to finish", pendingWatchPoints);
SleepEx(0, true);
}
// Warn about any unfinished watchpoints
for (auto& it : watchPoints) {
auto& watchPoint = it.second;
switch (watchPoint.status) {
case NOT_LISTENING:
case FINISHED:
break;
default:
logToJava(WARNING, "Watch point %s did not finish before termination timeout (status = %d)",
utf16ToUtf8String(watchPoint.path).c_str(), watchPoint.status);
break;
}
}
CloseHandle(threadHandle);
}
struct Command {
Server* server;
function<bool()> function;
condition_variable executed;
bool result;
exception_ptr failure;
};
static void CALLBACK executeOnRunLoopCallback(_In_ ULONG_PTR info) {
Command* command = (Command*) info;
try {
command->result = command->function();
} catch (const exception&) {
command->failure = current_exception();
}
unique_lock<mutex> lock(command->server->executionMutex);
command->executed.notify_all();
}
bool Server::executeOnRunLoop(function<bool()> function) {
Command command;
command.function = function;
command.server = this;
unique_lock<mutex> lock(executionMutex);
DWORD ret = QueueUserAPC(executeOnRunLoopCallback, threadHandle, (ULONG_PTR) &command);
if (ret == 0) {
throw FileWatcherException("Received error while queuing APC", GetLastError());
}
auto status = command.executed.wait_for(lock, THREAD_TIMEOUT);
if (status == cv_status::timeout) {
throw FileWatcherException("Execution timed out");
} else if (command.failure) {
rethrow_exception(command.failure);
} else {
return command.result;
}
}
void Server::registerPaths(const vector<u16string>& paths) {
executeOnRunLoop([this, paths]() {
AbstractServer::registerPaths(paths);
return true;
});
}
bool Server::unregisterPaths(const vector<u16string>& paths) {
return executeOnRunLoop([this, paths]() {
return AbstractServer::unregisterPaths(paths);
});
}
void Server::registerPath(const u16string& path) {
u16string longPath = path;
convertToLongPathIfNeeded(longPath);
auto it = watchPoints.find(longPath);
if (it != watchPoints.end()) {
if (it->second.status != FINISHED) {
throw FileWatcherException("Already watching path", path);
}
watchPoints.erase(it);
}
watchPoints.emplace(piecewise_construct,
forward_as_tuple(longPath),
forward_as_tuple(this, bufferSize, longPath));
}
bool Server::unregisterPath(const u16string& path) {
u16string longPath = path;
convertToLongPathIfNeeded(longPath);
if (watchPoints.erase(longPath) == 0) {
logToJava(INFO, "Path is not watched: %s", utf16ToUtf8String(path).c_str());
return false;
}
return true;
}
//
// JNI calls
//
JNIEXPORT jobject JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatcher0(JNIEnv* env, jclass target, jint bufferSize, jobject javaCallback) {
return wrapServer(env, new Server(env, bufferSize, javaCallback));
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImage.h"
#include "SkImageGenerator.h"
#include "SkNextID.h"
#include "SkYUVAIndex.h"
SkImageGenerator::SkImageGenerator(const SkImageInfo& info, uint32_t uniqueID)
: fInfo(info)
, fUniqueID(kNeedNewImageUniqueID == uniqueID ? SkNextID::ImageID() : uniqueID)
{}
bool SkImageGenerator::getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes) {
if (kUnknown_SkColorType == info.colorType()) {
return false;
}
if (nullptr == pixels) {
return false;
}
if (rowBytes < info.minRowBytes()) {
return false;
}
Options defaultOpts;
return this->onGetPixels(info, pixels, rowBytes, defaultOpts);
}
bool SkImageGenerator::queryYUVA8(SkYUVSizeInfo* sizeInfo,
SkYUVAIndex yuvaIndices[SkYUVAIndex::kIndexCount],
SkYUVColorSpace* colorSpace) const {
SkASSERT(sizeInfo);
if (!this->onQueryYUVA8(sizeInfo, yuvaIndices, colorSpace)) {
// try the deprecated method and make a guess at the other data
if (this->onQueryYUV8(sizeInfo, colorSpace)) {
// take a guess at the number of planes
int numPlanes = SkYUVSizeInfo::kMaxCount;
for (int i = 0; i < SkYUVSizeInfo::kMaxCount; ++i) {
if (sizeInfo->fSizes[i].isEmpty()) {
numPlanes = i;
break;
}
}
if (!numPlanes) {
return false;
}
switch (numPlanes) {
case 1:
// Assume 3 interleaved planes
sizeInfo->fColorTypes[0] = kRGBA_8888_SkColorType;
sizeInfo->fColorTypes[1] = kUnknown_SkColorType;
sizeInfo->fColorTypes[2] = kUnknown_SkColorType;
sizeInfo->fColorTypes[3] = kUnknown_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kG;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kB;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = -1;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
case 2:
// Assume 1 Y plane and interleaved UV planes
sizeInfo->fColorTypes[0] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[1] = kRGBA_8888_SkColorType;
sizeInfo->fColorTypes[2] = kUnknown_SkColorType;
sizeInfo->fColorTypes[3] = kUnknown_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kG;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = -1;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
case 3:
// Assume 3 separate non-interleaved planes
sizeInfo->fColorTypes[0] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[1] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[2] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[3] = kUnknown_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 2;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = -1;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
case 4:
default:
// Assume 4 separate non-interleaved planes
sizeInfo->fColorTypes[0] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[1] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[2] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[3] = kAlpha_8_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 2;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = 3;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
}
return true;
}
return false;
}
return true;
}
bool SkImageGenerator::getYUVA8Planes(const SkYUVSizeInfo& sizeInfo,
const SkYUVAIndex yuvaIndices[SkYUVAIndex::kIndexCount],
void* planes[SkYUVSizeInfo::kMaxCount]) {
for (int i = 0; i < SkYUVSizeInfo::kMaxCount; ++i) {
SkASSERT(sizeInfo.fSizes[i].fWidth >= 0);
SkASSERT(sizeInfo.fSizes[i].fHeight >= 0);
SkASSERT(sizeInfo.fWidthBytes[i] >= (size_t) sizeInfo.fSizes[i].fWidth);
}
int numPlanes = 0;
SkASSERT(SkYUVAIndex::AreValidIndices(yuvaIndices, &numPlanes));
SkASSERT(planes);
for (int i = 0; i < numPlanes; ++i) {
SkASSERT(planes[i]);
}
if (!this->onGetYUVA8Planes(sizeInfo, yuvaIndices, planes)) {
return this->onGetYUV8Planes(sizeInfo, planes);
}
return true;
}
#if SK_SUPPORT_GPU
#include "GrTextureProxy.h"
sk_sp<GrTextureProxy> SkImageGenerator::generateTexture(GrContext* ctx, const SkImageInfo& info,
const SkIPoint& origin,
bool willNeedMipMaps) {
SkIRect srcRect = SkIRect::MakeXYWH(origin.x(), origin.y(), info.width(), info.height());
if (!SkIRect::MakeWH(fInfo.width(), fInfo.height()).contains(srcRect)) {
return nullptr;
}
return this->onGenerateTexture(ctx, info, origin, willNeedMipMaps);
}
sk_sp<GrTextureProxy> SkImageGenerator::onGenerateTexture(GrContext*, const SkImageInfo&,
const SkIPoint&,
bool willNeedMipMaps) {
return nullptr;
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkBitmap.h"
#include "SkColorTable.h"
#include "SkGraphics.h"
static SkGraphics::ImageGeneratorFromEncodedDataFactory gFactory;
SkGraphics::ImageGeneratorFromEncodedDataFactory
SkGraphics::SetImageGeneratorFromEncodedDataFactory(ImageGeneratorFromEncodedDataFactory factory)
{
ImageGeneratorFromEncodedDataFactory prev = gFactory;
gFactory = factory;
return prev;
}
std::unique_ptr<SkImageGenerator> SkImageGenerator::MakeFromEncoded(sk_sp<SkData> data) {
if (!data) {
return nullptr;
}
if (gFactory) {
if (std::unique_ptr<SkImageGenerator> generator = gFactory(data)) {
return generator;
}
}
return SkImageGenerator::MakeFromEncodedImpl(std::move(data));
}
<commit_msg>Check correct number of planes in queryYUVA8<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImage.h"
#include "SkImageGenerator.h"
#include "SkNextID.h"
#include "SkYUVAIndex.h"
SkImageGenerator::SkImageGenerator(const SkImageInfo& info, uint32_t uniqueID)
: fInfo(info)
, fUniqueID(kNeedNewImageUniqueID == uniqueID ? SkNextID::ImageID() : uniqueID)
{}
bool SkImageGenerator::getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes) {
if (kUnknown_SkColorType == info.colorType()) {
return false;
}
if (nullptr == pixels) {
return false;
}
if (rowBytes < info.minRowBytes()) {
return false;
}
Options defaultOpts;
return this->onGetPixels(info, pixels, rowBytes, defaultOpts);
}
bool SkImageGenerator::queryYUVA8(SkYUVSizeInfo* sizeInfo,
SkYUVAIndex yuvaIndices[SkYUVAIndex::kIndexCount],
SkYUVColorSpace* colorSpace) const {
SkASSERT(sizeInfo);
if (!this->onQueryYUVA8(sizeInfo, yuvaIndices, colorSpace)) {
// try the deprecated method and make a guess at the other data
if (this->onQueryYUV8(sizeInfo, colorSpace)) {
// take a guess at the number of planes
int numPlanes = 3; // onQueryYUV8 only supports up to 3 channels
for (int i = 0; i < 3; ++i) {
if (sizeInfo->fSizes[i].isEmpty()) {
numPlanes = i;
break;
}
}
if (!numPlanes) {
return false;
}
switch (numPlanes) {
case 1:
// Assume 3 interleaved planes
sizeInfo->fColorTypes[0] = kRGBA_8888_SkColorType;
sizeInfo->fColorTypes[1] = kUnknown_SkColorType;
sizeInfo->fColorTypes[2] = kUnknown_SkColorType;
sizeInfo->fColorTypes[3] = kUnknown_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kG;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kB;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = -1;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
case 2:
// Assume 1 Y plane and interleaved UV planes (NV12)
sizeInfo->fColorTypes[0] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[1] = kRGBA_8888_SkColorType;
sizeInfo->fColorTypes[2] = kUnknown_SkColorType;
sizeInfo->fColorTypes[3] = kUnknown_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kG;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = -1;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
case 3:
default:
// Assume 3 separate non-interleaved planes
sizeInfo->fColorTypes[0] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[1] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[2] = kAlpha_8_SkColorType;
sizeInfo->fColorTypes[3] = kUnknown_SkColorType;
yuvaIndices[SkYUVAIndex::kY_Index].fIndex = 0;
yuvaIndices[SkYUVAIndex::kY_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kU_Index].fIndex = 1;
yuvaIndices[SkYUVAIndex::kU_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kV_Index].fIndex = 2;
yuvaIndices[SkYUVAIndex::kV_Index].fChannel = SkColorChannel::kR;
yuvaIndices[SkYUVAIndex::kA_Index].fIndex = -1;
yuvaIndices[SkYUVAIndex::kA_Index].fChannel = SkColorChannel::kR;
break;
}
return true;
}
return false;
}
return true;
}
bool SkImageGenerator::getYUVA8Planes(const SkYUVSizeInfo& sizeInfo,
const SkYUVAIndex yuvaIndices[SkYUVAIndex::kIndexCount],
void* planes[SkYUVSizeInfo::kMaxCount]) {
for (int i = 0; i < SkYUVSizeInfo::kMaxCount; ++i) {
SkASSERT(sizeInfo.fSizes[i].fWidth >= 0);
SkASSERT(sizeInfo.fSizes[i].fHeight >= 0);
SkASSERT(sizeInfo.fWidthBytes[i] >= (size_t) sizeInfo.fSizes[i].fWidth);
}
int numPlanes = 0;
SkASSERT(SkYUVAIndex::AreValidIndices(yuvaIndices, &numPlanes));
SkASSERT(planes);
for (int i = 0; i < numPlanes; ++i) {
SkASSERT(planes[i]);
}
if (!this->onGetYUVA8Planes(sizeInfo, yuvaIndices, planes)) {
return this->onGetYUV8Planes(sizeInfo, planes);
}
return true;
}
#if SK_SUPPORT_GPU
#include "GrTextureProxy.h"
sk_sp<GrTextureProxy> SkImageGenerator::generateTexture(GrContext* ctx, const SkImageInfo& info,
const SkIPoint& origin,
bool willNeedMipMaps) {
SkIRect srcRect = SkIRect::MakeXYWH(origin.x(), origin.y(), info.width(), info.height());
if (!SkIRect::MakeWH(fInfo.width(), fInfo.height()).contains(srcRect)) {
return nullptr;
}
return this->onGenerateTexture(ctx, info, origin, willNeedMipMaps);
}
sk_sp<GrTextureProxy> SkImageGenerator::onGenerateTexture(GrContext*, const SkImageInfo&,
const SkIPoint&,
bool willNeedMipMaps) {
return nullptr;
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkBitmap.h"
#include "SkColorTable.h"
#include "SkGraphics.h"
static SkGraphics::ImageGeneratorFromEncodedDataFactory gFactory;
SkGraphics::ImageGeneratorFromEncodedDataFactory
SkGraphics::SetImageGeneratorFromEncodedDataFactory(ImageGeneratorFromEncodedDataFactory factory)
{
ImageGeneratorFromEncodedDataFactory prev = gFactory;
gFactory = factory;
return prev;
}
std::unique_ptr<SkImageGenerator> SkImageGenerator::MakeFromEncoded(sk_sp<SkData> data) {
if (!data) {
return nullptr;
}
if (gFactory) {
if (std::unique_ptr<SkImageGenerator> generator = gFactory(data)) {
return generator;
}
}
return SkImageGenerator::MakeFromEncodedImpl(std::move(data));
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 Timo Savola
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
#ifndef CONCRETE_OBJECTS_OBJECT_HPP
#define CONCRETE_OBJECTS_OBJECT_HPP
#include "object-decl.hpp"
#include <cassert>
#include <concrete/block.hpp>
#include <concrete/context.hpp>
#include <concrete/exception.hpp>
#include <concrete/objects/none-fwd.hpp>
#include <concrete/objects/string-decl.hpp>
#include <concrete/objects/type-decl.hpp>
#include <concrete/util/packed.hpp>
namespace concrete {
struct ObjectBlock: Block {
struct NoRefcountInit {};
PortableObject type_object;
portable<int32_t> refcount;
ObjectBlock(BlockId type_id, NoRefcountInit): type_object(type_id)
{
}
ObjectBlock(const TypeObject &type): type_object(type), refcount(0)
{
}
TypeObject type() const
{
// don't use cast<TypeObject>() because it causes an infinite recursion
return TypeObject(type_object.id());
}
StringObject repr(BlockId id) const;
static void Destroy(ObjectBlock *block) throw ();
} CONCRETE_PACKED;
template <typename Ops>
TypeObject object<Ops>::Type()
{
return Context::Builtins().object_type;
}
template <typename Ops>
object<Ops> object<Ops>::New() throw (AllocError)
{
auto id = Context::Alloc(sizeof (ObjectBlock));
new (Context::Pointer(id)) ObjectBlock(Type());
return object(id);
}
template <typename Ops>
object<Ops>::object(): m_raw_id(Ops::store(Context::None().id()))
{
ref();
}
template <typename Ops> template <typename T>
bool object<Ops>::check() const
{
return type() == T::Type();
}
template <typename Ops> template <typename T>
T object<Ops>::cast() const
{
assert(check<T>());
return T(id());
}
template <typename Ops> template <typename T>
T object<Ops>::require() const
{
if (!check<T>())
throw TypeError(type());
return T(id());
}
template <typename Ops>
TypeObject object<Ops>::type() const
{
return object_block()->type();
}
template <typename Ops>
StringObject object<Ops>::repr() const
{
return object_block()->repr(id());
}
template <typename Ops>
void object<Ops>::ref() const
{
auto block = object_block();
block->refcount = block->refcount + 1;
}
template <typename Ops>
void object<Ops>::unref() const
{
auto block = object_block();
int refcount = block->refcount - 1;
block->refcount = refcount;
assert(refcount >= 0);
if (refcount == 0)
ObjectBlock::Destroy(block);
}
template <typename Ops>
ObjectBlock *object<Ops>::object_block() const
{
return static_cast<ObjectBlock *> (Context::Pointer(id()));
}
} // namespace
#endif
<commit_msg>Object::check implemented using type_check<commit_after>/*
* Copyright (c) 2011 Timo Savola
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
#ifndef CONCRETE_OBJECTS_OBJECT_HPP
#define CONCRETE_OBJECTS_OBJECT_HPP
#include "object-decl.hpp"
#include <cassert>
#include <concrete/block.hpp>
#include <concrete/context.hpp>
#include <concrete/exception.hpp>
#include <concrete/objects/none-fwd.hpp>
#include <concrete/objects/string-decl.hpp>
#include <concrete/objects/type-decl.hpp>
#include <concrete/util/packed.hpp>
namespace concrete {
struct ObjectBlock: Block {
struct NoRefcountInit {};
PortableObject type_object;
portable<int32_t> refcount;
ObjectBlock(BlockId type_id, NoRefcountInit): type_object(type_id)
{
}
ObjectBlock(const TypeObject &type): type_object(type), refcount(0)
{
}
TypeObject type() const
{
// don't use cast<TypeObject>() because it causes an infinite recursion
return TypeObject(type_object.id());
}
StringObject repr(BlockId id) const;
static void Destroy(ObjectBlock *block) throw ();
} CONCRETE_PACKED;
template <typename Ops>
TypeObject object<Ops>::Type()
{
return Context::Builtins().object_type;
}
template <typename Ops>
object<Ops> object<Ops>::New() throw (AllocError)
{
auto id = Context::Alloc(sizeof (ObjectBlock));
new (Context::Pointer(id)) ObjectBlock(Type());
return object(id);
}
template <typename Ops>
object<Ops>::object(): m_raw_id(Ops::store(Context::None().id()))
{
ref();
}
template <typename Ops> template <typename T>
bool object<Ops>::check() const
{
type_check<T> impl;
return impl(type());
}
template <typename Ops> template <typename T>
T object<Ops>::cast() const
{
assert(check<T>());
return T(id());
}
template <typename Ops> template <typename T>
T object<Ops>::require() const
{
if (!check<T>())
throw TypeError(type());
return T(id());
}
template <typename Ops>
TypeObject object<Ops>::type() const
{
return object_block()->type();
}
template <typename Ops>
StringObject object<Ops>::repr() const
{
return object_block()->repr(id());
}
template <typename Ops>
void object<Ops>::ref() const
{
auto block = object_block();
block->refcount = block->refcount + 1;
}
template <typename Ops>
void object<Ops>::unref() const
{
auto block = object_block();
int refcount = block->refcount - 1;
block->refcount = refcount;
assert(refcount >= 0);
if (refcount == 0)
ObjectBlock::Destroy(block);
}
template <typename Ops>
ObjectBlock *object<Ops>::object_block() const
{
return static_cast<ObjectBlock *> (Context::Pointer(id()));
}
} // namespace
#endif
<|endoftext|> |
<commit_before>/**************************************************************************\
* The component that goes BOOM! (timed) area effects on contact/damage *
* ___ *
* /\/\ __ _ __ _ _ __ _ _ _ __ ___ /___\_ __ _ _ ___ *
* / \ / _` |/ _` | '_ \| | | | '_ ` _ \ // // '_ \| | | / __| *
* / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \ *
* \/ \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/ *
* |___/ |_| *
* *
* Copyright (c) 2014 Florian Oetke *
* *
* This file is part of MagnumOpus and distributed under the MIT License *
* See LICENSE file for details. *
\**************************************************************************/
#pragma once
#include <core/ecs/ecs.hpp>
#include <core/units.hpp>
namespace mo {
namespace sys {
namespace combat {
class Explosive_comp : public ecs::Component<Explosive_comp> {
public:
static constexpr const char* name() {return "Explosive";}
void load(ecs::Entity_state&)override;
void store(ecs::Entity_state&)override;
Explosive_comp(ecs::Entity& owner, float damage=10, Distance range=Distance(2),
Time delay=Time(0), bool on_contact=false, bool on_damage=false) noexcept
: Component(owner), _damage(damage), _range(range), _delay(delay),
_activate_on_contact(on_contact), _activate_on_damage(on_damage) {}
struct Persisted_state;
friend struct Persisted_state;
private:
friend class Combat_system;
float _damage;
Distance _range;
Time _delay;
bool _activate_on_contact;
bool _activate_on_damage;
Time _delay_left = Time(0);
bool _exloded = false;
// TODO{foe]: add other effects
};
}
}
}
<commit_msg>missing destructor<commit_after>/**************************************************************************\
* The component that goes BOOM! (timed) area effects on contact/damage *
* ___ *
* /\/\ __ _ __ _ _ __ _ _ _ __ ___ /___\_ __ _ _ ___ *
* / \ / _` |/ _` | '_ \| | | | '_ ` _ \ // // '_ \| | | / __| *
* / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \ *
* \/ \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/ *
* |___/ |_| *
* *
* Copyright (c) 2014 Florian Oetke *
* *
* This file is part of MagnumOpus and distributed under the MIT License *
* See LICENSE file for details. *
\**************************************************************************/
#pragma once
#include <core/ecs/ecs.hpp>
#include <core/units.hpp>
namespace mo {
namespace sys {
namespace combat {
class Explosive_comp : public ecs::Component<Explosive_comp> {
public:
static constexpr const char* name() {return "Explosive";}
void load(ecs::Entity_state&)override;
void store(ecs::Entity_state&)override;
Explosive_comp(ecs::Entity& owner, float damage=10, Distance range=Distance(2),
Time delay=Time(0), bool on_contact=false, bool on_damage=false) noexcept
: Component(owner), _damage(damage), _range(range), _delay(delay),
_activate_on_contact(on_contact), _activate_on_damage(on_damage) {}
Explosive_comp(Explosive_comp&&)noexcept = default;
~Explosive_comp()noexcept = default;
Explosive_comp& operator=(Explosive_comp&&)noexcept = default;
struct Persisted_state;
friend struct Persisted_state;
private:
friend class Combat_system;
float _damage;
Distance _range;
Time _delay;
bool _activate_on_contact;
bool _activate_on_damage;
Time _delay_left = Time(0);
bool _exloded = false;
// TODO{foe]: add other effects
};
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2016, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <sstream>
#include <numeric>
#include <boost/utility/value_init.hpp>
#include <boost/interprocess/detail/atomic.hpp>
#include <boost/limits.hpp>
#include <boost/foreach.hpp>
#include "misc_language.h"
#include "include_base_utils.h"
#include "cryptonote_basic_impl.h"
#include "cryptonote_format_utils.h"
#include "file_io_utils.h"
#include "common/command_line.h"
#include "string_coding.h"
#include "storages/portable_storage_template_helper.h"
using namespace epee;
#include "miner.h"
extern "C" void slow_hash_allocate_state();
extern "C" void slow_hash_free_state();
namespace cryptonote
{
namespace
{
const command_line::arg_descriptor<std::string> arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true};
const command_line::arg_descriptor<std::string> arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true};
const command_line::arg_descriptor<uint32_t> arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true};
}
miner::miner(i_miner_handler* phandler):m_stop(1),
m_template(boost::value_initialized<block>()),
m_template_no(0),
m_diffic(0),
m_thread_index(0),
m_phandler(phandler),
m_height(0),
m_pausers_count(0),
m_threads_total(0),
m_starter_nonce(0),
m_last_hr_merge_time(0),
m_hashes(0),
m_do_print_hashrate(false),
m_do_mining(false),
m_current_hash_rate(0)
{
}
//-----------------------------------------------------------------------------------------------------
miner::~miner()
{
stop();
}
//-----------------------------------------------------------------------------------------------------
bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height)
{
CRITICAL_REGION_LOCAL(m_template_lock);
m_template = bl;
m_diffic = di;
m_height = height;
++m_template_no;
m_starter_nonce = crypto::rand<uint32_t>();
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::on_block_chain_update()
{
if(!is_mining())
return true;
return request_block_template();
}
//-----------------------------------------------------------------------------------------------------
bool miner::request_block_template()
{
block bl = AUTO_VAL_INIT(bl);
difficulty_type di = AUTO_VAL_INIT(di);
uint64_t height = AUTO_VAL_INIT(height);
cryptonote::blobdata extra_nonce;
if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size())
{
extra_nonce = m_extra_messages[m_config.current_extra_message_index];
}
if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce))
{
LOG_ERROR("Failed to get_block_template(), stopping mining");
return false;
}
set_block_template(bl, di, height);
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::on_idle()
{
m_update_block_template_interval.do_call([&](){
if(is_mining())request_block_template();
return true;
});
m_update_merge_hr_interval.do_call([&](){
merge_hr();
return true;
});
return true;
}
//-----------------------------------------------------------------------------------------------------
void miner::do_print_hashrate(bool do_hr)
{
m_do_print_hashrate = do_hr;
}
//-----------------------------------------------------------------------------------------------------
void miner::merge_hr()
{
if(m_last_hr_merge_time && is_mining())
{
m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1));
CRITICAL_REGION_LOCAL(m_last_hash_rates_lock);
m_last_hash_rates.push_back(m_current_hash_rate);
if(m_last_hash_rates.size() > 19)
m_last_hash_rates.pop_front();
if(m_do_print_hashrate)
{
uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0);
float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size());
std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << ENDL;
}
}
m_last_hr_merge_time = misc_utils::get_tick_count();
m_hashes = 0;
}
//-----------------------------------------------------------------------------------------------------
void miner::init_options(boost::program_options::options_description& desc)
{
command_line::add_arg(desc, arg_extra_messages);
command_line::add_arg(desc, arg_start_mining);
command_line::add_arg(desc, arg_mining_threads);
}
//-----------------------------------------------------------------------------------------------------
bool miner::init(const boost::program_options::variables_map& vm, bool testnet)
{
if(command_line::has_arg(vm, arg_extra_messages))
{
std::string buff;
bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff);
CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages));
std::vector<std::string> extra_vec;
boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on );
m_extra_messages.resize(extra_vec.size());
for(size_t i = 0; i != extra_vec.size(); i++)
{
string_tools::trim(extra_vec[i]);
if(!extra_vec[i].size())
continue;
std::string buff = string_encoding::base64_decode(extra_vec[i]);
if(buff != "0")
m_extra_messages[i] = buff;
}
m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string();
m_config = AUTO_VAL_INIT(m_config);
epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME);
LOG_PRINT_L0("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index);
}
if(command_line::has_arg(vm, arg_start_mining))
{
if(!cryptonote::get_account_address_from_str(m_mine_address, testnet, command_line::get_arg(vm, arg_start_mining)))
{
LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled");
return false;
}
m_threads_total = 1;
m_do_mining = true;
if(command_line::has_arg(vm, arg_mining_threads))
{
m_threads_total = command_line::get_arg(vm, arg_mining_threads);
}
}
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::is_mining() const
{
return !m_stop;
}
//-----------------------------------------------------------------------------------------------------
const account_public_address& miner::get_mining_address() const
{
return m_mine_address;
}
//-----------------------------------------------------------------------------------------------------
uint32_t miner::get_threads_count() const {
return m_threads_total;
}
//-----------------------------------------------------------------------------------------------------
bool miner::start(const account_public_address& adr, size_t threads_count, const boost::thread::attributes& attrs)
{
m_mine_address = adr;
m_threads_total = static_cast<uint32_t>(threads_count);
m_starter_nonce = crypto::rand<uint32_t>();
CRITICAL_REGION_LOCAL(m_threads_lock);
if(is_mining())
{
LOG_ERROR("Starting miner but it's already started");
return false;
}
if(!m_threads.empty())
{
LOG_ERROR("Unable to start miner because there are active mining threads");
return false;
}
if(!m_template_no)
request_block_template();//lets update block template
boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0);
boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0);
for(size_t i = 0; i != threads_count; i++)
{
m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this)));
}
LOG_PRINT_L0("Mining has started with " << threads_count << " threads, good luck!" );
return true;
}
//-----------------------------------------------------------------------------------------------------
uint64_t miner::get_speed() const
{
if(is_mining()) {
return m_current_hash_rate;
}
else {
return 0;
}
}
//-----------------------------------------------------------------------------------------------------
void miner::send_stop_signal()
{
boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1);
}
//-----------------------------------------------------------------------------------------------------
bool miner::stop()
{
if (!is_mining())
return true;
send_stop_signal();
CRITICAL_REGION_LOCAL(m_threads_lock);
BOOST_FOREACH(boost::thread& th, m_threads)
th.join();
LOG_PRINT_L0("Mining has been stopped, " << m_threads.size() << " finished" );
m_threads.clear();
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height)
{
for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++)
{
crypto::hash h;
get_block_longhash(bl, h, height);
if(check_hash(h, diffic))
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------------------
void miner::on_synchronized()
{
if(m_do_mining)
{
boost::thread::attributes attrs;
attrs.set_stack_size(THREAD_STACK_SIZE);
start(m_mine_address, m_threads_total, attrs);
}
}
//-----------------------------------------------------------------------------------------------------
void miner::pause()
{
CRITICAL_REGION_LOCAL(m_miners_count_lock);
++m_pausers_count;
if(m_pausers_count == 1 && is_mining())
LOG_PRINT_L2("MINING PAUSED");
}
//-----------------------------------------------------------------------------------------------------
void miner::resume()
{
CRITICAL_REGION_LOCAL(m_miners_count_lock);
--m_pausers_count;
if(m_pausers_count < 0)
{
m_pausers_count = 0;
LOG_PRINT_RED_L0("Unexpected miner::resume() called");
}
if(!m_pausers_count && is_mining())
LOG_PRINT_L2("MINING RESUMED");
}
//-----------------------------------------------------------------------------------------------------
bool miner::worker_thread()
{
uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index);
LOG_PRINT_L0("Miner thread was started ["<< th_local_index << "]");
log_space::log_singletone::set_thread_log_prefix(std::string("[miner ") + std::to_string(th_local_index) + "]");
uint32_t nonce = m_starter_nonce + th_local_index;
uint64_t height = 0;
difficulty_type local_diff = 0;
uint32_t local_template_ver = 0;
block b;
slow_hash_allocate_state();
while(!m_stop)
{
if(m_pausers_count)//anti split workaround
{
misc_utils::sleep_no_w(100);
continue;
}
if(local_template_ver != m_template_no)
{
CRITICAL_REGION_BEGIN(m_template_lock);
b = m_template;
local_diff = m_diffic;
height = m_height;
CRITICAL_REGION_END();
local_template_ver = m_template_no;
nonce = m_starter_nonce + th_local_index;
}
if(!local_template_ver)//no any set_block_template call
{
LOG_PRINT_L2("Block template not set yet");
epee::misc_utils::sleep_no_w(1000);
continue;
}
b.nonce = nonce;
crypto::hash h;
get_block_longhash(b, h, height);
if(check_hash(h, local_diff))
{
//we lucky!
++m_config.current_extra_message_index;
LOG_PRINT_GREEN("Found block for difficulty: " << local_diff, LOG_LEVEL_0);
if(!m_phandler->handle_block_found(b))
{
--m_config.current_extra_message_index;
}else
{
//success update, lets update config
epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME);
}
}
nonce+=m_threads_total;
++m_hashes;
}
slow_hash_free_state();
LOG_PRINT_L0("Miner thread stopped ["<< th_local_index << "]");
return true;
}
//-----------------------------------------------------------------------------------------------------
}
<commit_msg>miner: do not try to save config if the path isn't set<commit_after>// Copyright (c) 2014-2016, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <sstream>
#include <numeric>
#include <boost/utility/value_init.hpp>
#include <boost/interprocess/detail/atomic.hpp>
#include <boost/limits.hpp>
#include <boost/foreach.hpp>
#include "misc_language.h"
#include "include_base_utils.h"
#include "cryptonote_basic_impl.h"
#include "cryptonote_format_utils.h"
#include "file_io_utils.h"
#include "common/command_line.h"
#include "string_coding.h"
#include "storages/portable_storage_template_helper.h"
using namespace epee;
#include "miner.h"
extern "C" void slow_hash_allocate_state();
extern "C" void slow_hash_free_state();
namespace cryptonote
{
namespace
{
const command_line::arg_descriptor<std::string> arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true};
const command_line::arg_descriptor<std::string> arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true};
const command_line::arg_descriptor<uint32_t> arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true};
}
miner::miner(i_miner_handler* phandler):m_stop(1),
m_template(boost::value_initialized<block>()),
m_template_no(0),
m_diffic(0),
m_thread_index(0),
m_phandler(phandler),
m_height(0),
m_pausers_count(0),
m_threads_total(0),
m_starter_nonce(0),
m_last_hr_merge_time(0),
m_hashes(0),
m_do_print_hashrate(false),
m_do_mining(false),
m_current_hash_rate(0)
{
}
//-----------------------------------------------------------------------------------------------------
miner::~miner()
{
stop();
}
//-----------------------------------------------------------------------------------------------------
bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height)
{
CRITICAL_REGION_LOCAL(m_template_lock);
m_template = bl;
m_diffic = di;
m_height = height;
++m_template_no;
m_starter_nonce = crypto::rand<uint32_t>();
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::on_block_chain_update()
{
if(!is_mining())
return true;
return request_block_template();
}
//-----------------------------------------------------------------------------------------------------
bool miner::request_block_template()
{
block bl = AUTO_VAL_INIT(bl);
difficulty_type di = AUTO_VAL_INIT(di);
uint64_t height = AUTO_VAL_INIT(height);
cryptonote::blobdata extra_nonce;
if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size())
{
extra_nonce = m_extra_messages[m_config.current_extra_message_index];
}
if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce))
{
LOG_ERROR("Failed to get_block_template(), stopping mining");
return false;
}
set_block_template(bl, di, height);
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::on_idle()
{
m_update_block_template_interval.do_call([&](){
if(is_mining())request_block_template();
return true;
});
m_update_merge_hr_interval.do_call([&](){
merge_hr();
return true;
});
return true;
}
//-----------------------------------------------------------------------------------------------------
void miner::do_print_hashrate(bool do_hr)
{
m_do_print_hashrate = do_hr;
}
//-----------------------------------------------------------------------------------------------------
void miner::merge_hr()
{
if(m_last_hr_merge_time && is_mining())
{
m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1));
CRITICAL_REGION_LOCAL(m_last_hash_rates_lock);
m_last_hash_rates.push_back(m_current_hash_rate);
if(m_last_hash_rates.size() > 19)
m_last_hash_rates.pop_front();
if(m_do_print_hashrate)
{
uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0);
float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size());
std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << ENDL;
}
}
m_last_hr_merge_time = misc_utils::get_tick_count();
m_hashes = 0;
}
//-----------------------------------------------------------------------------------------------------
void miner::init_options(boost::program_options::options_description& desc)
{
command_line::add_arg(desc, arg_extra_messages);
command_line::add_arg(desc, arg_start_mining);
command_line::add_arg(desc, arg_mining_threads);
}
//-----------------------------------------------------------------------------------------------------
bool miner::init(const boost::program_options::variables_map& vm, bool testnet)
{
if(command_line::has_arg(vm, arg_extra_messages))
{
std::string buff;
bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff);
CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages));
std::vector<std::string> extra_vec;
boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on );
m_extra_messages.resize(extra_vec.size());
for(size_t i = 0; i != extra_vec.size(); i++)
{
string_tools::trim(extra_vec[i]);
if(!extra_vec[i].size())
continue;
std::string buff = string_encoding::base64_decode(extra_vec[i]);
if(buff != "0")
m_extra_messages[i] = buff;
}
m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string();
m_config = AUTO_VAL_INIT(m_config);
epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME);
LOG_PRINT_L0("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index);
}
if(command_line::has_arg(vm, arg_start_mining))
{
if(!cryptonote::get_account_address_from_str(m_mine_address, testnet, command_line::get_arg(vm, arg_start_mining)))
{
LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled");
return false;
}
m_threads_total = 1;
m_do_mining = true;
if(command_line::has_arg(vm, arg_mining_threads))
{
m_threads_total = command_line::get_arg(vm, arg_mining_threads);
}
}
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::is_mining() const
{
return !m_stop;
}
//-----------------------------------------------------------------------------------------------------
const account_public_address& miner::get_mining_address() const
{
return m_mine_address;
}
//-----------------------------------------------------------------------------------------------------
uint32_t miner::get_threads_count() const {
return m_threads_total;
}
//-----------------------------------------------------------------------------------------------------
bool miner::start(const account_public_address& adr, size_t threads_count, const boost::thread::attributes& attrs)
{
m_mine_address = adr;
m_threads_total = static_cast<uint32_t>(threads_count);
m_starter_nonce = crypto::rand<uint32_t>();
CRITICAL_REGION_LOCAL(m_threads_lock);
if(is_mining())
{
LOG_ERROR("Starting miner but it's already started");
return false;
}
if(!m_threads.empty())
{
LOG_ERROR("Unable to start miner because there are active mining threads");
return false;
}
if(!m_template_no)
request_block_template();//lets update block template
boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0);
boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0);
for(size_t i = 0; i != threads_count; i++)
{
m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this)));
}
LOG_PRINT_L0("Mining has started with " << threads_count << " threads, good luck!" );
return true;
}
//-----------------------------------------------------------------------------------------------------
uint64_t miner::get_speed() const
{
if(is_mining()) {
return m_current_hash_rate;
}
else {
return 0;
}
}
//-----------------------------------------------------------------------------------------------------
void miner::send_stop_signal()
{
boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1);
}
//-----------------------------------------------------------------------------------------------------
bool miner::stop()
{
if (!is_mining())
return true;
send_stop_signal();
CRITICAL_REGION_LOCAL(m_threads_lock);
BOOST_FOREACH(boost::thread& th, m_threads)
th.join();
LOG_PRINT_L0("Mining has been stopped, " << m_threads.size() << " finished" );
m_threads.clear();
return true;
}
//-----------------------------------------------------------------------------------------------------
bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height)
{
for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++)
{
crypto::hash h;
get_block_longhash(bl, h, height);
if(check_hash(h, diffic))
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------------------
void miner::on_synchronized()
{
if(m_do_mining)
{
boost::thread::attributes attrs;
attrs.set_stack_size(THREAD_STACK_SIZE);
start(m_mine_address, m_threads_total, attrs);
}
}
//-----------------------------------------------------------------------------------------------------
void miner::pause()
{
CRITICAL_REGION_LOCAL(m_miners_count_lock);
++m_pausers_count;
if(m_pausers_count == 1 && is_mining())
LOG_PRINT_L2("MINING PAUSED");
}
//-----------------------------------------------------------------------------------------------------
void miner::resume()
{
CRITICAL_REGION_LOCAL(m_miners_count_lock);
--m_pausers_count;
if(m_pausers_count < 0)
{
m_pausers_count = 0;
LOG_PRINT_RED_L0("Unexpected miner::resume() called");
}
if(!m_pausers_count && is_mining())
LOG_PRINT_L2("MINING RESUMED");
}
//-----------------------------------------------------------------------------------------------------
bool miner::worker_thread()
{
uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index);
LOG_PRINT_L0("Miner thread was started ["<< th_local_index << "]");
log_space::log_singletone::set_thread_log_prefix(std::string("[miner ") + std::to_string(th_local_index) + "]");
uint32_t nonce = m_starter_nonce + th_local_index;
uint64_t height = 0;
difficulty_type local_diff = 0;
uint32_t local_template_ver = 0;
block b;
slow_hash_allocate_state();
while(!m_stop)
{
if(m_pausers_count)//anti split workaround
{
misc_utils::sleep_no_w(100);
continue;
}
if(local_template_ver != m_template_no)
{
CRITICAL_REGION_BEGIN(m_template_lock);
b = m_template;
local_diff = m_diffic;
height = m_height;
CRITICAL_REGION_END();
local_template_ver = m_template_no;
nonce = m_starter_nonce + th_local_index;
}
if(!local_template_ver)//no any set_block_template call
{
LOG_PRINT_L2("Block template not set yet");
epee::misc_utils::sleep_no_w(1000);
continue;
}
b.nonce = nonce;
crypto::hash h;
get_block_longhash(b, h, height);
if(check_hash(h, local_diff))
{
//we lucky!
++m_config.current_extra_message_index;
LOG_PRINT_GREEN("Found block for difficulty: " << local_diff, LOG_LEVEL_0);
if(!m_phandler->handle_block_found(b))
{
--m_config.current_extra_message_index;
}else
{
//success update, lets update config
if (!m_config_folder_path.empty())
epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME);
}
}
nonce+=m_threads_total;
++m_hashes;
}
slow_hash_free_state();
LOG_PRINT_L0("Miner thread stopped ["<< th_local_index << "]");
return true;
}
//-----------------------------------------------------------------------------------------------------
}
<|endoftext|> |
<commit_before>/*
This file is part of libhttpserver
Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include "details/http_endpoint.hpp"
#include "http_utils.hpp"
#include "string_utilities.hpp"
using namespace std;
namespace httpserver
{
using namespace http;
namespace details
{
http_endpoint::~http_endpoint()
{
if(reg_compiled)
{
regfree(&(this->re_url_modded));
}
}
http_endpoint::http_endpoint
(
const string& url,
bool family,
bool registration,
bool use_regex
):
family_url(family),
reg_compiled(false)
{
if(use_regex)
this->url_modded = "^/";
else
this->url_modded = "/";
vector<string> parts;
#ifdef CASE_INSENSITIVE
string_utilities::to_lower_copy(url, url_complete);
#else
url_complete = url;
#endif
if(url_complete[0] != '/')
url_complete = "/" + url_complete;
http_utils::tokenize_url(url, parts);
string buffered;
bool first = true;
if(registration)
{
for(unsigned int i = 0; i< parts.size(); i++)
{
if((parts[i] != "") && (parts[i][0] != '{'))
{
if(first)
{
if(parts[i][0] == '^')
{
this->url_modded = parts[i];
}
else
{
this->url_modded += parts[i];
}
first = false;
}
else
{
this->url_modded += "/" + parts[i];
}
}
else
{
if(
(parts[i].size() >= 3) &&
(parts[i][0] == '{') &&
(parts[i][parts[i].size() - 1] == '}')
)
{
std::string::size_type bar = parts[i].find_first_of('|');
if(bar != string::npos)
{
this->url_pars.push_back(parts[i].substr(1, bar - 1));
if(first)
{
this->url_modded += parts[i].substr(
bar + 1, parts[i].size() - bar - 2
);
first = false;
}
else
{
this->url_modded += "/"+parts[i].substr(
bar + 1, parts[i].size() - bar - 2
);
}
}
else
{
this->url_pars.push_back(
parts[i].substr(1,parts[i].size() - 2)
);
if(first)
{
this->url_modded += "([^\\/]+)";
first = false;
}
else
{
this->url_modded += "/([^\\/]+)";
}
}
this->chunk_positions.push_back(i);
}
else
{
throw bad_http_endpoint();
}
}
this->url_pieces.push_back(parts[i]);
}
}
else
{
for(unsigned int i = 0; i< parts.size(); i++)
{
if(first)
{
this->url_modded += parts[i];
first = false;
}
else
{
this->url_modded += "/" + parts[i];
}
this->url_pieces.push_back(parts[i]);
}
}
if(use_regex)
{
this->url_modded += "$";
regcomp(&(this->re_url_modded), url_modded.c_str(),
REG_EXTENDED|REG_ICASE|REG_NOSUB
);
reg_compiled = true;
}
}
http_endpoint::http_endpoint(const http_endpoint& h):
url_complete(h.url_complete),
url_modded(h.url_modded),
url_pars(h.url_pars),
url_pieces(h.url_pieces),
chunk_positions(h.chunk_positions),
family_url(h.family_url),
reg_compiled(h.reg_compiled)
{
if(this->reg_compiled)
regcomp(&(this->re_url_modded), url_modded.c_str(),
REG_EXTENDED|REG_ICASE|REG_NOSUB
);
}
http_endpoint& http_endpoint::operator =(const http_endpoint& h)
{
this->url_complete = h.url_complete;
this->url_modded = h.url_modded;
this->family_url = h.family_url;
this->reg_compiled = h.reg_compiled;
if(this->reg_compiled)
regcomp(&(this->re_url_modded), url_modded.c_str(),
REG_EXTENDED|REG_ICASE|REG_NOSUB
);
this->url_pars = h.url_pars;
this->url_pieces = h.url_pieces;
this->chunk_positions = h.chunk_positions;
return *this;
}
bool http_endpoint::operator <(const http_endpoint& b) const
{
COMPARATOR(this->url_modded, b.url_modded, std::toupper);
}
bool http_endpoint::match(const http_endpoint& url) const
{
if(this->family_url && (url.url_pieces.size() >= this->url_pieces.size()))
{
string nn = "/";
bool first = true;
for(unsigned int i = 0; i < this->url_pieces.size(); i++)
{
if(first)
{
nn += url.url_pieces[i];
first = false;
}
else
{
nn += "/" + url.url_pieces[i];
}
}
return regexec(&(this->re_url_modded), nn.c_str(), 0, NULL, 0) == 0;
}
else
return regexec(&(this->re_url_modded),
url.url_complete.c_str(), 0, NULL, 0) == 0;
}
};
};
<commit_msg>Linearized code to make it more readable<commit_after>/*
This file is part of libhttpserver
Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include "details/http_endpoint.hpp"
#include "http_utils.hpp"
#include "string_utilities.hpp"
using namespace std;
namespace httpserver
{
using namespace http;
namespace details
{
http_endpoint::~http_endpoint()
{
if(reg_compiled)
{
regfree(&(this->re_url_modded));
}
}
http_endpoint::http_endpoint
(
const string& url,
bool family,
bool registration,
bool use_regex
):
family_url(family),
reg_compiled(false)
{
this->url_modded = use_regex ? "^/" : "/";
vector<string> parts;
#ifdef CASE_INSENSITIVE
string_utilities::to_lower_copy(url, url_complete);
#else
url_complete = url;
#endif
if(url_complete[0] != '/')
url_complete = "/" + url_complete;
http_utils::tokenize_url(url, parts);
string buffered;
bool first = true;
for (unsigned int i = 0; i < parts.size(); i++)
{
if(!registration)
{
this->url_modded += (first ? "" : "/") + parts[i];
first = false;
this->url_pieces.push_back(parts[i]);
continue;
}
if((parts[i] != "") && (parts[i][0] != '{'))
{
this->url_modded = (first ? "" : "/") + (parts[i][0] == '^' ? "" : this->url_modded) + parts[i];
first = false;
this->url_pieces.push_back(parts[i]);
continue;
}
if((parts[i].size() < 3) || (parts[i][0] != '{') || (parts[i][parts[i].size() - 1] != '}'))
throw bad_http_endpoint();
std::string::size_type bar = parts[i].find_first_of('|');
this->url_pars.push_back(parts[i].substr(1, bar != string::npos ? bar - 1 : parts[i].size() - bar - 2));
this->url_modded += (first ? "" : "/") + (bar != string::npos ? parts[i].substr(bar + 1, parts[i].size() - bar - 2) : "([^\\/]+)");
first = false;
this->chunk_positions.push_back(i);
this->url_pieces.push_back(parts[i]);
}
if(use_regex)
{
this->url_modded += "$";
regcomp(&(this->re_url_modded), url_modded.c_str(),
REG_EXTENDED|REG_ICASE|REG_NOSUB
);
this->reg_compiled = true;
}
}
http_endpoint::http_endpoint(const http_endpoint& h):
url_complete(h.url_complete),
url_modded(h.url_modded),
url_pars(h.url_pars),
url_pieces(h.url_pieces),
chunk_positions(h.chunk_positions),
family_url(h.family_url),
reg_compiled(h.reg_compiled)
{
if(this->reg_compiled)
regcomp(&(this->re_url_modded), url_modded.c_str(),
REG_EXTENDED|REG_ICASE|REG_NOSUB
);
}
http_endpoint& http_endpoint::operator =(const http_endpoint& h)
{
this->url_complete = h.url_complete;
this->url_modded = h.url_modded;
this->family_url = h.family_url;
this->reg_compiled = h.reg_compiled;
if(this->reg_compiled)
regcomp(&(this->re_url_modded), url_modded.c_str(),
REG_EXTENDED|REG_ICASE|REG_NOSUB
);
this->url_pars = h.url_pars;
this->url_pieces = h.url_pieces;
this->chunk_positions = h.chunk_positions;
return *this;
}
bool http_endpoint::operator <(const http_endpoint& b) const
{
COMPARATOR(this->url_modded, b.url_modded, std::toupper);
}
bool http_endpoint::match(const http_endpoint& url) const
{
if(!this->family_url || url.url_pieces.size() < this->url_pieces.size())
return regexec(&(this->re_url_modded), url.url_complete.c_str(), 0, NULL, 0) == 0;
string nn = "/";
bool first = true;
for(unsigned int i = 0; i < this->url_pieces.size(); i++)
{
nn += (first ? "" : "/") + url.url_pieces[i];
first = false;
}
return regexec(&(this->re_url_modded), nn.c_str(), 0, NULL, 0) == 0;
}
};
};
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <string>
#include <map>
#include <sstream>
#include <ext/hash_map>
namespace ext = __gnu_cxx;
typedef std::map< std::string, std::string > AttributeValueMap;
typedef bool (*ActionHandler)( AttributeValueMap & avm, std::string & reply );
typedef std::map< std::string, ActionHandler > ActionToHandlerMap;
/*
* The GAHP uses the following functions from the Query API:
*
* RunInstances
* TerminateInstances
* DescribeInstances
* CreateKeyPair
* DeleteKeyPair
* DescribeKeyPairs
*/
/*
* Inexplicably, this isn't one of the standard specializations.
* Even less explicably, you can't use namespace aliases to open a namespace.
*
* However, by supplying this specialization, all of the ext::hash_maps using
* std::string as a key work without further ado.
*/
namespace __gnu_cxx {
template<> struct hash< std::string > {
size_t operator()( const std::string & s ) const {
return __stl_hash_string( s.c_str() );
}
};
}
typedef struct {
} Group;
typedef ext::hash_map< std::string, Group > NameToGroupMap;
typedef struct {
std::string privateKey;
} Keypair;
typedef ext::hash_map< std::string, Keypair > NameToKeypairMap;
typedef struct {
std::string imageID;
std::string privateDNSName;
std::string publicDNSName;
std::string instanceType;
std::string instanceState;
std::string keyName;
ext::hash_map< std::string, const Group * > groups;
} Instance;
typedef ext::hash_map< std::string, Instance > InstanceIDToInstanceMap;
typedef struct {
NameToKeypairMap keypairs;
NameToGroupMap groups;
InstanceIDToInstanceMap instances;
} User;
typedef ext::hash_map< std::string, User > AccessKeyIDToUserMap;
// Global. Eww.
AccessKeyIDToUserMap users;
void registerTestUsers() {
users[ "1" ] = User();
users[ "2" ] = User();
}
// The compiler seems unwilling or unable to infer return types; GregT
// speculated that this might be because templated functions are in their
// own namespace, but getObject<>() doesn't infer the return type, either.
template< class V, class T, class K > V getObject( const T & map, const K & key, bool & found ) {
class T::const_iterator ci = map.find( key );
if( map.end() == ci ) {
found = false;
return V();
}
found = true;
return ci->second;
}
bool handleRunInstances( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleRunInstances()\n" );
return false;
}
bool handleTerminateInstances( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleTerminateInstances()\n" );
bool found = false;
std::string userID = getObject< std::string >( avm, "AWSAccessKeyId", found );
if( (!found) || userID.empty() ) {
fprintf( stderr, "DEBUG: failed to find AWSAccessKeyId in query.\n" );
reply = "Required parameter AWSAccessKeyId missing or empty.\n";
return false;
}
User user = getObject< User >( users, userID, found );
if( ! found ) {
fprintf( stderr, "Failed to find user identified by '%s'.\n", userID.c_str() );
reply = "Required parameter ASWAccessKeyId invalid.\n";
return false;
}
std::string instanceID = getObject< std::string >( avm, "InstanceId.1", found );
if( ! found || instanceID.empty() ) {
fprintf( stderr, "DEBUG: failed to find instanceID in query.\n" );
reply = "Required parameter InstanceId.1 missing or empty.\n";
return false;
}
Instance instance = getObject< Instance >( user.instances, instanceID, found );
if( ! found ) {
std::ostringstream error;
error << "Instance ID '" << instanceID << "' does not exist." << std::endl;
fprintf( stderr, "%s", error.str().c_str() );
reply = error.str();
return false;
}
// FIXME...
return false;
}
bool handleDescribeInstances( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleDescribeInstances()\n" );
return false;
}
bool handleCreateKeyPair( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleCreateKeyPair()\n" );
return false;
}
bool handleDeleteKeyPair( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleDeleteKeyPair()\n" );
return false;
}
bool handleDescribeKeyPairs( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleDescribeKeyPairs()\n" );
return false;
}
// Global. Eww.
ActionToHandlerMap simulatorActions;
void registerAllHandlers() {
simulatorActions[ "RunInstances" ] = & handleRunInstances;
simulatorActions[ "TerminateInstances" ] = & handleTerminateInstances;
simulatorActions[ "DescribeInstances" ] = & handleDescribeInstances;
simulatorActions[ "CreateKeyPair" ] = & handleCreateKeyPair;
simulatorActions[ "DeleteKeyPair" ] = & handleDeleteKeyPair;
simulatorActions[ "DescribeKeyPairs" ] = & handleDescribeKeyPairs;
}
// m/^Host: <host>\r\n/
bool extractHost( const std::string & request, std::string & host ) {
std::string::size_type i = request.find( "\r\nHost: " );
if( std::string::npos == i ) {
fprintf( stderr, "Malformed request '%s': contains no Host header; failing.\n", request.c_str() );
return false;
}
std::string::size_type j = request.find( "\r\n", i + 2 );
if( std::string::npos == j ) {
fprintf( stderr, "Malformed request '%s': Host field not CR/LF terminated; failing.\n", request.c_str() );
return false;
}
host = request.substr( i + 8, j - (i + 8) );
return true;
}
// m/^GET <URL> HTTP/
bool extractURL( const std::string & request, std::string & URL ) {
if( request.find( "GET " ) != 0 ) {
fprintf( stderr, "Malformed request '%s': did not begin with 'GET '; failing.\n", request.c_str() );
return false;
}
URL = request.substr( 4, request.find( "HTTP" ) - 5 );
return true;
}
/*
* The most fragile part of the EC2 GAHP is the query signing, so
* we'd like to validate it. See the comments in amazonCommands.cpp
* for more details.
*
* This function is presently a stub because I haven't solved the
* problem of key distribution between the tester and the simulator.
*/
bool validateSignature( std::string & method,
const std::string & host,
const std::string & URL,
const AttributeValueMap & queryParameters ) {
return true;
}
std::string constructReply( const std::string & statusLine, const std::string & response ) {
std::ostringstream reply;
// The ec2_gahp doesn't ever look at the headers.
reply << statusLine << "\r\n";
reply << "Content-Length: " << response.size() << "\r\n";
reply << "\r\n";
reply << response;
reply << "\r\n";
return reply.str();
}
std::string handleRequest( const std::string & request ) {
std::string URL;
if( ! extractURL( request, URL ) ) {
return constructReply( "HTTP/1.1 400 Bad Request", "" );
}
std::string host;
if( ! extractHost( request, host ) ) {
return constructReply( "HTTP/1.1 400 Bad Request", "" );
}
std::transform( host.begin(), host.end(), host.begin(), & tolower );
// fprintf( stderr, "DEBUG: found 'http://%s%s'\n", host.c_str(), URL.c_str() );
AttributeValueMap queryParameters;
std::string::size_type i = URL.find( "?" );
while( i < URL.size() ) {
// Properly encoded URLs will only have ampersands between
// the key-value pairs, and equals between keys and values.
std::string::size_type equalsIdx = URL.find( "=", i + 1 );
if( std::string::npos == equalsIdx ) {
std::ostringstream error;
error << "Malformed URL '" << URL << "': attribute without value; failing" << std::endl;
fprintf( stderr, error.str().c_str() );
return constructReply( "HTTP/1.1 400 Bad Request", error.str() );
}
std::string::size_type ampersandIdx = URL.find( "&", i + 1 );
if( std::string::npos == ampersandIdx ) {
ampersandIdx = URL.size();
}
std::string key = URL.substr( i + 1, equalsIdx - (i + 1) );
std::string value = URL.substr( equalsIdx + 1, ampersandIdx - (equalsIdx + 1 ) );
// fprintf( stderr, "DEBUG: key = '%s', value = '%s'\n", key.c_str(), value.c_str() );
queryParameters[ key ] = value;
i = ampersandIdx;
}
std::string method = "GET";
if( ! validateSignature( method, host, URL, queryParameters ) ) {
return constructReply( "HTTP/1.1 401 Unauthorized", "Failed signature validation." );
}
std::string action = queryParameters[ "Action" ];
if( action.empty() ) {
return constructReply( "HTTP/1.1 400 Bad Request", "No action specified." );
}
std::string response;
ActionToHandlerMap::const_iterator ci = simulatorActions.find( action );
if( simulatorActions.end() == ci ) {
std::ostringstream error;
error << "Action '" << action << "' not found." << std::endl;
fprintf( stderr, error.str().c_str() );
return constructReply( "HTTP/1.1 404 Not Found", error.str() );
}
if( (*(ci->second))( queryParameters, response ) ) {
return constructReply( "HTTP/1.1 200 OK", response );
} else {
return constructReply( "HTTP/1.1 406 Not Acceptable", response );
}
}
void handleConnection( int sockfd ) {
ssize_t bytesRead;
char buffer[1024+1];
std::string request;
while( 1 ) {
bytesRead = read( sockfd, (void *) buffer, 1024 );
if( bytesRead == -1 ) {
if( errno == EINTR ) {
fprintf( stderr, "read() interrupted, retrying.\n" );
continue;
}
fprintf( stderr, "read() failed (%d): '%s'\n", errno, strerror( errno ) );
return;
}
if( bytesRead == 0 ) {
close( sockfd );
return;
}
buffer[bytesRead] = '\0';
request += buffer;
// fprintf( stderr, "DEBUG: request is now '%s'.\n", request.c_str() );
// A given HTTP request is terminated by a blank line.
std::string::size_type index = request.find( "\r\n\r\n" );
while( index != std::string::npos ) {
std::string firstRequest = request.substr( 0, index + 4 );
request = request.substr( index + 4 );
// if( ! request.empty() ) { fprintf( stderr, "DEBUG: request remainder '%s'\n", request.c_str() ); }
// fprintf( stderr, "DEBUG: handling request '%s'\n", firstRequest.c_str() );
std::string reply = handleRequest( firstRequest );
if( ! reply.empty() ) {
// fprintf( stderr, "DEBUG: writing reply '%s'\n", reply.c_str() );
ssize_t totalBytesWritten = 0;
ssize_t bytesToWrite = reply.size();
const char * outBuf = reply.c_str();
while( totalBytesWritten != bytesToWrite ) {
ssize_t bytesWritten = write( sockfd,
outBuf + totalBytesWritten,
bytesToWrite - totalBytesWritten );
if( bytesWritten == -1 ) {
fprintf( stderr, "write() failed (%d), '%s'; aborting reply.\n", errno, strerror( errno ) );
close( sockfd );
return;
}
totalBytesWritten += bytesWritten;
}
}
index = request.find( "\r\n\r\n" );
}
}
}
// FIXME: sigterm handler to dump diagnostics and gracefully exit. See
// the condor_amazon simulator.
int main( int argc, char ** argv ) {
int listenSocket = socket( PF_INET, SOCK_STREAM, 0 );
if( listenSocket == -1 ) {
fprintf( stderr, "socket() failed (%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 1 );
}
struct sockaddr_in listenAddr;
listenAddr.sin_family = AF_INET;
listenAddr.sin_port = htons( 21737 );
listenAddr.sin_addr.s_addr = INADDR_ANY;
int rv = bind( listenSocket, (struct sockaddr *)(& listenAddr), sizeof( listenAddr ) );
if( rv != 0 ) {
fprintf( stderr, "bind() failed (%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 2 );
}
rv = listen( listenSocket, 0 );
if( rv != 0 ) {
fprintf( stderr, "listen() failed (%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 3 );
}
registerAllHandlers();
registerTestUsers();
while( 1 ) {
struct sockaddr_in remoteAddr;
socklen_t raSize = sizeof( remoteAddr );
int remoteSocket = accept( listenSocket, (struct sockaddr *)(& remoteAddr), & raSize );
if( remoteSocket == -1 ) {
fprintf( stderr, "accept() failed(%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 4 );
}
handleConnection( remoteSocket );
}
return 0;
} // end main()
<commit_msg>(#1821) Tracking commit.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <string>
#include <map>
#include <sstream>
#include <ext/hash_map>
namespace ext = __gnu_cxx;
typedef std::map< std::string, std::string > AttributeValueMap;
typedef bool (*ActionHandler)( AttributeValueMap & avm, std::string & reply );
typedef std::map< std::string, ActionHandler > ActionToHandlerMap;
/*
* The GAHP uses the following functions from the Query API:
*
* RunInstances
* TerminateInstances
* DescribeInstances
* CreateKeyPair
* DeleteKeyPair
* DescribeKeyPairs
*/
/*
* Inexplicably, this isn't one of the standard specializations.
* Even less explicably, you can't use namespace aliases to open a namespace.
*
* However, by supplying this specialization, all of the ext::hash_maps using
* std::string as a key work without further ado.
*/
namespace __gnu_cxx {
template<> struct hash< std::string > {
size_t operator()( const std::string & s ) const {
return __stl_hash_string( s.c_str() );
}
};
}
typedef struct {
} Group;
typedef ext::hash_map< std::string, Group > NameToGroupMap;
typedef struct {
std::string privateKey;
} Keypair;
typedef ext::hash_map< std::string, Keypair > NameToKeypairMap;
typedef struct {
std::string imageID;
std::string privateDNSName;
std::string publicDNSName;
std::string instanceType;
std::string instanceState;
std::string keyName;
ext::hash_map< std::string, const Group * > groups;
} Instance;
typedef ext::hash_map< std::string, Instance > InstanceIDToInstanceMap;
typedef struct {
NameToKeypairMap keypairs;
NameToGroupMap groups;
InstanceIDToInstanceMap instances;
} User;
typedef ext::hash_map< std::string, User > AccessKeyIDToUserMap;
// Global. Eww.
AccessKeyIDToUserMap users;
void registerTestUsers() {
users[ "1" ] = User();
users[ "2" ] = User();
}
// The compiler seems unwilling or unable to infer return types; GregT
// speculated that this might be because templated functions are in their
// own namespace, but getObject<>() doesn't infer the return type, either.
template< class V, class T, class K > V getObject( const T & map, const K & key, bool & found ) {
class T::const_iterator ci = map.find( key );
if( map.end() == ci ) {
found = false;
return V();
}
found = true;
return ci->second;
}
bool validateAndAcquireUser( AttributeValueMap & avm, std::string & userID, User & user, std::string & reply ) {
bool found = false;
userID = getObject< std::string >( avm, "AWSAccessKeyId", found );
if( (!found) || userID.empty() ) {
fprintf( stderr, "DEBUG: failed to find AWSAccessKeyId in query.\n" );
reply = "Required parameter AWSAccessKeyId missing or empty.\n";
return false;
}
user = getObject< User >( users, userID, found );
if( ! found ) {
fprintf( stderr, "Failed to find user identified by '%s'.\n", userID.c_str() );
reply = "Required parameter ASWAccessKeyId invalid.\n";
return false;
}
return true;
}
bool handleRunInstances( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleRunInstances()\n" );
std::string userID;
User user;
bool found = validateAndAcquireUser( avm, userID, user, reply );
if( ! found ) { return false; }
// Validate the ImageId, MinCount, and MaxCount parameters, as well
// as the optional parameters KeyName, InstanceType, SecurityGroup*,
// and UserData.
// We presently assume all imageIDs are valid.
std::string imageID = getObject< std::string >( avm, "ImageId", found );
if( (! found) || imageID.empty() ) {
fprintf( stderr, "Failed to find imageID in query.\n" );
reply = "Required parameter ImageId missing or empty.\n";
return false;
}
std::string minCount = getObject< std::string >( avm, "MinCount", found );
if( (! found) || minCount.empty() ) {
fprintf( stderr, "Failed to find minCount in query.\n" );
reply = "Required parameter MinCount missing or empty.\n";
return false;
}
std::string maxCount = getObject< std::string >( avm, "MaxCount", found );
if( (! found) || maxCount.empty() ) {
fprintf( stderr, "Failed to find maxCount in query.\n" );
reply = "Required parameter MaxCount missing or empty.\n";
return false;
}
// FIXME: Verify that maxCount >= minCount.
std::string keyName = getObject< std::string >( avm, "KeyName", found );
if( ! keyName.empty() ) {
// FIXME: Verify that this keypair exists.
}
// We presently assume all instanceTypes are valid.
std::string instanceType = getObject< std::string >( avm, "InstanceType", found );
std::string userData = getObject< std::string >( avm, "UserData", found );
if( ! userData.empty() ) {
// FIXME: Verify that the user data is Base64-encoded.
}
std::vector< std::string > securityGroupNames;
for( int i = 1; ; ++i ) {
std::ostringstream sgParameterName;
sgParameterName << "SecurityGroup." << i;
std::string sgName = getObject< std::string >( avm, sgParameterName.str(), found );
if( ! found ) { break; }
if( sgName.empty() ) {
std::ostringstream error;
error << "Optional parameter " << sgName << " must not be empty." << std::endl;
reply = error.str();
fprintf( stderr, "%s", reply.c_str() );
return false;
}
// FIXME: Verify that the group sgName exists.
}
// FIXME: create the corresponding Instance.
return true;
}
bool handleTerminateInstances( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleTerminateInstances()\n" );
std::string userID;
User user;
bool found = validateAndAcquireUser( avm, userID, user, reply );
if( ! found ) { return false; }
std::string instanceID = getObject< std::string >( avm, "InstanceId.1", found );
if( (! found) || instanceID.empty() ) {
fprintf( stderr, "DEBUG: failed to find instanceID in query.\n" );
reply = "Required parameter InstanceId.1 missing or empty.\n";
return false;
}
Instance instance = getObject< Instance >( user.instances, instanceID, found );
if( ! found ) {
std::ostringstream error;
error << "Instance ID '" << instanceID << "' does not exist." << std::endl;
reply = error.str();
fprintf( stderr, "%s", reply.c_str() );
return false;
}
reply = "// FIXME: spam out some XML.\n";
return true;
}
bool handleDescribeInstances( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleDescribeInstances()\n" );
return false;
}
bool handleCreateKeyPair( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleCreateKeyPair()\n" );
return false;
}
bool handleDeleteKeyPair( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleDeleteKeyPair()\n" );
return false;
}
bool handleDescribeKeyPairs( AttributeValueMap & avm, std::string & reply ) {
fprintf( stderr, "handleDescribeKeyPairs()\n" );
return false;
}
// Global. Eww.
ActionToHandlerMap simulatorActions;
void registerAllHandlers() {
simulatorActions[ "RunInstances" ] = & handleRunInstances;
simulatorActions[ "TerminateInstances" ] = & handleTerminateInstances;
simulatorActions[ "DescribeInstances" ] = & handleDescribeInstances;
simulatorActions[ "CreateKeyPair" ] = & handleCreateKeyPair;
simulatorActions[ "DeleteKeyPair" ] = & handleDeleteKeyPair;
simulatorActions[ "DescribeKeyPairs" ] = & handleDescribeKeyPairs;
}
// m/^Host: <host>\r\n/
bool extractHost( const std::string & request, std::string & host ) {
std::string::size_type i = request.find( "\r\nHost: " );
if( std::string::npos == i ) {
fprintf( stderr, "Malformed request '%s': contains no Host header; failing.\n", request.c_str() );
return false;
}
std::string::size_type j = request.find( "\r\n", i + 2 );
if( std::string::npos == j ) {
fprintf( stderr, "Malformed request '%s': Host field not CR/LF terminated; failing.\n", request.c_str() );
return false;
}
host = request.substr( i + 8, j - (i + 8) );
return true;
}
// m/^GET <URL> HTTP/
bool extractURL( const std::string & request, std::string & URL ) {
if( request.find( "GET " ) != 0 ) {
fprintf( stderr, "Malformed request '%s': did not begin with 'GET '; failing.\n", request.c_str() );
return false;
}
URL = request.substr( 4, request.find( "HTTP" ) - 5 );
return true;
}
/*
* The most fragile part of the EC2 GAHP is the query signing, so
* we'd like to validate it. See the comments in amazonCommands.cpp
* for more details.
*
* This function is presently a stub because I haven't solved the
* problem of key distribution between the tester and the simulator.
*
* Validates parameters:
* Signature,
* SignatureVersion
* SignatureMethod
* Timestamp
* Version
*
*/
bool validateSignature( std::string & method,
const std::string & host,
const std::string & URL,
const AttributeValueMap & queryParameters ) {
return true;
}
std::string constructReply( const std::string & statusLine, const std::string & response ) {
std::ostringstream reply;
// The ec2_gahp doesn't ever look at the headers.
reply << statusLine << "\r\n";
reply << "Content-Length: " << response.size() << "\r\n";
reply << "\r\n";
reply << response;
reply << "\r\n";
return reply.str();
}
std::string handleRequest( const std::string & request ) {
std::string URL;
if( ! extractURL( request, URL ) ) {
return constructReply( "HTTP/1.1 400 Bad Request", "" );
}
std::string host;
if( ! extractHost( request, host ) ) {
return constructReply( "HTTP/1.1 400 Bad Request", "" );
}
std::transform( host.begin(), host.end(), host.begin(), & tolower );
// fprintf( stderr, "DEBUG: found 'http://%s%s'\n", host.c_str(), URL.c_str() );
AttributeValueMap queryParameters;
std::string::size_type i = URL.find( "?" );
while( i < URL.size() ) {
// Properly encoded URLs will only have ampersands between
// the key-value pairs, and equals between keys and values.
std::string::size_type equalsIdx = URL.find( "=", i + 1 );
if( std::string::npos == equalsIdx ) {
std::ostringstream error;
error << "Malformed URL '" << URL << "': attribute without value; failing" << std::endl;
fprintf( stderr, error.str().c_str() );
return constructReply( "HTTP/1.1 400 Bad Request", error.str() );
}
std::string::size_type ampersandIdx = URL.find( "&", i + 1 );
if( std::string::npos == ampersandIdx ) {
ampersandIdx = URL.size();
}
std::string key = URL.substr( i + 1, equalsIdx - (i + 1) );
std::string value = URL.substr( equalsIdx + 1, ampersandIdx - (equalsIdx + 1 ) );
// fprintf( stderr, "DEBUG: key = '%s', value = '%s'\n", key.c_str(), value.c_str() );
queryParameters[ key ] = value;
i = ampersandIdx;
}
std::string method = "GET";
if( ! validateSignature( method, host, URL, queryParameters ) ) {
return constructReply( "HTTP/1.1 401 Unauthorized", "Failed signature validation." );
}
std::string action = queryParameters[ "Action" ];
if( action.empty() ) {
return constructReply( "HTTP/1.1 400 Bad Request", "No action specified." );
}
std::string response;
ActionToHandlerMap::const_iterator ci = simulatorActions.find( action );
if( simulatorActions.end() == ci ) {
std::ostringstream error;
error << "Action '" << action << "' not found." << std::endl;
fprintf( stderr, error.str().c_str() );
return constructReply( "HTTP/1.1 404 Not Found", error.str() );
}
if( (*(ci->second))( queryParameters, response ) ) {
return constructReply( "HTTP/1.1 200 OK", response );
} else {
return constructReply( "HTTP/1.1 406 Not Acceptable", response );
}
}
void handleConnection( int sockfd ) {
ssize_t bytesRead;
char buffer[1024+1];
std::string request;
while( 1 ) {
bytesRead = read( sockfd, (void *) buffer, 1024 );
if( bytesRead == -1 ) {
if( errno == EINTR ) {
fprintf( stderr, "read() interrupted, retrying.\n" );
continue;
}
fprintf( stderr, "read() failed (%d): '%s'\n", errno, strerror( errno ) );
return;
}
if( bytesRead == 0 ) {
close( sockfd );
return;
}
buffer[bytesRead] = '\0';
request += buffer;
// fprintf( stderr, "DEBUG: request is now '%s'.\n", request.c_str() );
// A given HTTP request is terminated by a blank line.
std::string::size_type index = request.find( "\r\n\r\n" );
while( index != std::string::npos ) {
std::string firstRequest = request.substr( 0, index + 4 );
request = request.substr( index + 4 );
// if( ! request.empty() ) { fprintf( stderr, "DEBUG: request remainder '%s'\n", request.c_str() ); }
// fprintf( stderr, "DEBUG: handling request '%s'\n", firstRequest.c_str() );
std::string reply = handleRequest( firstRequest );
if( ! reply.empty() ) {
// fprintf( stderr, "DEBUG: writing reply '%s'\n", reply.c_str() );
ssize_t totalBytesWritten = 0;
ssize_t bytesToWrite = reply.size();
const char * outBuf = reply.c_str();
while( totalBytesWritten != bytesToWrite ) {
ssize_t bytesWritten = write( sockfd,
outBuf + totalBytesWritten,
bytesToWrite - totalBytesWritten );
if( bytesWritten == -1 ) {
fprintf( stderr, "write() failed (%d), '%s'; aborting reply.\n", errno, strerror( errno ) );
close( sockfd );
return;
}
totalBytesWritten += bytesWritten;
}
}
index = request.find( "\r\n\r\n" );
}
}
}
// FIXME: sigterm handler to dump diagnostics and gracefully exit. See
// the condor_amazon simulator.
int main( int argc, char ** argv ) {
int listenSocket = socket( PF_INET, SOCK_STREAM, 0 );
if( listenSocket == -1 ) {
fprintf( stderr, "socket() failed (%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 1 );
}
struct sockaddr_in listenAddr;
listenAddr.sin_family = AF_INET;
listenAddr.sin_port = htons( 21737 );
listenAddr.sin_addr.s_addr = INADDR_ANY;
int rv = bind( listenSocket, (struct sockaddr *)(& listenAddr), sizeof( listenAddr ) );
if( rv != 0 ) {
fprintf( stderr, "bind() failed (%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 2 );
}
rv = listen( listenSocket, 0 );
if( rv != 0 ) {
fprintf( stderr, "listen() failed (%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 3 );
}
registerAllHandlers();
registerTestUsers();
while( 1 ) {
struct sockaddr_in remoteAddr;
socklen_t raSize = sizeof( remoteAddr );
int remoteSocket = accept( listenSocket, (struct sockaddr *)(& remoteAddr), & raSize );
if( remoteSocket == -1 ) {
fprintf( stderr, "accept() failed(%d): '%s'; aborting.\n", errno, strerror( errno ) );
exit( 4 );
}
handleConnection( remoteSocket );
}
return 0;
} // end main()
<|endoftext|> |
<commit_before><commit_msg>fix conversion again<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: line.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#define _LINE_CXX
#include <tools/link.hxx>
#include <tools/line.hxx>
#include <tools/debug.hxx>
#include <cstdlib>
#include <cmath>
inline long FRound( double fVal )
{
return( fVal > 0.0 ? (long) ( fVal + 0.5 ) : -(long) ( -fVal + 0.5 ) );
}
// --------
// - Line -
// --------
double Line::GetLength() const
{
return hypot( maStart.X() - maEnd.X(), maStart.Y() - maEnd.Y() );
}
// ------------------------------------------------------------------------
BOOL Line::Intersection( const Line& rLine, Point& rIntersection ) const
{
double fX, fY;
BOOL bRet;
if( Intersection( rLine, fX, fY ) )
{
rIntersection.X() = FRound( fX );
rIntersection.Y() = FRound( fY );
bRet = TRUE;
}
else
bRet = FALSE;
return bRet;
}
// ------------------------------------------------------------------------
BOOL Line::Intersection( const Line& rLine, double& rIntersectionX, double& rIntersectionY ) const
{
const double fAx = maEnd.X() - maStart.X();
const double fAy = maEnd.Y() - maStart.Y();
const double fBx = rLine.maStart.X() - rLine.maEnd.X();
const double fBy = rLine.maStart.Y() - rLine.maEnd.Y();
const double fDen = fAy * fBx - fAx * fBy;
BOOL bOk = FALSE;
if( fDen != 0. )
{
const double fCx = maStart.X() - rLine.maStart.X();
const double fCy = maStart.Y() - rLine.maStart.Y();
const double fA = fBy * fCx - fBx * fCy;
const BOOL bGreater = ( fDen > 0. );
bOk = TRUE;
if ( bGreater )
{
if ( ( fA < 0. ) || ( fA > fDen ) )
bOk = FALSE;
}
else if ( ( fA > 0. ) || ( fA < fDen ) )
bOk = FALSE;
if ( bOk )
{
const double fB = fAx * fCy - fAy * fCx;
if ( bGreater )
{
if ( ( fB < 0. ) || ( fB > fDen ) )
bOk = FALSE;
}
else if ( ( fB > 0. ) || ( fB < fDen ) )
bOk = FALSE;
if( bOk )
{
const double fAlpha = fA / fDen;
rIntersectionX = ( maStart.X() + fAlpha * fAx );
rIntersectionY = ( maStart.Y() + fAlpha * fAy );
}
}
}
return bOk;
}
// ------------------------------------------------------------------------
BOOL Line::Intersection( const Rectangle& rRect, Line& rIntersection ) const
{
const BOOL bStartInside = rRect.IsInside( maStart );
const BOOL bEndInside = rRect.IsInside( maEnd );
BOOL bRet = TRUE;
if( bStartInside && bEndInside )
{
// line completely inside rect
rIntersection.maStart = maStart;
rIntersection.maEnd = maEnd;
}
else
{
// calculate intersections
const Point aTL( rRect.TopLeft() ), aTR( rRect.TopRight() );
const Point aBR( rRect.BottomRight() ), aBL( rRect.BottomLeft() );
Point aIntersect1, aIntersect2;
Point* pCurIntersection = &aIntersect1;
if( Intersection( Line( aTL, aTR ), *pCurIntersection ) )
pCurIntersection = &aIntersect2;
if( Intersection( Line( aTR, aBR ), *pCurIntersection ) )
pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL;
if( pCurIntersection && Intersection( Line( aBR, aBL ), *pCurIntersection ) )
pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL;
if( pCurIntersection && Intersection( Line( aBL, aTL ), *pCurIntersection ) )
pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL;
if( !pCurIntersection )
{
// two intersections
rIntersection.maStart = aIntersect1;
rIntersection.maEnd = aIntersect2;
}
else if( pCurIntersection == &aIntersect2 )
{
// one intersection
rIntersection.maStart = aIntersect1;
if( ( maStart != aIntersect1 ) && bStartInside )
rIntersection.maEnd = maStart;
else if( ( maEnd != aIntersect1 ) && bEndInside )
rIntersection.maEnd = maEnd;
else
rIntersection.maEnd = rIntersection.maStart;
}
else
bRet = FALSE;
}
return bRet;
}
// ------------------------------------------------------------------------
Point Line::NearestPoint( const Point& rPoint ) const
{
Point aRetPt;
if ( maStart != maEnd )
{
const double fDistX = maEnd.X() - maStart.X();
const double fDistY = maStart.Y() - maEnd.Y();
const double fTau = ( ( maStart.Y() - rPoint.Y() ) * fDistY -
( maStart.X() - rPoint.X() ) * fDistX ) /
( fDistX * fDistX + fDistY * fDistY );
if( fTau < 0.0 )
aRetPt = maStart;
else if( fTau <= 1.0 )
{
aRetPt.X() = FRound( maStart.X() + fTau * fDistX );
aRetPt.Y() = FRound( maStart.Y() - fTau * fDistY );
}
else
aRetPt = maEnd;
}
else
aRetPt = maStart;
return aRetPt;
}
// ------------------------------------------------------------------------
double Line::GetDistance( const double& rPtX, const double& rPtY ) const
{
double fDist;
if( maStart != maEnd )
{
const double fDistX = maEnd.X() - maStart.X();
const double fDistY = maEnd.Y() - maStart.Y();
const double fACX = maStart.X() - rPtX;
const double fACY = maStart.Y() - rPtY;
const double fL2 = fDistX * fDistX + fDistY * fDistY;
const double fR = ( fACY * -fDistY - fACX * fDistX ) / fL2;
const double fS = ( fACY * fDistX - fACX * fDistY ) / fL2;
if( fR < 0.0 )
{
fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY );
if( fS < 0.0 )
fDist *= -1.0;
}
else if( fR <= 1.0 )
fDist = fS * sqrt( fL2 );
else
{
fDist = hypot( maEnd.X() - rPtX, maEnd.Y() - rPtY );
if( fS < 0.0 )
fDist *= -1.0;
}
}
else
fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY );
return fDist;
}
// ------------------------------------------------------------------------
void Line::Enum( const Link& rEnumLink )
{
DBG_ASSERT( rEnumLink.IsSet(), "This call doesn't make any sense with !rEnumLink.IsSet()" );
Point aEnum;
long nX;
long nY;
if( maStart.X() == maEnd.X() )
{
const long nEndY = maEnd.Y();
nX = maStart.X();
nY = maStart.Y();
if( nEndY > nY )
{
while( nY <= nEndY )
{
aEnum.X() = nX;
aEnum.Y() = nY++;
rEnumLink.Call( &aEnum );
}
}
else
{
while( nY >= nEndY )
{
aEnum.X() = nX;
aEnum.Y() = nY--;
rEnumLink.Call( &aEnum );
}
}
}
else if( maStart.Y() == maEnd.Y() )
{
const long nEndX = maEnd.X();
nX = maStart.X();
nY = maStart.Y();
if( nEndX > nX )
{
while( nX <= nEndX )
{
aEnum.X() = nX++;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
}
}
else
{
while( nX >= nEndX )
{
aEnum.X() = nX--;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
}
}
}
else
{
const long nDX = labs( maEnd.X() - maStart.X() );
const long nDY = labs( maEnd.Y() - maStart.Y() );
const long nStartX = maStart.X();
const long nStartY = maStart.Y();
const long nEndX = maEnd.X();
const long nEndY = maEnd.Y();
const long nXInc = ( nStartX < nEndX ) ? 1L : -1L;
const long nYInc = ( nStartY < nEndY ) ? 1L : -1L;
if( nDX >= nDY )
{
const long nDYX = ( nDY - nDX ) << 1;
const long nDY2 = nDY << 1;
long nD = nDY2 - nDX;
for( nX = nStartX, nY = nStartY; nX != nEndX; nX += nXInc )
{
aEnum.X() = nX;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
if( nD < 0L )
nD += nDY2;
else
nD += nDYX, nY += nYInc;
}
}
else
{
const long nDYX = ( nDX - nDY ) << 1;
const long nDY2 = nDX << 1;
long nD = nDY2 - nDY;
for( nX = nStartX, nY = nStartY; nY != nEndY; nY += nYInc )
{
aEnum.X() = nX;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
if( nD < 0L )
nD += nDY2;
else
nD += nDYX, nX += nXInc;
}
}
// last point
aEnum.X() = nEndX;
aEnum.Y() = nEndY;
rEnumLink.Call( &aEnum );
}
}
<commit_msg>INTEGRATION: CWS hr51 (1.6.16); FILE MERGED 2008/06/06 14:13:38 hr 1.6.16.1: #i88947#: includes; namespaces<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: line.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#define _LINE_CXX
#include <tools/link.hxx>
#include <tools/line.hxx>
#include <tools/debug.hxx>
#include <cstdlib>
#include <cmath> // std::sqrt
#include <math.h> // hypot, doens't seem to live in std namespace everywhere
inline long FRound( double fVal )
{
return( fVal > 0.0 ? (long) ( fVal + 0.5 ) : -(long) ( -fVal + 0.5 ) );
}
// --------
// - Line -
// --------
double Line::GetLength() const
{
return hypot( maStart.X() - maEnd.X(), maStart.Y() - maEnd.Y() );
}
// ------------------------------------------------------------------------
BOOL Line::Intersection( const Line& rLine, Point& rIntersection ) const
{
double fX, fY;
BOOL bRet;
if( Intersection( rLine, fX, fY ) )
{
rIntersection.X() = FRound( fX );
rIntersection.Y() = FRound( fY );
bRet = TRUE;
}
else
bRet = FALSE;
return bRet;
}
// ------------------------------------------------------------------------
BOOL Line::Intersection( const Line& rLine, double& rIntersectionX, double& rIntersectionY ) const
{
const double fAx = maEnd.X() - maStart.X();
const double fAy = maEnd.Y() - maStart.Y();
const double fBx = rLine.maStart.X() - rLine.maEnd.X();
const double fBy = rLine.maStart.Y() - rLine.maEnd.Y();
const double fDen = fAy * fBx - fAx * fBy;
BOOL bOk = FALSE;
if( fDen != 0. )
{
const double fCx = maStart.X() - rLine.maStart.X();
const double fCy = maStart.Y() - rLine.maStart.Y();
const double fA = fBy * fCx - fBx * fCy;
const BOOL bGreater = ( fDen > 0. );
bOk = TRUE;
if ( bGreater )
{
if ( ( fA < 0. ) || ( fA > fDen ) )
bOk = FALSE;
}
else if ( ( fA > 0. ) || ( fA < fDen ) )
bOk = FALSE;
if ( bOk )
{
const double fB = fAx * fCy - fAy * fCx;
if ( bGreater )
{
if ( ( fB < 0. ) || ( fB > fDen ) )
bOk = FALSE;
}
else if ( ( fB > 0. ) || ( fB < fDen ) )
bOk = FALSE;
if( bOk )
{
const double fAlpha = fA / fDen;
rIntersectionX = ( maStart.X() + fAlpha * fAx );
rIntersectionY = ( maStart.Y() + fAlpha * fAy );
}
}
}
return bOk;
}
// ------------------------------------------------------------------------
BOOL Line::Intersection( const Rectangle& rRect, Line& rIntersection ) const
{
const BOOL bStartInside = rRect.IsInside( maStart );
const BOOL bEndInside = rRect.IsInside( maEnd );
BOOL bRet = TRUE;
if( bStartInside && bEndInside )
{
// line completely inside rect
rIntersection.maStart = maStart;
rIntersection.maEnd = maEnd;
}
else
{
// calculate intersections
const Point aTL( rRect.TopLeft() ), aTR( rRect.TopRight() );
const Point aBR( rRect.BottomRight() ), aBL( rRect.BottomLeft() );
Point aIntersect1, aIntersect2;
Point* pCurIntersection = &aIntersect1;
if( Intersection( Line( aTL, aTR ), *pCurIntersection ) )
pCurIntersection = &aIntersect2;
if( Intersection( Line( aTR, aBR ), *pCurIntersection ) )
pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL;
if( pCurIntersection && Intersection( Line( aBR, aBL ), *pCurIntersection ) )
pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL;
if( pCurIntersection && Intersection( Line( aBL, aTL ), *pCurIntersection ) )
pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL;
if( !pCurIntersection )
{
// two intersections
rIntersection.maStart = aIntersect1;
rIntersection.maEnd = aIntersect2;
}
else if( pCurIntersection == &aIntersect2 )
{
// one intersection
rIntersection.maStart = aIntersect1;
if( ( maStart != aIntersect1 ) && bStartInside )
rIntersection.maEnd = maStart;
else if( ( maEnd != aIntersect1 ) && bEndInside )
rIntersection.maEnd = maEnd;
else
rIntersection.maEnd = rIntersection.maStart;
}
else
bRet = FALSE;
}
return bRet;
}
// ------------------------------------------------------------------------
Point Line::NearestPoint( const Point& rPoint ) const
{
Point aRetPt;
if ( maStart != maEnd )
{
const double fDistX = maEnd.X() - maStart.X();
const double fDistY = maStart.Y() - maEnd.Y();
const double fTau = ( ( maStart.Y() - rPoint.Y() ) * fDistY -
( maStart.X() - rPoint.X() ) * fDistX ) /
( fDistX * fDistX + fDistY * fDistY );
if( fTau < 0.0 )
aRetPt = maStart;
else if( fTau <= 1.0 )
{
aRetPt.X() = FRound( maStart.X() + fTau * fDistX );
aRetPt.Y() = FRound( maStart.Y() - fTau * fDistY );
}
else
aRetPt = maEnd;
}
else
aRetPt = maStart;
return aRetPt;
}
// ------------------------------------------------------------------------
double Line::GetDistance( const double& rPtX, const double& rPtY ) const
{
double fDist;
if( maStart != maEnd )
{
const double fDistX = maEnd.X() - maStart.X();
const double fDistY = maEnd.Y() - maStart.Y();
const double fACX = maStart.X() - rPtX;
const double fACY = maStart.Y() - rPtY;
const double fL2 = fDistX * fDistX + fDistY * fDistY;
const double fR = ( fACY * -fDistY - fACX * fDistX ) / fL2;
const double fS = ( fACY * fDistX - fACX * fDistY ) / fL2;
if( fR < 0.0 )
{
fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY );
if( fS < 0.0 )
fDist *= -1.0;
}
else if( fR <= 1.0 )
fDist = fS * std::sqrt( fL2 );
else
{
fDist = hypot( maEnd.X() - rPtX, maEnd.Y() - rPtY );
if( fS < 0.0 )
fDist *= -1.0;
}
}
else
fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY );
return fDist;
}
// ------------------------------------------------------------------------
void Line::Enum( const Link& rEnumLink )
{
DBG_ASSERT( rEnumLink.IsSet(), "This call doesn't make any sense with !rEnumLink.IsSet()" );
Point aEnum;
long nX;
long nY;
if( maStart.X() == maEnd.X() )
{
const long nEndY = maEnd.Y();
nX = maStart.X();
nY = maStart.Y();
if( nEndY > nY )
{
while( nY <= nEndY )
{
aEnum.X() = nX;
aEnum.Y() = nY++;
rEnumLink.Call( &aEnum );
}
}
else
{
while( nY >= nEndY )
{
aEnum.X() = nX;
aEnum.Y() = nY--;
rEnumLink.Call( &aEnum );
}
}
}
else if( maStart.Y() == maEnd.Y() )
{
const long nEndX = maEnd.X();
nX = maStart.X();
nY = maStart.Y();
if( nEndX > nX )
{
while( nX <= nEndX )
{
aEnum.X() = nX++;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
}
}
else
{
while( nX >= nEndX )
{
aEnum.X() = nX--;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
}
}
}
else
{
const long nDX = labs( maEnd.X() - maStart.X() );
const long nDY = labs( maEnd.Y() - maStart.Y() );
const long nStartX = maStart.X();
const long nStartY = maStart.Y();
const long nEndX = maEnd.X();
const long nEndY = maEnd.Y();
const long nXInc = ( nStartX < nEndX ) ? 1L : -1L;
const long nYInc = ( nStartY < nEndY ) ? 1L : -1L;
if( nDX >= nDY )
{
const long nDYX = ( nDY - nDX ) << 1;
const long nDY2 = nDY << 1;
long nD = nDY2 - nDX;
for( nX = nStartX, nY = nStartY; nX != nEndX; nX += nXInc )
{
aEnum.X() = nX;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
if( nD < 0L )
nD += nDY2;
else
nD += nDYX, nY += nYInc;
}
}
else
{
const long nDYX = ( nDX - nDY ) << 1;
const long nDY2 = nDX << 1;
long nD = nDY2 - nDY;
for( nX = nStartX, nY = nStartY; nY != nEndY; nY += nYInc )
{
aEnum.X() = nX;
aEnum.Y() = nY;
rEnumLink.Call( &aEnum );
if( nD < 0L )
nD += nDY2;
else
nD += nDYX, nX += nXInc;
}
}
// last point
aEnum.X() = nEndX;
aEnum.Y() = nEndY;
rEnumLink.Call( &aEnum );
}
}
<|endoftext|> |
<commit_before>//===--- OwnedToGuaranteedTransform.cpp -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "fso-owned-to-guaranteed-transform"
#include "FunctionSignatureOpts.h"
#include "swift/SIL/DebugUtils.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
static llvm::cl::opt<bool> FSODisableOwnedToGuaranteed(
"sil-fso-disable-owned-to-guaranteed",
llvm::cl::desc("Do not perform owned to guaranteed during FSO. Intended "
"only for testing purposes."));
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// Return the single return value of the function.
static SILValue findReturnValue(SILFunction *F) {
auto RBB = F->findReturnBB();
if (RBB == F->end())
return SILValue();
auto Term = dyn_cast<ReturnInst>(RBB->getTerminator());
return Term->getOperand();
}
/// Return the single apply found in this function.
static SILInstruction *findOnlyApply(SILFunction *F) {
SILInstruction *OnlyApply = nullptr;
for (auto &B : *F) {
for (auto &X : B) {
if (!isa<ApplyInst>(X) && !isa<TryApplyInst>(X))
continue;
assert(!OnlyApply && "There are more than 1 function calls");
OnlyApply = &X;
}
}
assert(OnlyApply && "There is no function calls");
return OnlyApply;
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
bool FunctionSignatureTransform::OwnedToGuaranteedAnalyzeParameters() {
SILFunction *F = TransformDescriptor.OriginalFunction;
auto Args = F->begin()->getSILFunctionArguments();
// A map from consumed SILArguments to the release associated with an
// argument.
//
// TODO: The return block and throw block should really be abstracted away.
SILArgumentConvention ArgumentConventions[] = {
SILArgumentConvention::Direct_Owned, SILArgumentConvention::Indirect_In};
ConsumedArgToEpilogueReleaseMatcher ArgToReturnReleaseMap(
RCIA->get(F), F, ArgumentConventions);
ConsumedArgToEpilogueReleaseMatcher ArgToThrowReleaseMap(
RCIA->get(F), F, ArgumentConventions,
ConsumedArgToEpilogueReleaseMatcher::ExitKind::Throw);
// Did we decide we should optimize any parameter?
bool SignatureOptimize = false;
// Analyze the argument information.
for (unsigned i : indices(Args)) {
ArgumentDescriptor &A = TransformDescriptor.ArgumentDescList[i];
if (!A.canOptimizeLiveArg()) {
continue;
}
// See if we can find a ref count equivalent strong_release or release_value
// at the end of this function if our argument is an @owned parameter.
// See if we can find a destroy_addr at the end of this function if our
// argument is an @in parameter.
if (A.hasConvention(SILArgumentConvention::Direct_Owned) ||
A.hasConvention(SILArgumentConvention::Indirect_In)) {
auto Releases = ArgToReturnReleaseMap.getReleasesForArgument(A.Arg);
if (!Releases.empty()) {
// If the function has a throw block we must also find a matching
// release in the throw block.
auto ReleasesInThrow =
ArgToThrowReleaseMap.getReleasesForArgument(A.Arg);
if (!ArgToThrowReleaseMap.hasBlock() || !ReleasesInThrow.empty()) {
assert(A.CalleeRelease.empty());
assert(A.CalleeReleaseInThrowBlock.empty());
llvm::copy(Releases, std::back_inserter(A.CalleeRelease));
llvm::copy(ReleasesInThrow,
std::back_inserter(A.CalleeReleaseInThrowBlock));
// We can convert this parameter to a @guaranteed.
A.OwnedToGuaranteed = true;
SignatureOptimize = true;
}
}
}
// Modified self argument.
if (A.OwnedToGuaranteed && Args[i]->isSelf()) {
TransformDescriptor.shouldModifySelfArgument = true;
}
}
return SignatureOptimize;
}
bool FunctionSignatureTransform::OwnedToGuaranteedAnalyzeResults() {
SILFunction *F = TransformDescriptor.OriginalFunction;
auto ResultDescList = TransformDescriptor.ResultDescList;
auto fnConv = F->getConventions();
// For now, only do anything if there's a single direct result.
if (fnConv.getNumDirectSILResults() != 1)
return false;
if (!fnConv.getIndirectSILResults().empty())
return false;
bool SignatureOptimize = false;
if (ResultDescList[0].hasConvention(ResultConvention::Owned)) {
auto RV = findReturnValue(F);
if (!RV)
return false;
auto &RI = ResultDescList[0];
// We have an @owned return value, find the epilogue retains now.
auto Retains = EA->get(F)->computeEpilogueARCInstructions(
EpilogueARCContext::EpilogueARCKind::Retain, RV);
// We do not need to worry about the throw block, as the return value is
// only going to be used in the return block/normal block of the try_apply
// instruction.
if (!Retains.empty()) {
RI.CalleeRetain = Retains;
SignatureOptimize = true;
RI.OwnedToGuaranteed = true;
}
}
return SignatureOptimize;
}
void
FunctionSignatureTransform::OwnedToGuaranteedTransformFunctionParameters() {
// And remove all Callee releases that we found and made redundant via owned
// to guaranteed conversion.
for (const ArgumentDescriptor &AD : TransformDescriptor.ArgumentDescList) {
if (!AD.OwnedToGuaranteed)
continue;
for (auto &X : AD.CalleeRelease) {
X->eraseFromParent();
}
for (auto &X : AD.CalleeReleaseInThrowBlock) {
X->eraseFromParent();
}
// Now we need to replace the FunctionArgument so that we have the correct
// ValueOwnershipKind.
AD.Arg->setOwnershipKind(ValueOwnershipKind::Guaranteed);
}
}
void FunctionSignatureTransform::OwnedToGuaranteedTransformFunctionResults() {
// And remove all callee retains that we found and made redundant via owned
// to unowned conversion.
for (const ResultDescriptor &RD : TransformDescriptor.ResultDescList) {
if (!RD.OwnedToGuaranteed)
continue;
for (auto &X : RD.CalleeRetain) {
if (isa<StrongRetainInst>(X) || isa<RetainValueInst>(X)) {
X->eraseFromParent();
continue;
}
// Create a release to balance it out.
auto AI = cast<ApplyInst>(X);
createDecrementBefore(AI, AI->getParent()->getTerminator());
}
}
}
void FunctionSignatureTransform::OwnedToGuaranteedFinalizeThunkFunction(
SILBuilder &Builder, SILFunction *F) {
// Finish the epilogue work for the argument as well as result.
for (auto &ArgDesc : TransformDescriptor.ArgumentDescList) {
OwnedToGuaranteedAddArgumentRelease(ArgDesc, Builder, F);
}
for (auto &ResDesc : TransformDescriptor.ResultDescList) {
OwnedToGuaranteedAddResultRelease(ResDesc, Builder, F);
}
}
static void createArgumentRelease(SILBuilder &Builder, ArgumentDescriptor &AD) {
auto &F = Builder.getFunction();
SILArgument *Arg = F.getArguments()[AD.Index];
if (Arg->getType().isAddress()) {
assert(AD.PInfo->getConvention() == ParameterConvention::Indirect_In &&
F.getConventions().useLoweredAddresses());
Builder.createDestroyAddr(RegularLocation::getAutoGeneratedLocation(),
F.getArguments()[AD.Index]);
return;
}
Builder.createReleaseValue(RegularLocation::getAutoGeneratedLocation(),
F.getArguments()[AD.Index],
Builder.getDefaultAtomicity());
}
/// Set up epilogue work for the thunk arguments based in the given argument.
/// Default implementation simply passes it through.
void FunctionSignatureTransform::OwnedToGuaranteedAddArgumentRelease(
ArgumentDescriptor &AD, SILBuilder &Builder, SILFunction *F) {
// If we have any arguments that were consumed but are now guaranteed,
// insert a releasing RC instruction.
if (!AD.OwnedToGuaranteed) {
return;
}
SILInstruction *Call = findOnlyApply(F);
if (isa<ApplyInst>(Call)) {
Builder.setInsertionPoint(&*std::next(SILBasicBlock::iterator(Call)));
createArgumentRelease(Builder, AD);
} else {
SILBasicBlock *NormalBB = dyn_cast<TryApplyInst>(Call)->getNormalBB();
Builder.setInsertionPoint(&*NormalBB->begin());
createArgumentRelease(Builder, AD);
SILBasicBlock *ErrorBB = dyn_cast<TryApplyInst>(Call)->getErrorBB();
Builder.setInsertionPoint(&*ErrorBB->begin());
createArgumentRelease(Builder, AD);
}
}
void FunctionSignatureTransform::OwnedToGuaranteedAddResultRelease(
ResultDescriptor &RD, SILBuilder &Builder, SILFunction *F) {
// If we have any result that were consumed but are now guaranteed,
// insert a releasing RC instruction.
if (!RD.OwnedToGuaranteed) {
return;
}
SILInstruction *Call = findOnlyApply(F);
if (auto AI = dyn_cast<ApplyInst>(Call)) {
Builder.setInsertionPoint(&*std::next(SILBasicBlock::iterator(AI)));
Builder.createRetainValue(RegularLocation::getAutoGeneratedLocation(), AI,
Builder.getDefaultAtomicity());
} else {
SILBasicBlock *NormalBB = cast<TryApplyInst>(Call)->getNormalBB();
Builder.setInsertionPoint(&*NormalBB->begin());
Builder.createRetainValue(RegularLocation::getAutoGeneratedLocation(),
NormalBB->getArgument(0),
Builder.getDefaultAtomicity());
}
}
bool FunctionSignatureTransform::OwnedToGuaranteedAnalyze() {
if (FSODisableOwnedToGuaranteed)
return false;
bool Result = OwnedToGuaranteedAnalyzeResults();
bool Params = OwnedToGuaranteedAnalyzeParameters();
return Params || Result;
}
void FunctionSignatureTransform::OwnedToGuaranteedTransform() {
OwnedToGuaranteedTransformFunctionResults();
OwnedToGuaranteedTransformFunctionParameters();
}
<commit_msg>Make booleans const<commit_after>//===--- OwnedToGuaranteedTransform.cpp -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "fso-owned-to-guaranteed-transform"
#include "FunctionSignatureOpts.h"
#include "swift/SIL/DebugUtils.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
static llvm::cl::opt<bool> FSODisableOwnedToGuaranteed(
"sil-fso-disable-owned-to-guaranteed",
llvm::cl::desc("Do not perform owned to guaranteed during FSO. Intended "
"only for testing purposes."));
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// Return the single return value of the function.
static SILValue findReturnValue(SILFunction *F) {
auto RBB = F->findReturnBB();
if (RBB == F->end())
return SILValue();
auto Term = dyn_cast<ReturnInst>(RBB->getTerminator());
return Term->getOperand();
}
/// Return the single apply found in this function.
static SILInstruction *findOnlyApply(SILFunction *F) {
SILInstruction *OnlyApply = nullptr;
for (auto &B : *F) {
for (auto &X : B) {
if (!isa<ApplyInst>(X) && !isa<TryApplyInst>(X))
continue;
assert(!OnlyApply && "There are more than 1 function calls");
OnlyApply = &X;
}
}
assert(OnlyApply && "There is no function calls");
return OnlyApply;
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
bool FunctionSignatureTransform::OwnedToGuaranteedAnalyzeParameters() {
SILFunction *F = TransformDescriptor.OriginalFunction;
auto Args = F->begin()->getSILFunctionArguments();
// A map from consumed SILArguments to the release associated with an
// argument.
//
// TODO: The return block and throw block should really be abstracted away.
SILArgumentConvention ArgumentConventions[] = {
SILArgumentConvention::Direct_Owned, SILArgumentConvention::Indirect_In};
ConsumedArgToEpilogueReleaseMatcher ArgToReturnReleaseMap(
RCIA->get(F), F, ArgumentConventions);
ConsumedArgToEpilogueReleaseMatcher ArgToThrowReleaseMap(
RCIA->get(F), F, ArgumentConventions,
ConsumedArgToEpilogueReleaseMatcher::ExitKind::Throw);
// Did we decide we should optimize any parameter?
bool SignatureOptimize = false;
// Analyze the argument information.
for (unsigned i : indices(Args)) {
ArgumentDescriptor &A = TransformDescriptor.ArgumentDescList[i];
if (!A.canOptimizeLiveArg()) {
continue;
}
// See if we can find a ref count equivalent strong_release or release_value
// at the end of this function if our argument is an @owned parameter.
// See if we can find a destroy_addr at the end of this function if our
// argument is an @in parameter.
if (A.hasConvention(SILArgumentConvention::Direct_Owned) ||
A.hasConvention(SILArgumentConvention::Indirect_In)) {
auto Releases = ArgToReturnReleaseMap.getReleasesForArgument(A.Arg);
if (!Releases.empty()) {
// If the function has a throw block we must also find a matching
// release in the throw block.
auto ReleasesInThrow =
ArgToThrowReleaseMap.getReleasesForArgument(A.Arg);
if (!ArgToThrowReleaseMap.hasBlock() || !ReleasesInThrow.empty()) {
assert(A.CalleeRelease.empty());
assert(A.CalleeReleaseInThrowBlock.empty());
llvm::copy(Releases, std::back_inserter(A.CalleeRelease));
llvm::copy(ReleasesInThrow,
std::back_inserter(A.CalleeReleaseInThrowBlock));
// We can convert this parameter to a @guaranteed.
A.OwnedToGuaranteed = true;
SignatureOptimize = true;
}
}
}
// Modified self argument.
if (A.OwnedToGuaranteed && Args[i]->isSelf()) {
TransformDescriptor.shouldModifySelfArgument = true;
}
}
return SignatureOptimize;
}
bool FunctionSignatureTransform::OwnedToGuaranteedAnalyzeResults() {
SILFunction *F = TransformDescriptor.OriginalFunction;
auto ResultDescList = TransformDescriptor.ResultDescList;
auto fnConv = F->getConventions();
// For now, only do anything if there's a single direct result.
if (fnConv.getNumDirectSILResults() != 1)
return false;
if (!fnConv.getIndirectSILResults().empty())
return false;
bool SignatureOptimize = false;
if (ResultDescList[0].hasConvention(ResultConvention::Owned)) {
auto RV = findReturnValue(F);
if (!RV)
return false;
auto &RI = ResultDescList[0];
// We have an @owned return value, find the epilogue retains now.
auto Retains = EA->get(F)->computeEpilogueARCInstructions(
EpilogueARCContext::EpilogueARCKind::Retain, RV);
// We do not need to worry about the throw block, as the return value is
// only going to be used in the return block/normal block of the try_apply
// instruction.
if (!Retains.empty()) {
RI.CalleeRetain = Retains;
SignatureOptimize = true;
RI.OwnedToGuaranteed = true;
}
}
return SignatureOptimize;
}
void
FunctionSignatureTransform::OwnedToGuaranteedTransformFunctionParameters() {
// And remove all Callee releases that we found and made redundant via owned
// to guaranteed conversion.
for (const ArgumentDescriptor &AD : TransformDescriptor.ArgumentDescList) {
if (!AD.OwnedToGuaranteed)
continue;
for (auto &X : AD.CalleeRelease) {
X->eraseFromParent();
}
for (auto &X : AD.CalleeReleaseInThrowBlock) {
X->eraseFromParent();
}
// Now we need to replace the FunctionArgument so that we have the correct
// ValueOwnershipKind.
AD.Arg->setOwnershipKind(ValueOwnershipKind::Guaranteed);
}
}
void FunctionSignatureTransform::OwnedToGuaranteedTransformFunctionResults() {
// And remove all callee retains that we found and made redundant via owned
// to unowned conversion.
for (const ResultDescriptor &RD : TransformDescriptor.ResultDescList) {
if (!RD.OwnedToGuaranteed)
continue;
for (auto &X : RD.CalleeRetain) {
if (isa<StrongRetainInst>(X) || isa<RetainValueInst>(X)) {
X->eraseFromParent();
continue;
}
// Create a release to balance it out.
auto AI = cast<ApplyInst>(X);
createDecrementBefore(AI, AI->getParent()->getTerminator());
}
}
}
void FunctionSignatureTransform::OwnedToGuaranteedFinalizeThunkFunction(
SILBuilder &Builder, SILFunction *F) {
// Finish the epilogue work for the argument as well as result.
for (auto &ArgDesc : TransformDescriptor.ArgumentDescList) {
OwnedToGuaranteedAddArgumentRelease(ArgDesc, Builder, F);
}
for (auto &ResDesc : TransformDescriptor.ResultDescList) {
OwnedToGuaranteedAddResultRelease(ResDesc, Builder, F);
}
}
static void createArgumentRelease(SILBuilder &Builder, ArgumentDescriptor &AD) {
auto &F = Builder.getFunction();
SILArgument *Arg = F.getArguments()[AD.Index];
if (Arg->getType().isAddress()) {
assert(AD.PInfo->getConvention() == ParameterConvention::Indirect_In &&
F.getConventions().useLoweredAddresses());
Builder.createDestroyAddr(RegularLocation::getAutoGeneratedLocation(),
F.getArguments()[AD.Index]);
return;
}
Builder.createReleaseValue(RegularLocation::getAutoGeneratedLocation(),
F.getArguments()[AD.Index],
Builder.getDefaultAtomicity());
}
/// Set up epilogue work for the thunk arguments based in the given argument.
/// Default implementation simply passes it through.
void FunctionSignatureTransform::OwnedToGuaranteedAddArgumentRelease(
ArgumentDescriptor &AD, SILBuilder &Builder, SILFunction *F) {
// If we have any arguments that were consumed but are now guaranteed,
// insert a releasing RC instruction.
if (!AD.OwnedToGuaranteed) {
return;
}
SILInstruction *Call = findOnlyApply(F);
if (isa<ApplyInst>(Call)) {
Builder.setInsertionPoint(&*std::next(SILBasicBlock::iterator(Call)));
createArgumentRelease(Builder, AD);
} else {
SILBasicBlock *NormalBB = dyn_cast<TryApplyInst>(Call)->getNormalBB();
Builder.setInsertionPoint(&*NormalBB->begin());
createArgumentRelease(Builder, AD);
SILBasicBlock *ErrorBB = dyn_cast<TryApplyInst>(Call)->getErrorBB();
Builder.setInsertionPoint(&*ErrorBB->begin());
createArgumentRelease(Builder, AD);
}
}
void FunctionSignatureTransform::OwnedToGuaranteedAddResultRelease(
ResultDescriptor &RD, SILBuilder &Builder, SILFunction *F) {
// If we have any result that were consumed but are now guaranteed,
// insert a releasing RC instruction.
if (!RD.OwnedToGuaranteed) {
return;
}
SILInstruction *Call = findOnlyApply(F);
if (auto AI = dyn_cast<ApplyInst>(Call)) {
Builder.setInsertionPoint(&*std::next(SILBasicBlock::iterator(AI)));
Builder.createRetainValue(RegularLocation::getAutoGeneratedLocation(), AI,
Builder.getDefaultAtomicity());
} else {
SILBasicBlock *NormalBB = cast<TryApplyInst>(Call)->getNormalBB();
Builder.setInsertionPoint(&*NormalBB->begin());
Builder.createRetainValue(RegularLocation::getAutoGeneratedLocation(),
NormalBB->getArgument(0),
Builder.getDefaultAtomicity());
}
}
bool FunctionSignatureTransform::OwnedToGuaranteedAnalyze() {
if (FSODisableOwnedToGuaranteed)
return false;
const bool Result = OwnedToGuaranteedAnalyzeResults();
const bool Params = OwnedToGuaranteedAnalyzeParameters();
return Params || Result;
}
void FunctionSignatureTransform::OwnedToGuaranteedTransform() {
OwnedToGuaranteedTransformFunctionResults();
OwnedToGuaranteedTransformFunctionParameters();
}
<|endoftext|> |
<commit_before>/*
* IF (RSA/RW) Operation
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/if_op.h>
#include <botan/numthry.h>
namespace Botan {
/*
* Default_IF_Op Constructor
*/
Default_IF_Op::Default_IF_Op(const BigInt& e, const BigInt& n, const BigInt&,
const BigInt& p, const BigInt& q,
const BigInt& d1, const BigInt& d2,
const BigInt& c)
{
powermod_e_n = Fixed_Exponent_Power_Mod(e, n);
if(d1 != 0 && d2 != 0 && p != 0 && q != 0)
{
powermod_d1_p = Fixed_Exponent_Power_Mod(d1, p);
powermod_d2_q = Fixed_Exponent_Power_Mod(d2, q);
reducer = Modular_Reducer(p);
this->c = c;
this->q = q;
}
}
/*
* Default IF Private Operation
*/
BigInt Default_IF_Op::private_op(const BigInt& i) const
{
if(q == 0)
throw Internal_Error("Default_IF_Op::private_op: No private key");
BigInt j1 = powermod_d1_p(i);
BigInt j2 = powermod_d2_q(i);
j1 = reducer.reduce(sub_mul(j1, j2, c));
return mul_add(j1, q, j2);
}
}
<commit_msg>In IF decryption, two large powmods are done, one mod p and one mod q. Spawn one of them off in a new thread and compute the other on the current thread. Performance on my Core2 shows a 60 to 90% improvement in overall speed in RSA private key operations. Will probably be even better once std::async is available (not currently in GCC) since it will probably use a thread pool which will amortize the thread creation/shutdown cost.<commit_after>/*
* IF (RSA/RW) Operation
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/if_op.h>
#include <botan/numthry.h>
#include <future>
#include <thread>
namespace Botan {
/*
* Default_IF_Op Constructor
*/
Default_IF_Op::Default_IF_Op(const BigInt& e, const BigInt& n, const BigInt&,
const BigInt& p, const BigInt& q,
const BigInt& d1, const BigInt& d2,
const BigInt& c)
{
powermod_e_n = Fixed_Exponent_Power_Mod(e, n);
if(d1 != 0 && d2 != 0 && p != 0 && q != 0)
{
powermod_d1_p = Fixed_Exponent_Power_Mod(d1, p);
powermod_d2_q = Fixed_Exponent_Power_Mod(d2, q);
reducer = Modular_Reducer(p);
this->c = c;
this->q = q;
}
}
/*
* Default IF Private Operation
*/
BigInt Default_IF_Op::private_op(const BigInt& i) const
{
if(q == 0)
throw Internal_Error("Default_IF_Op::private_op: No private key");
/*
* A simple std::bind(powermod_d1_p, i) would work instead of a
* lambda but GCC 4.5's std::result_of doesn't use decltype and gets
* confused
*
* Todo: use std::async() once it is in GCC
* auto future_j1 = std::async(std::bind(powermod_d1_p, i));
* BigInt j2 = powermod_d2_q(i);
* BigInt j1 = future.get();
*/
std::packaged_task<BigInt ()> task_j1([&]() { return powermod_d1_p(i); });
auto future_j1 = task_j1.get_future();
std::thread thr_j1(std::move(task_j1));
BigInt j2 = powermod_d2_q(i);
BigInt j1 = future_j1.get();
thr_j1.join();
j1 = reducer.reduce(sub_mul(j1, j2, c));
return mul_add(j1, q, j2);
}
}
<|endoftext|> |
<commit_before>#include "batterywidget.h"
#include "batterytranslation.h"
#include "dcpbattery.h"
#include "dcpspaceritem.h"
#include "batterygconf.h"
#include <DuiButton>
#include <DuiLayout>
#include <DuiGridLayoutPolicy>
#include <DuiLinearLayoutPolicy>
#include <DuiLabel>
#include <DuiSlider>
BatteryWidget::BatteryWidget(QGraphicsWidget *parent)
:DcpWidget(parent)
{
setReferer(DcpBattery::None);
initWidget();
}
BatteryWidget::~BatteryWidget()
{
delete batteryGConf;
batteryGConf = NULL;
}
void BatteryWidget::initWidget()
{
//create gconf if
initBatteryGConf();
//testing purposes
batteryGConf->setRemainingTalkTime(140);
batteryGConf->setRemainingStandByTime(340);
batteryGConf->setPSMThreshold(20);
QList<int> values;
values << 10 << 20 << 30 << 60 << 90 << 120 << 150 << 180 << 210;
batteryGConf->setPSMThresholdValues(values);
batteryGConf->setPSMToggle(true);
//create talkTimeLayout
DuiLayout *talkTimeLayout = new DuiLayout(0);
DuiGridLayoutPolicy *talkTimeLayoutPolicy = new DuiGridLayoutPolicy(talkTimeLayout);
//TODO add the charging icon to position 0, 0, 1, 2
talkTimeLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::TalkTimeText), 0, 1);
talkTimeLabel = new DuiLabel(timeInString(batteryGConf->remainingTalkTime(), DcpBattery::TalkTimeValueText));
talkTimeLayoutPolicy->addItemAtPosition(talkTimeLabel, 1, 1);
//create standByTimeLayout
DuiLayout *standByTimeLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *standByTimeLayoutPolicy = new DuiLinearLayoutPolicy(standByTimeLayout, Qt::Vertical);
standByTimeLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::StandByTimeText), 0);
standByTimeLabel = new DuiLabel(timeInString(batteryGConf->remainingStandByTime(), DcpBattery::StandByTimeValueText));
standByTimeLayoutPolicy->addItemAtPosition(standByTimeLabel, 1);
//create PSMLayout
DuiLayout *PSMLayout = new DuiLayout(0);
DuiGridLayoutPolicy *PSMLayoutPolicy = new DuiGridLayoutPolicy(PSMLayout);
PSMLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::PSMText), 0, 0);
PSMLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::NBCText), 1, 0);
PSMButton = new DuiButton();
PSMButton->setCheckable(true);
updateButton(PSMButton, batteryGConf->PSMToggle());
PSMLayoutPolicy->addItemAtPosition(PSMButton, 0, 1, 2, 1);
//create upperLayout and put talkTimeLayot, standByTimeLayout and PSMLayout into it
DuiLayout *upperLayout = new DuiLayout(0);
DuiGridLayoutPolicy *upperLayoutPolicy = new DuiGridLayoutPolicy(upperLayout);
upperLayoutPolicy->addItemAtPosition(talkTimeLayout, 0, 0);
upperLayoutPolicy->addItemAtPosition(standByTimeLayout, 0, 1);
upperLayoutPolicy->addItemAtPosition(PSMLayout, 1, 0);
//create disablePSMLayout
DuiLayout *disablePSMLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *disablePSMLayoutPolicy = new DuiLinearLayoutPolicy(disablePSMLayout, Qt::Horizontal);
disablePSMButton = new DuiButton();
disablePSMButton->setCheckable(true);
updateButton(disablePSMButton, batteryGConf->PSMDisabled());
disablePSMLayoutPolicy->addItemAtPosition(disablePSMButton, 0);
disablePSMLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::DisablePSMText), 1);
//create lowerLayout and put disablePSMLayout into it
DuiLayout *lowerLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *lowerLayoutPolicy = new DuiLinearLayoutPolicy(lowerLayout, Qt::Vertical);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::AutoPSMText), 0);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::AutoPSMDescText), 1);
lowerLayoutPolicy->addItemAtPosition(disablePSMLayout, 2);
//temp duiLabel (as long as the duiSlider doesn't support thumbLabel)
sliderLabel = new DuiLabel(timeInString(batteryGConf->PSMThreshold(), DcpBattery::PSMThresholdValueText));
lowerLayoutPolicy->addItemAtPosition(sliderLabel, 3);
initSlider();
lowerLayoutPolicy->addItemAtPosition(slider, 4);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::AutoPSMAdv1Text), 5);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(QString("- " + DcpBattery::AutoPSMAdv2Text)), 6);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(QString("- " + DcpBattery::AutoPSMAdv3Text)), 7);
/*
landscapePolicy->addItemAtPosition(
new DcpSpacerItem(this, widgetWidth, 10, QSizePolicy::Expanding,
QSizePolicy::Expanding), 0, Qt::AlignLeft);
mainLayoutPolicy->addItemAtPosition(centralLayout, 1, Qt::AlignHCenter);
mainLayoutPolicy->addItemAtPosition(
new DcpSpacerItem(this, widgetWidth, 10, QSizePolicy::Expanding,
QSizePolicy::Expanding), 2, Qt::AlignRight);
*/
//create mainLayout
DuiLayout *mainLayout = new DuiLayout(this);
DuiLinearLayoutPolicy *landscapeLayoutPolicy = new DuiLinearLayoutPolicy(mainLayout, Qt::Vertical);
//TODO create portraitLayoutPolicy and listen the orientation change signals
landscapeLayoutPolicy->addItemAtPosition(upperLayout, 0);
landscapeLayoutPolicy->addItemAtPosition(lowerLayout, 1);
this->setLayout(mainLayout);
}
void BatteryWidget::initBatteryGConf()
{
//define the slots that catch the changing GConf key values
QHash<BatteryGConf::GConfKey, QString> keysAndSlots;
keysAndSlots.insert(BatteryGConf::RemainingTalkTimeKey, "RemainingTalkTimeChanged");
keysAndSlots.insert(BatteryGConf::RemainingStandByTimeKey, "RemainingTalkStandByChanged");
keysAndSlots.insert(BatteryGConf::BatteryLevelKey, "BatteryLevelChanged");
keysAndSlots.insert(BatteryGConf::ChargingKey, "ChargingChanged");
batteryGConf = new BatteryGConf(this, keysAndSlots);
}
void BatteryWidget::initSlider()
{
slider = new DuiSlider();
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(sliderValueChanged(int)));
sliderValues = batteryGConf->PSMThresholdValues();
slider->setRange(0,sliderValues.size()-1);
slider->setValue(sliderValues.indexOf(batteryGConf->PSMThreshold()));
slider->setThumbLabel(timeInString(batteryGConf->PSMThreshold(), DcpBattery::PSMThresholdValueText));
slider->setThumbLabelVisible(true);
slider->setOrientation(Qt::Horizontal);
}
void BatteryWidget::sliderValueChanged(int newValue)
{
slider->setThumbLabel(timeInString(sliderValues.at(newValue), DcpBattery::PSMThresholdValueText));
//temp duiLabel (as long as the duiSlider doesn't support thumbLabel)
sliderLabel->setText(timeInString(sliderValues.at(newValue), DcpBattery::PSMThresholdValueText));
}
QString BatteryWidget::timeInString(int time, QString pattern)
{
//removing possible extra "!! " from in front
QString patternCut = pattern.right(pattern.length() - pattern.indexOf("%1"));
//saving possible extra "!! " from in front
QString prefix = pattern.left(pattern.indexOf("%1"));
QStringList list = patternCut.split("%1", QString::SkipEmptyParts);
if(time < 60)
return QString("%1%2%3").arg(prefix).arg(time).arg(list.at(0).trimmed());
else {
QVariant minutes = time%60;
if(minutes.toInt() == 0)
minutes = "00";
return QString("%1%2:%3%4").arg(prefix).arg(time/60).arg(minutes.toString()).arg(list.at(1).trimmed());
}
}
void BatteryWidget::updateButton(DuiButton *button, bool toggle)
{
if(toggle)
button->setText("ON");
else
button->setText("OFF");
button->setChecked(toggle);
}
void BatteryWidget::BatteryPSMToggleChanged(QString key, bool value)
{
qDebug() << "JAKAKAKAKKA: " << key << " JAKJKAJKJJKA " << value;
}
<commit_msg>Debug removed (compilation errors)<commit_after>#include "batterywidget.h"
#include "batterytranslation.h"
#include "dcpbattery.h"
#include "dcpspaceritem.h"
#include "batterygconf.h"
#include <DuiButton>
#include <DuiLayout>
#include <DuiGridLayoutPolicy>
#include <DuiLinearLayoutPolicy>
#include <DuiLabel>
#include <DuiSlider>
BatteryWidget::BatteryWidget(QGraphicsWidget *parent)
:DcpWidget(parent)
{
setReferer(DcpBattery::None);
initWidget();
}
BatteryWidget::~BatteryWidget()
{
delete batteryGConf;
batteryGConf = NULL;
}
void BatteryWidget::initWidget()
{
//create gconf if
initBatteryGConf();
//testing purposes
batteryGConf->setRemainingTalkTime(140);
batteryGConf->setRemainingStandByTime(340);
batteryGConf->setPSMThreshold(20);
QList<int> values;
values << 10 << 20 << 30 << 60 << 90 << 120 << 150 << 180 << 210;
batteryGConf->setPSMThresholdValues(values);
batteryGConf->setPSMToggle(true);
//create talkTimeLayout
DuiLayout *talkTimeLayout = new DuiLayout(0);
DuiGridLayoutPolicy *talkTimeLayoutPolicy = new DuiGridLayoutPolicy(talkTimeLayout);
//TODO add the charging icon to position 0, 0, 1, 2
talkTimeLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::TalkTimeText), 0, 1);
talkTimeLabel = new DuiLabel(timeInString(batteryGConf->remainingTalkTime(), DcpBattery::TalkTimeValueText));
talkTimeLayoutPolicy->addItemAtPosition(talkTimeLabel, 1, 1);
//create standByTimeLayout
DuiLayout *standByTimeLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *standByTimeLayoutPolicy = new DuiLinearLayoutPolicy(standByTimeLayout, Qt::Vertical);
standByTimeLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::StandByTimeText), 0);
standByTimeLabel = new DuiLabel(timeInString(batteryGConf->remainingStandByTime(), DcpBattery::StandByTimeValueText));
standByTimeLayoutPolicy->addItemAtPosition(standByTimeLabel, 1);
//create PSMLayout
DuiLayout *PSMLayout = new DuiLayout(0);
DuiGridLayoutPolicy *PSMLayoutPolicy = new DuiGridLayoutPolicy(PSMLayout);
PSMLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::PSMText), 0, 0);
PSMLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::NBCText), 1, 0);
PSMButton = new DuiButton();
PSMButton->setCheckable(true);
updateButton(PSMButton, batteryGConf->PSMToggle());
PSMLayoutPolicy->addItemAtPosition(PSMButton, 0, 1, 2, 1);
//create upperLayout and put talkTimeLayot, standByTimeLayout and PSMLayout into it
DuiLayout *upperLayout = new DuiLayout(0);
DuiGridLayoutPolicy *upperLayoutPolicy = new DuiGridLayoutPolicy(upperLayout);
upperLayoutPolicy->addItemAtPosition(talkTimeLayout, 0, 0);
upperLayoutPolicy->addItemAtPosition(standByTimeLayout, 0, 1);
upperLayoutPolicy->addItemAtPosition(PSMLayout, 1, 0);
//create disablePSMLayout
DuiLayout *disablePSMLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *disablePSMLayoutPolicy = new DuiLinearLayoutPolicy(disablePSMLayout, Qt::Horizontal);
disablePSMButton = new DuiButton();
disablePSMButton->setCheckable(true);
updateButton(disablePSMButton, batteryGConf->PSMDisabled());
disablePSMLayoutPolicy->addItemAtPosition(disablePSMButton, 0);
disablePSMLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::DisablePSMText), 1);
//create lowerLayout and put disablePSMLayout into it
DuiLayout *lowerLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *lowerLayoutPolicy = new DuiLinearLayoutPolicy(lowerLayout, Qt::Vertical);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::AutoPSMText), 0);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::AutoPSMDescText), 1);
lowerLayoutPolicy->addItemAtPosition(disablePSMLayout, 2);
//temp duiLabel (as long as the duiSlider doesn't support thumbLabel)
sliderLabel = new DuiLabel(timeInString(batteryGConf->PSMThreshold(), DcpBattery::PSMThresholdValueText));
lowerLayoutPolicy->addItemAtPosition(sliderLabel, 3);
initSlider();
lowerLayoutPolicy->addItemAtPosition(slider, 4);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(DcpBattery::AutoPSMAdv1Text), 5);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(QString("- " + DcpBattery::AutoPSMAdv2Text)), 6);
lowerLayoutPolicy->addItemAtPosition(new DuiLabel(QString("- " + DcpBattery::AutoPSMAdv3Text)), 7);
/*
landscapePolicy->addItemAtPosition(
new DcpSpacerItem(this, widgetWidth, 10, QSizePolicy::Expanding,
QSizePolicy::Expanding), 0, Qt::AlignLeft);
mainLayoutPolicy->addItemAtPosition(centralLayout, 1, Qt::AlignHCenter);
mainLayoutPolicy->addItemAtPosition(
new DcpSpacerItem(this, widgetWidth, 10, QSizePolicy::Expanding,
QSizePolicy::Expanding), 2, Qt::AlignRight);
*/
//create mainLayout
DuiLayout *mainLayout = new DuiLayout(this);
DuiLinearLayoutPolicy *landscapeLayoutPolicy = new DuiLinearLayoutPolicy(mainLayout, Qt::Vertical);
//TODO create portraitLayoutPolicy and listen the orientation change signals
landscapeLayoutPolicy->addItemAtPosition(upperLayout, 0);
landscapeLayoutPolicy->addItemAtPosition(lowerLayout, 1);
this->setLayout(mainLayout);
}
void BatteryWidget::initBatteryGConf()
{
//define the slots that catch the changing GConf key values
QHash<BatteryGConf::GConfKey, QString> keysAndSlots;
keysAndSlots.insert(BatteryGConf::RemainingTalkTimeKey, "RemainingTalkTimeChanged");
keysAndSlots.insert(BatteryGConf::RemainingStandByTimeKey, "RemainingTalkStandByChanged");
keysAndSlots.insert(BatteryGConf::BatteryLevelKey, "BatteryLevelChanged");
keysAndSlots.insert(BatteryGConf::ChargingKey, "ChargingChanged");
batteryGConf = new BatteryGConf(this, keysAndSlots);
}
void BatteryWidget::initSlider()
{
slider = new DuiSlider();
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(sliderValueChanged(int)));
sliderValues = batteryGConf->PSMThresholdValues();
slider->setRange(0,sliderValues.size()-1);
slider->setValue(sliderValues.indexOf(batteryGConf->PSMThreshold()));
slider->setThumbLabel(timeInString(batteryGConf->PSMThreshold(), DcpBattery::PSMThresholdValueText));
slider->setThumbLabelVisible(true);
slider->setOrientation(Qt::Horizontal);
}
void BatteryWidget::sliderValueChanged(int newValue)
{
slider->setThumbLabel(timeInString(sliderValues.at(newValue), DcpBattery::PSMThresholdValueText));
//temp duiLabel (as long as the duiSlider doesn't support thumbLabel)
sliderLabel->setText(timeInString(sliderValues.at(newValue), DcpBattery::PSMThresholdValueText));
}
QString BatteryWidget::timeInString(int time, QString pattern)
{
//removing possible extra "!! " from in front
QString patternCut = pattern.right(pattern.length() - pattern.indexOf("%1"));
//saving possible extra "!! " from in front
QString prefix = pattern.left(pattern.indexOf("%1"));
QStringList list = patternCut.split("%1", QString::SkipEmptyParts);
if(time < 60)
return QString("%1%2%3").arg(prefix).arg(time).arg(list.at(0).trimmed());
else {
QVariant minutes = time%60;
if(minutes.toInt() == 0)
minutes = "00";
return QString("%1%2:%3%4").arg(prefix).arg(time/60).arg(minutes.toString()).arg(list.at(1).trimmed());
}
}
void BatteryWidget::updateButton(DuiButton *button, bool toggle)
{
if(toggle)
button->setText("ON");
else
button->setText("OFF");
button->setChecked(toggle);
}
void BatteryWidget::BatteryPSMToggleChanged(QString key, bool value)
{
}
<|endoftext|> |
<commit_before>#include <bench/spbench/spbenchsolver.h>
void bench_printhelp()
{
cout<< " \nbenchsolver : performs a benchmark of all the solvers available in Eigen \n\n";
cout<< " MATRIX FOLDER : \n";
cout<< " The matrices for the benchmark should be collected in a folder specified with an environment variable EIGEN_MATRIXDIR \n";
cout<< " This folder should contain the subfolders real/ and complex/ : \n";
cout<< " The matrices are stored using the matrix market coordinate format \n";
cout<< " The matrix and associated right-hand side (rhs) files are named respectively \n";
cout<< " as MatrixName.mtx and MatrixName_b.mtx. If the rhs does not exist, a random one is generated. \n";
cout<< " If a matrix is SPD, the matrix should be named as MatrixName_SPD.mtx \n";
cout<< " If a true solution exists, it should be named as MatrixName_x.mtx; \n" ;
cout<< " it will be used to compute the norm of the error relative to the computed solutions\n\n";
cout<< " OPTIONS : \n";
cout<< " -h or --help \n print this help and return\n\n";
cout<< " -d matrixdir \n Use matrixdir as the matrix folder instead of the one specified in the environment variable EIGEN_MATRIXDIR\n\n";
cout<< " -o outputfile.html \n Output the statistics to a html file \n\n";
cout<< " --eps <RelErr> Sets the relative tolerance for iterative solvers (default 1e-08)
cout<< " --maxits <MaxIts> Sets the maximum number of iterations (default 1000)
}
int main(int argc, char ** args)
{
bool help = ( get_options(argc, args, "-h") || get_options(argc, args, "--help") );
if(help) {
bench_printhelp();
return 0;
}
// Get the location of the test matrices
string matrix_dir;
if (!get_options(argc, args, "-d", &matrix_dir))
{
if(getenv("EIGEN_MATRIXDIR") == NULL){
std::cerr << "Please, specify the location of the matrices with -d mat_folder or the environment variable EIGEN_MATRIXDIR \n";
std::cerr << " Run with --help to see the list of all the available options \n";
return -1;
}
matrix_dir = getenv("EIGEN_MATRIXDIR");
}
std::ofstream statbuf;
string statFile ;
// Get the file to write the statistics
bool statFileExists = get_options(argc, args, "-o", &statFile);
if(statFileExists)
{
statbuf.open(statFile.c_str(), std::ios::out);
if(statbuf.good()){
statFileExists = true;
printStatheader(statbuf);
statbuf.close();
}
else
std::cerr << "Unable to open the provided file for writting... \n";
}
// Get the maximum number of iterations and the tolerance
int maxiters = 1000;
double tol = 1e-08;
string inval;
if (get_options(argc, args, "--eps", &inval))
tol = atof(inval.c_str());
if(get_options(argc, args, "--maxits", &inval))
maxiters = atoi(inval.c_str());
string current_dir;
// Test the matrices in %EIGEN_MATRIXDIR/real
current_dir = matrix_dir + "/real";
Browse_Matrices<double>(current_dir, statFileExists, statFile,maxiters, tol);
// Test the matrices in %EIGEN_MATRIXDIR/complex
current_dir = matrix_dir + "/complex";
Browse_Matrices<std::complex<double> >(current_dir, statFileExists, statFile, maxiters, tol);
if(statFileExists)
{
statbuf.open(statFile.c_str(), std::ios::app);
statbuf << "</TABLE> \n";
cout << "\n Output written in " << statFile << " ...\n";
statbuf.close();
}
return 0;
}
<commit_msg>fix sparse benchmark help<commit_after>#include <bench/spbench/spbenchsolver.h>
void bench_printhelp()
{
cout<< " \nbenchsolver : performs a benchmark of all the solvers available in Eigen \n\n";
cout<< " MATRIX FOLDER : \n";
cout<< " The matrices for the benchmark should be collected in a folder specified with an environment variable EIGEN_MATRIXDIR \n";
cout<< " This folder should contain the subfolders real/ and complex/ : \n";
cout<< " The matrices are stored using the matrix market coordinate format \n";
cout<< " The matrix and associated right-hand side (rhs) files are named respectively \n";
cout<< " as MatrixName.mtx and MatrixName_b.mtx. If the rhs does not exist, a random one is generated. \n";
cout<< " If a matrix is SPD, the matrix should be named as MatrixName_SPD.mtx \n";
cout<< " If a true solution exists, it should be named as MatrixName_x.mtx; \n" ;
cout<< " it will be used to compute the norm of the error relative to the computed solutions\n\n";
cout<< " OPTIONS : \n";
cout<< " -h or --help \n print this help and return\n\n";
cout<< " -d matrixdir \n Use matrixdir as the matrix folder instead of the one specified in the environment variable EIGEN_MATRIXDIR\n\n";
cout<< " -o outputfile.html \n Output the statistics to a html file \n\n";
cout<< " --eps <RelErr> Sets the relative tolerance for iterative solvers (default 1e-08) \n\n";
cout<< " --maxits <MaxIts> Sets the maximum number of iterations (default 1000) \n\n";
}
int main(int argc, char ** args)
{
bool help = ( get_options(argc, args, "-h") || get_options(argc, args, "--help") );
if(help) {
bench_printhelp();
return 0;
}
// Get the location of the test matrices
string matrix_dir;
if (!get_options(argc, args, "-d", &matrix_dir))
{
if(getenv("EIGEN_MATRIXDIR") == NULL){
std::cerr << "Please, specify the location of the matrices with -d mat_folder or the environment variable EIGEN_MATRIXDIR \n";
std::cerr << " Run with --help to see the list of all the available options \n";
return -1;
}
matrix_dir = getenv("EIGEN_MATRIXDIR");
}
std::ofstream statbuf;
string statFile ;
// Get the file to write the statistics
bool statFileExists = get_options(argc, args, "-o", &statFile);
if(statFileExists)
{
statbuf.open(statFile.c_str(), std::ios::out);
if(statbuf.good()){
statFileExists = true;
printStatheader(statbuf);
statbuf.close();
}
else
std::cerr << "Unable to open the provided file for writting... \n";
}
// Get the maximum number of iterations and the tolerance
int maxiters = 1000;
double tol = 1e-08;
string inval;
if (get_options(argc, args, "--eps", &inval))
tol = atof(inval.c_str());
if(get_options(argc, args, "--maxits", &inval))
maxiters = atoi(inval.c_str());
string current_dir;
// Test the matrices in %EIGEN_MATRIXDIR/real
current_dir = matrix_dir + "/real";
Browse_Matrices<double>(current_dir, statFileExists, statFile,maxiters, tol);
// Test the matrices in %EIGEN_MATRIXDIR/complex
current_dir = matrix_dir + "/complex";
Browse_Matrices<std::complex<double> >(current_dir, statFileExists, statFile, maxiters, tol);
if(statFileExists)
{
statbuf.open(statFile.c_str(), std::ios::app);
statbuf << "</TABLE> \n";
cout << "\n Output written in " << statFile << " ...\n";
statbuf.close();
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class ComparisonColumn {
protected:
static constexpr std::size_t mRepeat =
static_cast<std::size_t>(1e8 / (NumberOfRows * NumberOfColumns));
TMatrixType mA;
TMatrixType mB;
TMatrixType mResult;
std::string mColumnName;
void initialize(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = j + 1.00;
}
void initializeInverse(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = 1.00 / (i + 1);
}
public:
ComparisonColumn() = delete;
ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
initialize(mA);
initialize(mB);
initialize(mResult);
}
std::string const& GetColumnName() { return mColumnName; }
TMatrixType& GetResult() { return mResult; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
constexpr double tolerance = 1e-12;
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
if (std::abs(mResult(i, j) != Reference(i, j)) > tolerance){
std::cout << mResult(i, j) << " != " << Reference(i, j) ;
return false;
}
return true;
}
void MeasureSumTime() {
initialize(mA);
initialize(mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA + mB;
mB.noalias() = mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = D * mA;
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureATransposeBAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA.transpose() * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class UblasComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
using BaseType =
ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;
UblasComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
ColumnName) {}
void MeasureSumTime() {
BaseType::initialize(BaseType::mA);
BaseType::initialize(BaseType::mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
boost::numeric::ublas::noalias(BaseType::mResult) =
BaseType::mA + BaseType::mB;
boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) = prod(D, BaseType::mA);
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureATransposeBAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(trans(BaseType::mA), TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class EmptyComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
EmptyComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
void MeasureSumTime() { std::cout << "\t\t"; }
void MeasureMultTime() { std::cout << "\t\t"; }
void MeasureABAMultTime() { std::cout << "\t\t"; }
void MeasureATransposeBAMultTime() { std::cout << "\t\t"; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
return true;
}
};
template <std::size_t NumberOfRows, std::size_t NumberOfColumns>
class BenchmarkMatrix {
ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mUblasColumn;
#endif
public:
BenchmarkMatrix()
: mAMatrixColumn("AMatrix"),
mEigenColumn("Eigen"),
mUblasColumn("Ublas") {
std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
<< "]";
std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
std::cout << "\t\t" << mEigenColumn.GetColumnName();
std::cout << "\t\t" << mUblasColumn.GetColumnName();
std::cout << std::endl;
}
~BenchmarkMatrix() = default;
void Run() {
std::cout << "C = A + B";
mAMatrixColumn.MeasureSumTime();
mEigenColumn.MeasureSumTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureSumTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B";
mAMatrixColumn.MeasureMultTime();
mEigenColumn.MeasureMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B * A";
mAMatrixColumn.MeasureABAMultTime();
mEigenColumn.MeasureABAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureABAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A^T * B * A";
mAMatrixColumn.MeasureATransposeBAMultTime();
mEigenColumn.MeasureATransposeBAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureATransposeBAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
// std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
// std::cout << "Eigen : " << mEigenColumn.GetResult() << std::endl;
std::cout << std::endl;
}
};
int main() {
BenchmarkMatrix<3, 3> benchmark_3_3;
benchmark_3_3.Run();
BenchmarkMatrix<4, 4> benchmark_4_4;
benchmark_4_4.Run();
BenchmarkMatrix<6, 6> benchmark_6_6;
benchmark_6_6.Run();
BenchmarkMatrix<12, 12> benchmark_12_12;
benchmark_12_12.Run();
BenchmarkMatrix<16, 16> benchmark_16_16;
benchmark_16_16.Run();
return 0;
}
<commit_msg>adding the macro to disable boost part in benchmarking<commit_after>#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class ComparisonColumn {
protected:
static constexpr std::size_t mRepeat =
static_cast<std::size_t>(1e8 / (NumberOfRows * NumberOfColumns));
TMatrixType mA;
TMatrixType mB;
TMatrixType mResult;
std::string mColumnName;
void initialize(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = j + 1.00;
}
void initializeInverse(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = 1.00 / (i + 1);
}
public:
ComparisonColumn() = delete;
ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
initialize(mA);
initialize(mB);
initialize(mResult);
}
std::string const& GetColumnName() { return mColumnName; }
TMatrixType& GetResult() { return mResult; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
constexpr double tolerance = 1e-12;
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
if (std::abs(mResult(i, j) != Reference(i, j)) > tolerance){
std::cout << mResult(i, j) << " != " << Reference(i, j) ;
return false;
}
return true;
}
void MeasureSumTime() {
initialize(mA);
initialize(mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA + mB;
mB.noalias() = mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = D * mA;
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureATransposeBAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA.transpose() * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class UblasComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
using BaseType =
ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;
UblasComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
ColumnName) {}
void MeasureSumTime() {
BaseType::initialize(BaseType::mA);
BaseType::initialize(BaseType::mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
boost::numeric::ublas::noalias(BaseType::mResult) =
BaseType::mA + BaseType::mB;
boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) = prod(D, BaseType::mA);
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureATransposeBAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(trans(BaseType::mA), TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
#endif
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class EmptyComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
EmptyComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
void MeasureSumTime() { std::cout << "\t\t"; }
void MeasureMultTime() { std::cout << "\t\t"; }
void MeasureABAMultTime() { std::cout << "\t\t"; }
void MeasureATransposeBAMultTime() { std::cout << "\t\t"; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
return true;
}
};
template <std::size_t NumberOfRows, std::size_t NumberOfColumns>
class BenchmarkMatrix {
ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mUblasColumn;
#endif
public:
BenchmarkMatrix()
: mAMatrixColumn("AMatrix"),
mEigenColumn("Eigen"),
mUblasColumn("Ublas") {
std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
<< "]";
std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
std::cout << "\t\t" << mEigenColumn.GetColumnName();
std::cout << "\t\t" << mUblasColumn.GetColumnName();
std::cout << std::endl;
}
~BenchmarkMatrix() = default;
void Run() {
std::cout << "C = A + B";
mAMatrixColumn.MeasureSumTime();
mEigenColumn.MeasureSumTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureSumTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B";
mAMatrixColumn.MeasureMultTime();
mEigenColumn.MeasureMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B * A";
mAMatrixColumn.MeasureABAMultTime();
mEigenColumn.MeasureABAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureABAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A^T * B * A";
mAMatrixColumn.MeasureATransposeBAMultTime();
mEigenColumn.MeasureATransposeBAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureATransposeBAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
// std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
// std::cout << "Eigen : " << mEigenColumn.GetResult() << std::endl;
std::cout << std::endl;
}
};
int main() {
BenchmarkMatrix<3, 3> benchmark_3_3;
benchmark_3_3.Run();
BenchmarkMatrix<4, 4> benchmark_4_4;
benchmark_4_4.Run();
BenchmarkMatrix<6, 6> benchmark_6_6;
benchmark_6_6.Run();
BenchmarkMatrix<12, 12> benchmark_12_12;
benchmark_12_12.Run();
BenchmarkMatrix<16, 16> benchmark_16_16;
benchmark_16_16.Run();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016, Andrej Kislovskij
*
* This is PUBLIC DOMAIN software so use at your own risk as it comes
* with no warranties. This code is yours to share, use and modify without
* any restrictions or obligations.
*
* For more information see conwrap/LICENSE or refer refer to http://unlicense.org
*
* Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
*/
#include <asio.hpp>
#include <chrono>
#include <conwrap/ProcessorAsio.hpp>
#include <conwrap/ProcessorQueue.hpp>
#include <functional>
#include <iostream>
struct Dummy
{
// TODO: this is a temporary fix before reflection is implemented
void setProcessor(conwrap::Processor<Dummy>*) {}
};
class Server
{
public:
Server(short p) : port(p) {}
void close()
{
// closing acceptor
acceptorPtr->close();
// closing socket
if (socketPtr->is_open())
{
try {
socketPtr->shutdown(asio::socket_base::shutdown_both);
} catch (...) {}
try {
socketPtr->close();
} catch (...) {}
}
}
void ping()
{
if (socketPtr->is_open())
{
socketPtr->send(asio::buffer("ping\n\r"));
}
}
void setProcessor(conwrap::ProcessorAsio<Server>* p)
{
processorPtr = p;
// creating an acceptor
acceptorPtr = std::make_unique<asio::ip::tcp::acceptor>(
*processorPtr->getDispatcher(),
asio::ip::tcp::endpoint(
asio::ip::tcp::v4(),
port
)
);
// creating a socket
socketPtr = std::make_unique<asio::ip::tcp::socket>(
*processorPtr->getDispatcher()
);
acceptorPtr->async_accept(
*socketPtr,
[=](const std::error_code error)
{
// this wrapping is needed to pass handler from asio thread to the processor thread
processorPtr->wrapHandler([=]
{
// start receiving data
onData(error, 0);
})();
}
);
}
// TODO: this is a temporary fix before reflection is implemented
void setProcessor(conwrap::ProcessorQueue<Server>*) {}
protected:
void onData(const std::error_code error, const std::size_t receivedSize)
{
if (!error)
{
// if there is data to send back to the client
if (receivedSize > 0)
{
socketPtr->send(asio::buffer(buffer, receivedSize));
}
// keep receiving
socketPtr->async_read_some(
asio::buffer(buffer, BUFFER_SIZE),
[=](const std::error_code error, const std::size_t receivedSize)
{
// this wrapping is needed to pass handler from asio thread to the processor thread
processorPtr->wrapHandler([=]
{
onData(error, receivedSize);
})();
}
);
}
}
private:
conwrap::ProcessorAsio<Server>* processorPtr;
short port;
std::unique_ptr<asio::ip::tcp::acceptor> acceptorPtr;
std::unique_ptr<asio::ip::tcp::socket> socketPtr;
enum {
BUFFER_SIZE = 1024
};
char buffer[BUFFER_SIZE];
};
int main(int argc, char *argv[])
{
{
conwrap::ProcessorQueue<Dummy> processorQueue;
processorQueue.process([]
{
std::cout << "Hello from queue task\n\r";
});
}
std::cout << "Back to main\n\r";
{
conwrap::ProcessorAsio<Dummy> processorAsio;
processorAsio.process([]
{
std::cout << "Hello from asio task\n\r";
});
processorAsio.flush();
std::cout << "Back to main\n\r";
}
{
conwrap::ProcessorAsio<Server> processorAsio(1234);
std::cout << "Echo server is listening on 1234 port (press ^C to terminate)\n\r";
// now server runs on a separate thread; any other logic can be done here
for (int i = 0; i < 3; i++)
{
// submitting a task in a regular way
processorAsio.process([]() -> int
{
std::cout << "Hello from asio task\n\r";
// this is just to demonstrate that now asio can be used with tasks that return value
return 1234;
});
for (int j = 0; j < 3; j++)
{
// submitting a task directly via asio io_service
processorAsio.getDispatcher()->post(
// a task submitted directly via asio io_service must be wrapped as following
processorAsio.wrapHandler([&]
{
processorAsio.getResource()->ping();
})
);
// sleeping
std::this_thread::sleep_for(std::chrono::seconds{5});
}
// after this flush all tasks including asio handlers are executed
processorAsio.flush();
std::cout << "All tasks were flushed\n\r";
}
// without this close processor's destructor would wait forever for async receive handler
// sync socket operations are thread safe since asio 1.4.0 so posting to asio thread is optional
processorAsio.getDispatcher()->post([&]
{
processorAsio.getResource()->close();
});
// this flush is required as handler posted to asio captured processorAsio reference
processorAsio.flush();
}
return 0;
}
<commit_msg>Minor changes<commit_after>/*
* Copyright 2016, Andrej Kislovskij
*
* This is PUBLIC DOMAIN software so use at your own risk as it comes
* with no warranties. This code is yours to share, use and modify without
* any restrictions or obligations.
*
* For more information see conwrap/LICENSE or refer refer to http://unlicense.org
*
* Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
*/
#include <asio.hpp>
#include <chrono>
#include <conwrap/ProcessorAsio.hpp>
#include <conwrap/ProcessorQueue.hpp>
#include <functional>
#include <iostream>
struct Dummy
{
// TODO: this is a temporary fix before reflection is implemented
void setProcessor(conwrap::Processor<Dummy>*) {}
};
class Server
{
public:
Server(short p) : port(p) {}
void close()
{
// closing acceptor
acceptorPtr->close();
// closing socket
if (socketPtr->is_open())
{
try {
socketPtr->shutdown(asio::socket_base::shutdown_both);
} catch (...) {}
try {
socketPtr->close();
} catch (...) {}
}
}
void ping()
{
if (socketPtr->is_open())
{
socketPtr->send(asio::buffer("ping\n\r"));
}
}
void setProcessor(conwrap::ProcessorAsio<Server>* p)
{
processorPtr = p;
// creating an acceptor
acceptorPtr = std::make_unique<asio::ip::tcp::acceptor>(
*processorPtr->getDispatcher(),
asio::ip::tcp::endpoint(
asio::ip::tcp::v4(),
port
)
);
// creating a socket
socketPtr = std::make_unique<asio::ip::tcp::socket>(
*processorPtr->getDispatcher()
);
acceptorPtr->async_accept(
*socketPtr,
[=](const std::error_code error)
{
// wrapping is needed to pass handler from asio's thread to the processor's thread
processorPtr->wrapHandler([=]
{
// start receiving data
onData(error, 0);
})();
}
);
}
// TODO: this is a temporary fix before reflection is implemented
void setProcessor(conwrap::ProcessorQueue<Server>*) {}
protected:
void onData(const std::error_code error, const std::size_t receivedSize)
{
if (!error)
{
// if there is data to send back to the client
if (receivedSize > 0)
{
socketPtr->send(asio::buffer(buffer, receivedSize));
}
// keep receiving
socketPtr->async_read_some(
asio::buffer(buffer, BUFFER_SIZE),
[=](const std::error_code error, const std::size_t receivedSize)
{
// wrapping is needed to pass handler from asio's thread to the processor's thread
processorPtr->wrapHandler([=]
{
onData(error, receivedSize);
})();
}
);
}
}
private:
conwrap::ProcessorAsio<Server>* processorPtr;
short port;
std::unique_ptr<asio::ip::tcp::acceptor> acceptorPtr;
std::unique_ptr<asio::ip::tcp::socket> socketPtr;
enum {
BUFFER_SIZE = 1024
};
char buffer[BUFFER_SIZE];
};
int main(int argc, char *argv[])
{
{
conwrap::ProcessorQueue<Dummy> processorQueue;
processorQueue.process([]
{
std::cout << "Hello from queue task\n\r";
});
}
std::cout << "Back to main\n\r";
{
conwrap::ProcessorAsio<Dummy> processorAsio;
processorAsio.process([]
{
std::cout << "Hello from asio task\n\r";
});
processorAsio.flush();
std::cout << "Back to main\n\r";
}
{
conwrap::ProcessorAsio<Server> processorAsio(1234);
std::cout << "Echo server is listening on 1234 port (press ^C to terminate)\n\r";
// now server runs on a separate thread; any other logic can be done here
for (int i = 0; i < 3; i++)
{
// submitting a task in a regular way
processorAsio.process([]() -> int
{
std::cout << "Hello from asio task\n\r";
// this is just to demonstrate that now asio can be used with tasks that return value
return 1234;
});
for (int j = 0; j < 3; j++)
{
// submitting a task directly via asio io_service
processorAsio.getDispatcher()->post(
// a task submitted directly via asio io_service must be wrapped as following
processorAsio.wrapHandler([&]
{
processorAsio.getResource()->ping();
})
);
// sleeping
std::this_thread::sleep_for(std::chrono::seconds{5});
}
// after this flush all tasks including asio handlers are executed
processorAsio.flush();
std::cout << "All tasks were flushed\n\r";
}
// without this close processor's destructor would wait forever for async receive handler
// sync socket operations are thread safe since asio 1.4.0 so posting to asio thread is optional
processorAsio.getDispatcher()->post([&]
{
processorAsio.getResource()->close();
});
// this flush is required as handler posted to asio captured processorAsio reference
processorAsio.flush();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "uinput_device.h"
#include "ros/ros.h"
#include <linux/input.h>
#include <linux/uinput.h>
#include <linux/types.h>
#include <algorithm>
#include <fcntl.h>
#include <stdio.h>
#include <sstream>
#include <string>
#include "util.h"
#include <lg_msg_defs/EvdevEvent.h>
#include <lg_msg_defs/EvdevEvents.h>
#include <lg_msg_defs/EvdevDeviceInfo.h>
// emulate a typical ELO touchscreen
const __s32 MIN_TRACKING_ID = 0;
const __s32 MAX_TRACKING_ID = 65535;
const __s32 MIN_SLOT = 0;
const __s32 MAX_SLOT = 7;
UinputDeviceInitError::UinputDeviceInitError(const char* msg): msg_(msg) {}
UinputDeviceInitError::UinputDeviceInitError(const std::string& msg): msg_(msg) {}
UinputDeviceInitError::~UinputDeviceInitError() throw() {}
const char* UinputDeviceInitError::what() const throw() {
return msg_.c_str();
}
/**
* \brief Constructor
* \param device_name Human-readable name for the virtual device.
*/
UinputDevice::UinputDevice(const std::string& device_name, bool translate_to_multitouch):
fd_(-1),
device_name_(device_name),
translate_to_multitouch_(translate_to_multitouch),
offscreen_x_(0),
offscreen_y_(0)
{}
/**
* \brief Creates the uinput device.
* \param info Information about the source device.
* \return true if successful.
*/
bool UinputDevice::Init(const lg_msg_defs::EvdevDeviceInfoResponse& info) {
int fd;
// open the special uinput device
fd = open(UinputDeviceConstants::UINPUT_PATH, O_WRONLY | O_NONBLOCK);
if (fd < 0) {
perror("opening the uinput node");
return false;
}
try {
InitDevice_(fd, info);
} catch (UinputDeviceInitError& e) {
ROS_ERROR_STREAM(e.what());
close(fd);
return false;
}
// fd is now a handle for the user device
fd_ = fd;
return true;
}
/**
* \brief Internal helper for creating the uinput device.
*
* Throws UinputDeviceInitError on failure.
*
* \param fd File descriptor to operate on.
* \param info Information about the source device.
*/
void UinputDevice::InitDevice_(int fd, const lg_msg_defs::EvdevDeviceInfoResponse& info) {
struct uinput_user_dev uidev;
int status;
// initialize the user device struct
memset(&uidev, 0, sizeof(uidev));
// set allowed device types and codes
std::size_t i;
std::size_t sz;
sz = info.types.size();
for (i = 0; i < sz; i++) {
EnableCode_(fd, UI_SET_EVBIT, info.types[i]);
}
sz = info.key_codes.size();
for (i = 0; i < sz; i++) {
__u16 code = info.key_codes[i];
if (translate_to_multitouch_ && code == BTN_LEFT) {
code = BTN_TOUCH;
}
EnableCode_(fd, UI_SET_KEYBIT, code);
}
sz = info.rel_codes.size();
for (i = 0; i < sz; i++) {
EnableCode_(fd, UI_SET_RELBIT, info.rel_codes[i]);
}
sz = info.abs_codes.size();
for (i = 0; i < sz; i++) {
__u16 code = info.abs_codes[i];
if (i > info.abs_min.size() || i > info.abs_max.size()) {
std::ostringstream error_msg;
error_msg << "Device info missing abs_min or abs_max for abs code " << code << " at index " << i;
throw UinputDeviceInitError(error_msg.str());
}
EnableCode_(fd, UI_SET_ABSBIT, code);
uidev.absmax[code] = info.abs_max[i];
uidev.absmin[code] = info.abs_min[i];
// set offscreen coords to maximums
if (code == ABS_X) {
offscreen_x_ = info.abs_max[i];
} else if (code == ABS_Y) {
offscreen_y_ = info.abs_max[i];
}
if (translate_to_multitouch_) {
if (code == ABS_X) {
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_POSITION_X);
uidev.absmax[ABS_MT_POSITION_X] = info.abs_max[i];
uidev.absmin[ABS_MT_POSITION_X] = info.abs_min[i];
} else if (code == ABS_Y) {
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_POSITION_Y);
uidev.absmax[ABS_MT_POSITION_Y] = info.abs_max[i];
uidev.absmin[ABS_MT_POSITION_Y] = info.abs_min[i];
}
}
}
if (translate_to_multitouch_) {
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_TRACKING_ID);
uidev.absmax[ABS_MT_TRACKING_ID] = MAX_TRACKING_ID;
uidev.absmin[ABS_MT_TRACKING_ID] = MIN_TRACKING_ID;
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_SLOT);
uidev.absmax[ABS_MT_TRACKING_ID] = MAX_SLOT;
uidev.absmin[ABS_MT_TRACKING_ID] = MIN_SLOT;
}
// set the device name
strncpy(uidev.name, device_name_.c_str(), UINPUT_MAX_NAME_SIZE);
// set more device attributes
uidev.id.bustype = info.bustype;
uidev.id.vendor = info.vendor;
uidev.id.product = info.product;
uidev.id.version = info.version;
// write the device information
status = write(fd, &uidev, sizeof(uidev));
if (status != sizeof(uidev)) {
throw UinputDeviceInitError("Error writing to uinput device");
}
// create the device
status = ioctl(fd, UI_DEV_CREATE);
if (status != 0) {
throw UinputDeviceInitError("Error on ioctl UI_DEV_CREATE");
}
ROS_DEBUG(
"Created device: %s with vendor: %d product: %d version: %d",
uidev.name, uidev.id.vendor, uidev.id.product, uidev.id.version
);
}
/**
* \brief Shortcut for enabling an event type or code during virtual device setup.
*
* Throws UinputDeviceInitError on failure.
*
* \param fd File descriptor to write to.
* \param codeBits Bitmask describing which type of event code to enable.
* \param code Event code to be enabled.
*/
void UinputDevice::EnableCode_(int fd, int codeBits, int code) {
int status = ioctl(fd, codeBits, code);
if (status != 0) {
std::ostringstream error_msg;
error_msg << "Failed to enable code " << codeBits << ":" << code;
throw UinputDeviceInitError(error_msg.str());
}
}
/**
* \brief Waits for the virtual device to appear in the xinput list.
*
* Breaks if ROS is shutdown.
*
* \return true if the device is available.
*/
bool UinputDevice::WaitForXinput() {
using util::exec;
const unsigned int MAX_INTERVAL = 999999;// usec
unsigned int interval = 10000; // usec
std::ostringstream cmd;
cmd << "xinput query-state '" << device_name_ << "'";
while (true) {
usleep(std::min(interval, MAX_INTERVAL));
if (!ros::ok()) {
return false;
}
int status = system(cmd.str().c_str());
if (status == 0) {
return true;
}
interval *= 2;
if (interval > (MAX_INTERVAL*5)) {
ROS_ERROR("Couldn't find device after many attempts... shutting down");
ros::shutdown();
}
}
}
/**
* \brief Floats the xinput device pointer.
* \return true if successful.
*/
bool UinputDevice::FloatPointer() const {
std::ostringstream cmd;
cmd << "/usr/bin/xinput float '" << device_name_ << "'";
int status = system(cmd.str().c_str());
return status == 0;
}
/**
* \brief Handles a ROS message containing a vector of events.
*
* Implicitly writes a SYN event after the incoming events.
*
* Shuts down ROS upon failure.
*
* \param msg A message describing one or more evdev events.
*/
void UinputDevice::HandleEventMessage(const lg_msg_defs::EvdevEvents::Ptr& msg) {
if (fd_ < 0) {
ROS_ERROR("Tried to handle an event message, but UinputDevice was not initialized");
ros::shutdown();
return;
}
std::size_t num_events = msg->events.size();
if (translate_to_multitouch_) {
for (int i = 0; i < num_events; i++) {
lg_msg_defs::EvdevEvent ev = msg->events[i];
__u16 type = ev.type;
__u16 code = ev.code;
__s32 value = ev.value;
if (type == EV_KEY) {
if (code == BTN_LEFT) {
if (value == 1) {
if (!WriteEvent_(EV_ABS, ABS_MT_TRACKING_ID, 1)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
} else if (value == 0) {
if (!WriteEvent_(EV_ABS, ABS_MT_TRACKING_ID, -1)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
}
}
else if (type == EV_ABS) {
if (code == ABS_X) {
if (!WriteEvent_(EV_ABS, ABS_MT_POSITION_X, value)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
else if (code == ABS_Y) {
if (!WriteEvent_(EV_ABS, ABS_MT_POSITION_Y, value)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
}
}
}
for (int i = 0; i < num_events; i++) {
lg_msg_defs::EvdevEvent ev = msg->events[i];
__u16 type = ev.type;
__u16 code = ev.code;
__s32 value = ev.value;
if (translate_to_multitouch_) {
if (type == EV_KEY && code == BTN_LEFT) {
code = BTN_TOUCH;
}
}
if (!WriteEvent_(type, code, value)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
// force an EV_SYN after each message
if (!WriteEvent_(EV_SYN, SYN_REPORT, 0)) {
ROS_ERROR("Error while writing a SYN event");
ros::shutdown();
return;
}
}
/**
* \brief Zeroes the ABS position to clear the cursor.
*/
void UinputDevice::Zero() {
WriteEvent_(EV_ABS, ABS_X, offscreen_x_);
WriteEvent_(EV_ABS, ABS_Y, offscreen_y_);
WriteEvent_(EV_SYN, SYN_REPORT, 0);
}
/*
* \brief Writes an event to the virtual device.
* \param type Event type.
* \param code Event code.
* \param value Event value.
* \return true if successful.
*/
bool UinputDevice::WriteEvent_(__u16 type, __u16 code, __s32 value) {
struct input_event ev;
memset(&ev, 0, sizeof(ev));
ev.type = type;
ev.code = code;
ev.value = value;
int num_wrote = write(fd_, &ev, sizeof(ev));
if (num_wrote != sizeof(ev)) {
return false;
}
ROS_DEBUG(
"Wrote type: %d code: %d value: %d",
ev.type, ev.code, ev.value
);
return true;
}
<commit_msg>Fix multitouch spoofing for TOUCH codes<commit_after>#include "uinput_device.h"
#include "ros/ros.h"
#include <linux/input.h>
#include <linux/uinput.h>
#include <linux/types.h>
#include <algorithm>
#include <fcntl.h>
#include <stdio.h>
#include <sstream>
#include <string>
#include "util.h"
#include <lg_msg_defs/EvdevEvent.h>
#include <lg_msg_defs/EvdevEvents.h>
#include <lg_msg_defs/EvdevDeviceInfo.h>
// emulate a typical ELO touchscreen
const __s32 MIN_TRACKING_ID = 0;
const __s32 MAX_TRACKING_ID = 65535;
const __s32 MIN_SLOT = 0;
const __s32 MAX_SLOT = 7;
UinputDeviceInitError::UinputDeviceInitError(const char* msg): msg_(msg) {}
UinputDeviceInitError::UinputDeviceInitError(const std::string& msg): msg_(msg) {}
UinputDeviceInitError::~UinputDeviceInitError() throw() {}
const char* UinputDeviceInitError::what() const throw() {
return msg_.c_str();
}
/**
* \brief Constructor
* \param device_name Human-readable name for the virtual device.
*/
UinputDevice::UinputDevice(const std::string& device_name, bool translate_to_multitouch):
fd_(-1),
device_name_(device_name),
translate_to_multitouch_(translate_to_multitouch),
offscreen_x_(0),
offscreen_y_(0)
{}
/**
* \brief Creates the uinput device.
* \param info Information about the source device.
* \return true if successful.
*/
bool UinputDevice::Init(const lg_msg_defs::EvdevDeviceInfoResponse& info) {
int fd;
// open the special uinput device
fd = open(UinputDeviceConstants::UINPUT_PATH, O_WRONLY | O_NONBLOCK);
if (fd < 0) {
perror("opening the uinput node");
return false;
}
try {
InitDevice_(fd, info);
} catch (UinputDeviceInitError& e) {
ROS_ERROR_STREAM(e.what());
close(fd);
return false;
}
// fd is now a handle for the user device
fd_ = fd;
return true;
}
/**
* \brief Internal helper for creating the uinput device.
*
* Throws UinputDeviceInitError on failure.
*
* \param fd File descriptor to operate on.
* \param info Information about the source device.
*/
void UinputDevice::InitDevice_(int fd, const lg_msg_defs::EvdevDeviceInfoResponse& info) {
struct uinput_user_dev uidev;
int status;
// initialize the user device struct
memset(&uidev, 0, sizeof(uidev));
// set allowed device types and codes
std::size_t i;
std::size_t sz;
sz = info.types.size();
for (i = 0; i < sz; i++) {
EnableCode_(fd, UI_SET_EVBIT, info.types[i]);
}
sz = info.key_codes.size();
for (i = 0; i < sz; i++) {
__u16 code = info.key_codes[i];
if (translate_to_multitouch_ && code == BTN_LEFT) {
code = BTN_TOUCH;
}
EnableCode_(fd, UI_SET_KEYBIT, code);
}
sz = info.rel_codes.size();
for (i = 0; i < sz; i++) {
EnableCode_(fd, UI_SET_RELBIT, info.rel_codes[i]);
}
sz = info.abs_codes.size();
for (i = 0; i < sz; i++) {
__u16 code = info.abs_codes[i];
if (i > info.abs_min.size() || i > info.abs_max.size()) {
std::ostringstream error_msg;
error_msg << "Device info missing abs_min or abs_max for abs code " << code << " at index " << i;
throw UinputDeviceInitError(error_msg.str());
}
EnableCode_(fd, UI_SET_ABSBIT, code);
uidev.absmax[code] = info.abs_max[i];
uidev.absmin[code] = info.abs_min[i];
// set offscreen coords to maximums
if (code == ABS_X) {
offscreen_x_ = info.abs_max[i];
} else if (code == ABS_Y) {
offscreen_y_ = info.abs_max[i];
}
if (translate_to_multitouch_) {
if (code == ABS_X) {
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_POSITION_X);
uidev.absmax[ABS_MT_POSITION_X] = info.abs_max[i];
uidev.absmin[ABS_MT_POSITION_X] = info.abs_min[i];
} else if (code == ABS_Y) {
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_POSITION_Y);
uidev.absmax[ABS_MT_POSITION_Y] = info.abs_max[i];
uidev.absmin[ABS_MT_POSITION_Y] = info.abs_min[i];
}
}
}
if (translate_to_multitouch_) {
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_TRACKING_ID);
uidev.absmax[ABS_MT_TRACKING_ID] = MAX_TRACKING_ID;
uidev.absmin[ABS_MT_TRACKING_ID] = MIN_TRACKING_ID;
EnableCode_(fd, UI_SET_ABSBIT, ABS_MT_SLOT);
uidev.absmax[ABS_MT_TRACKING_ID] = MAX_SLOT;
uidev.absmin[ABS_MT_TRACKING_ID] = MIN_SLOT;
}
// set the device name
strncpy(uidev.name, device_name_.c_str(), UINPUT_MAX_NAME_SIZE);
// set more device attributes
uidev.id.bustype = info.bustype;
uidev.id.vendor = info.vendor;
uidev.id.product = info.product;
uidev.id.version = info.version;
// write the device information
status = write(fd, &uidev, sizeof(uidev));
if (status != sizeof(uidev)) {
throw UinputDeviceInitError("Error writing to uinput device");
}
// create the device
status = ioctl(fd, UI_DEV_CREATE);
if (status != 0) {
throw UinputDeviceInitError("Error on ioctl UI_DEV_CREATE");
}
ROS_DEBUG(
"Created device: %s with vendor: %d product: %d version: %d",
uidev.name, uidev.id.vendor, uidev.id.product, uidev.id.version
);
}
/**
* \brief Shortcut for enabling an event type or code during virtual device setup.
*
* Throws UinputDeviceInitError on failure.
*
* \param fd File descriptor to write to.
* \param codeBits Bitmask describing which type of event code to enable.
* \param code Event code to be enabled.
*/
void UinputDevice::EnableCode_(int fd, int codeBits, int code) {
int status = ioctl(fd, codeBits, code);
if (status != 0) {
std::ostringstream error_msg;
error_msg << "Failed to enable code " << codeBits << ":" << code;
throw UinputDeviceInitError(error_msg.str());
}
}
/**
* \brief Waits for the virtual device to appear in the xinput list.
*
* Breaks if ROS is shutdown.
*
* \return true if the device is available.
*/
bool UinputDevice::WaitForXinput() {
using util::exec;
const unsigned int MAX_INTERVAL = 999999;// usec
unsigned int interval = 10000; // usec
std::ostringstream cmd;
cmd << "xinput query-state '" << device_name_ << "'";
while (true) {
usleep(std::min(interval, MAX_INTERVAL));
if (!ros::ok()) {
return false;
}
int status = system(cmd.str().c_str());
if (status == 0) {
return true;
}
interval *= 2;
if (interval > (MAX_INTERVAL*5)) {
ROS_ERROR("Couldn't find device after many attempts... shutting down");
ros::shutdown();
}
}
}
/**
* \brief Floats the xinput device pointer.
* \return true if successful.
*/
bool UinputDevice::FloatPointer() const {
std::ostringstream cmd;
cmd << "/usr/bin/xinput float '" << device_name_ << "'";
int status = system(cmd.str().c_str());
return status == 0;
}
/**
* \brief Handles a ROS message containing a vector of events.
*
* Implicitly writes a SYN event after the incoming events.
*
* Shuts down ROS upon failure.
*
* \param msg A message describing one or more evdev events.
*/
void UinputDevice::HandleEventMessage(const lg_msg_defs::EvdevEvents::Ptr& msg) {
if (fd_ < 0) {
ROS_ERROR("Tried to handle an event message, but UinputDevice was not initialized");
ros::shutdown();
return;
}
std::size_t num_events = msg->events.size();
if (translate_to_multitouch_) {
for (int i = 0; i < num_events; i++) {
lg_msg_defs::EvdevEvent ev = msg->events[i];
__u16 type = ev.type;
__u16 code = ev.code;
__s32 value = ev.value;
if (type == EV_KEY) {
if (code == BTN_LEFT || code == BTN_TOUCH) {
if (value == 1) {
if (!WriteEvent_(EV_ABS, ABS_MT_TRACKING_ID, 1)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
} else if (value == 0) {
if (!WriteEvent_(EV_ABS, ABS_MT_TRACKING_ID, -1)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
}
}
else if (type == EV_ABS) {
if (code == ABS_X) {
if (!WriteEvent_(EV_ABS, ABS_MT_POSITION_X, value)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
else if (code == ABS_Y) {
if (!WriteEvent_(EV_ABS, ABS_MT_POSITION_Y, value)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
}
}
}
for (int i = 0; i < num_events; i++) {
lg_msg_defs::EvdevEvent ev = msg->events[i];
__u16 type = ev.type;
__u16 code = ev.code;
__s32 value = ev.value;
if (translate_to_multitouch_) {
if (type == EV_KEY && code == BTN_LEFT) {
code = BTN_TOUCH;
}
}
if (!WriteEvent_(type, code, value)) {
ROS_ERROR("Error while writing an event to the device");
ros::shutdown();
return;
}
}
// force an EV_SYN after each message
if (!WriteEvent_(EV_SYN, SYN_REPORT, 0)) {
ROS_ERROR("Error while writing a SYN event");
ros::shutdown();
return;
}
}
/**
* \brief Zeroes the ABS position to clear the cursor.
*/
void UinputDevice::Zero() {
WriteEvent_(EV_ABS, ABS_X, offscreen_x_);
WriteEvent_(EV_ABS, ABS_Y, offscreen_y_);
WriteEvent_(EV_SYN, SYN_REPORT, 0);
}
/*
* \brief Writes an event to the virtual device.
* \param type Event type.
* \param code Event code.
* \param value Event value.
* \return true if successful.
*/
bool UinputDevice::WriteEvent_(__u16 type, __u16 code, __s32 value) {
struct input_event ev;
memset(&ev, 0, sizeof(ev));
ev.type = type;
ev.code = code;
ev.value = value;
int num_wrote = write(fd_, &ev, sizeof(ev));
if (num_wrote != sizeof(ev)) {
return false;
}
ROS_DEBUG(
"Wrote type: %d code: %d value: %d",
ev.type, ev.code, ev.value
);
return true;
}
<|endoftext|> |
<commit_before>//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions identifies calls to builtin functions that allocate
// or free memory.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Target/TargetData.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// malloc Call Utility Functions.
//
/// isMalloc - Returns true if the value is either a malloc call or a
/// bitcast of the result of a malloc call.
bool llvm::isMalloc(const Value *I) {
return extractMallocCall(I) || extractMallocCallFromBitCast(I);
}
static bool isMallocCall(const CallInst *CI) {
if (!CI)
return false;
Function *Callee = CI->getCalledFunction();
if (Callee == 0 || !Callee->isDeclaration() || Callee->getName() != "malloc")
return false;
// Check malloc prototype.
// FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
// attribute will exist.
const FunctionType *FTy = Callee->getFunctionType();
if (FTy->getNumParams() != 1)
return false;
if (IntegerType *ITy = dyn_cast<IntegerType>(FTy->param_begin()->get())) {
if (ITy->getBitWidth() != 32 && ITy->getBitWidth() != 64)
return false;
return true;
}
return false;
}
/// extractMallocCall - Returns the corresponding CallInst if the instruction
/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
/// ignore InvokeInst here.
const CallInst *llvm::extractMallocCall(const Value *I) {
const CallInst *CI = dyn_cast<CallInst>(I);
return (isMallocCall(CI)) ? CI : NULL;
}
CallInst *llvm::extractMallocCall(Value *I) {
CallInst *CI = dyn_cast<CallInst>(I);
return (isMallocCall(CI)) ? CI : NULL;
}
static bool isBitCastOfMallocCall(const BitCastInst *BCI) {
if (!BCI)
return false;
return isMallocCall(dyn_cast<CallInst>(BCI->getOperand(0)));
}
/// extractMallocCallFromBitCast - Returns the corresponding CallInst if the
/// instruction is a bitcast of the result of a malloc call.
CallInst *llvm::extractMallocCallFromBitCast(Value *I) {
BitCastInst *BCI = dyn_cast<BitCastInst>(I);
return (isBitCastOfMallocCall(BCI)) ? cast<CallInst>(BCI->getOperand(0))
: NULL;
}
const CallInst *llvm::extractMallocCallFromBitCast(const Value *I) {
const BitCastInst *BCI = dyn_cast<BitCastInst>(I);
return (isBitCastOfMallocCall(BCI)) ? cast<CallInst>(BCI->getOperand(0))
: NULL;
}
static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
bool LookThroughSExt = false) {
if (!CI)
return NULL;
// The size of the malloc's result type must be known to determine array size.
const Type *T = getMallocAllocatedType(CI);
if (!T || !T->isSized() || !TD)
return NULL;
unsigned ElementSize = TD->getTypeAllocSize(T);
if (const StructType *ST = dyn_cast<StructType>(T))
ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
// If malloc call's arg can be determined to be a multiple of ElementSize,
// return the multiple. Otherwise, return NULL.
Value *MallocArg = CI->getArgOperand(0);
Value *Multiple = NULL;
if (ComputeMultiple(MallocArg, ElementSize, Multiple,
LookThroughSExt))
return Multiple;
return NULL;
}
/// isArrayMalloc - Returns the corresponding CallInst if the instruction
/// is a call to malloc whose array size can be determined and the array size
/// is not constant 1. Otherwise, return NULL.
const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
const CallInst *CI = extractMallocCall(I);
Value *ArraySize = computeArraySize(CI, TD);
if (ArraySize &&
ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
return CI;
// CI is a non-array malloc or we can't figure out that it is an array malloc.
return NULL;
}
/// getMallocType - Returns the PointerType resulting from the malloc call.
/// The PointerType depends on the number of bitcast uses of the malloc call:
/// 0: PointerType is the calls' return type.
/// 1: PointerType is the bitcast's result type.
/// >1: Unique PointerType cannot be determined, return NULL.
const PointerType *llvm::getMallocType(const CallInst *CI) {
assert(isMalloc(CI) && "getMallocType and not malloc call");
const PointerType *MallocType = NULL;
unsigned NumOfBitCastUses = 0;
// Determine if CallInst has a bitcast use.
for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
UI != E; )
if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
MallocType = cast<PointerType>(BCI->getDestTy());
NumOfBitCastUses++;
}
// Malloc call has 1 bitcast use, so type is the bitcast's destination type.
if (NumOfBitCastUses == 1)
return MallocType;
// Malloc call was not bitcast, so type is the malloc function's return type.
if (NumOfBitCastUses == 0)
return cast<PointerType>(CI->getType());
// Type could not be determined.
return NULL;
}
/// getMallocAllocatedType - Returns the Type allocated by malloc call.
/// The Type depends on the number of bitcast uses of the malloc call:
/// 0: PointerType is the malloc calls' return type.
/// 1: PointerType is the bitcast's result type.
/// >1: Unique PointerType cannot be determined, return NULL.
const Type *llvm::getMallocAllocatedType(const CallInst *CI) {
const PointerType *PT = getMallocType(CI);
return PT ? PT->getElementType() : NULL;
}
/// getMallocArraySize - Returns the array size of a malloc call. If the
/// argument passed to malloc is a multiple of the size of the malloced type,
/// then return that multiple. For non-array mallocs, the multiple is
/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
/// determined.
Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
bool LookThroughSExt) {
assert(isMalloc(CI) && "getMallocArraySize and not malloc call");
return computeArraySize(CI, TD, LookThroughSExt);
}
//===----------------------------------------------------------------------===//
// free Call Utility Functions.
//
/// isFreeCall - Returns non-null if the value is a call to the builtin free()
const CallInst *llvm::isFreeCall(const Value *I) {
const CallInst *CI = dyn_cast<CallInst>(I);
if (!CI)
return 0;
Function *Callee = CI->getCalledFunction();
if (Callee == 0 || !Callee->isDeclaration() || Callee->getName() != "free")
return 0;
// Check free prototype.
// FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
// attribute will exist.
const FunctionType *FTy = Callee->getFunctionType();
if (!FTy->getReturnType()->isVoidTy())
return 0;
if (FTy->getNumParams() != 1)
return 0;
if (FTy->param_begin()->get() != Type::getInt8PtrTy(Callee->getContext()))
return 0;
return CI;
}
<commit_msg>Add C++ global operator {new,new[],delete,delete[]}(unsigned {int,long}) to the memory builtins as equivalent to malloc/free.<commit_after>//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions identifies calls to builtin functions that allocate
// or free memory.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Target/TargetData.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// malloc Call Utility Functions.
//
/// isMalloc - Returns true if the value is either a malloc call or a
/// bitcast of the result of a malloc call.
bool llvm::isMalloc(const Value *I) {
return extractMallocCall(I) || extractMallocCallFromBitCast(I);
}
static bool isMallocCall(const CallInst *CI) {
if (!CI)
return false;
Function *Callee = CI->getCalledFunction();
if (Callee == 0 || !Callee->isDeclaration())
return false;
if (Callee->getName() != "malloc" &&
Callee->getName() != "_Znwj" && Callee->getName() != "_Znwm" &&
Callee->getName() != "_Znaj" && Callee->getName() != "_Znam")
return false;
// Check malloc prototype.
// FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
// attribute will exist.
const FunctionType *FTy = Callee->getFunctionType();
if (FTy->getNumParams() != 1)
return false;
if (IntegerType *ITy = dyn_cast<IntegerType>(FTy->param_begin()->get())) {
if (ITy->getBitWidth() != 32 && ITy->getBitWidth() != 64)
return false;
return true;
}
return false;
}
/// extractMallocCall - Returns the corresponding CallInst if the instruction
/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
/// ignore InvokeInst here.
const CallInst *llvm::extractMallocCall(const Value *I) {
const CallInst *CI = dyn_cast<CallInst>(I);
return (isMallocCall(CI)) ? CI : NULL;
}
CallInst *llvm::extractMallocCall(Value *I) {
CallInst *CI = dyn_cast<CallInst>(I);
return (isMallocCall(CI)) ? CI : NULL;
}
static bool isBitCastOfMallocCall(const BitCastInst *BCI) {
if (!BCI)
return false;
return isMallocCall(dyn_cast<CallInst>(BCI->getOperand(0)));
}
/// extractMallocCallFromBitCast - Returns the corresponding CallInst if the
/// instruction is a bitcast of the result of a malloc call.
CallInst *llvm::extractMallocCallFromBitCast(Value *I) {
BitCastInst *BCI = dyn_cast<BitCastInst>(I);
return (isBitCastOfMallocCall(BCI)) ? cast<CallInst>(BCI->getOperand(0))
: NULL;
}
const CallInst *llvm::extractMallocCallFromBitCast(const Value *I) {
const BitCastInst *BCI = dyn_cast<BitCastInst>(I);
return (isBitCastOfMallocCall(BCI)) ? cast<CallInst>(BCI->getOperand(0))
: NULL;
}
static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
bool LookThroughSExt = false) {
if (!CI)
return NULL;
// The size of the malloc's result type must be known to determine array size.
const Type *T = getMallocAllocatedType(CI);
if (!T || !T->isSized() || !TD)
return NULL;
unsigned ElementSize = TD->getTypeAllocSize(T);
if (const StructType *ST = dyn_cast<StructType>(T))
ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
// If malloc call's arg can be determined to be a multiple of ElementSize,
// return the multiple. Otherwise, return NULL.
Value *MallocArg = CI->getArgOperand(0);
Value *Multiple = NULL;
if (ComputeMultiple(MallocArg, ElementSize, Multiple,
LookThroughSExt))
return Multiple;
return NULL;
}
/// isArrayMalloc - Returns the corresponding CallInst if the instruction
/// is a call to malloc whose array size can be determined and the array size
/// is not constant 1. Otherwise, return NULL.
const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
const CallInst *CI = extractMallocCall(I);
Value *ArraySize = computeArraySize(CI, TD);
if (ArraySize &&
ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
return CI;
// CI is a non-array malloc or we can't figure out that it is an array malloc.
return NULL;
}
/// getMallocType - Returns the PointerType resulting from the malloc call.
/// The PointerType depends on the number of bitcast uses of the malloc call:
/// 0: PointerType is the calls' return type.
/// 1: PointerType is the bitcast's result type.
/// >1: Unique PointerType cannot be determined, return NULL.
const PointerType *llvm::getMallocType(const CallInst *CI) {
assert(isMalloc(CI) && "getMallocType and not malloc call");
const PointerType *MallocType = NULL;
unsigned NumOfBitCastUses = 0;
// Determine if CallInst has a bitcast use.
for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
UI != E; )
if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
MallocType = cast<PointerType>(BCI->getDestTy());
NumOfBitCastUses++;
}
// Malloc call has 1 bitcast use, so type is the bitcast's destination type.
if (NumOfBitCastUses == 1)
return MallocType;
// Malloc call was not bitcast, so type is the malloc function's return type.
if (NumOfBitCastUses == 0)
return cast<PointerType>(CI->getType());
// Type could not be determined.
return NULL;
}
/// getMallocAllocatedType - Returns the Type allocated by malloc call.
/// The Type depends on the number of bitcast uses of the malloc call:
/// 0: PointerType is the malloc calls' return type.
/// 1: PointerType is the bitcast's result type.
/// >1: Unique PointerType cannot be determined, return NULL.
const Type *llvm::getMallocAllocatedType(const CallInst *CI) {
const PointerType *PT = getMallocType(CI);
return PT ? PT->getElementType() : NULL;
}
/// getMallocArraySize - Returns the array size of a malloc call. If the
/// argument passed to malloc is a multiple of the size of the malloced type,
/// then return that multiple. For non-array mallocs, the multiple is
/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
/// determined.
Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
bool LookThroughSExt) {
assert(isMalloc(CI) && "getMallocArraySize and not malloc call");
return computeArraySize(CI, TD, LookThroughSExt);
}
//===----------------------------------------------------------------------===//
// free Call Utility Functions.
//
/// isFreeCall - Returns non-null if the value is a call to the builtin free()
const CallInst *llvm::isFreeCall(const Value *I) {
const CallInst *CI = dyn_cast<CallInst>(I);
if (!CI)
return 0;
Function *Callee = CI->getCalledFunction();
if (Callee == 0 || !Callee->isDeclaration())
return 0;
if (Callee->getName() != "free" &&
Callee->getName() != "_Zdlj" && Callee->getName() != "_Zdlm" &&
Callee->getName() != "_Zdaj" && Callee->getName() != "_Zdam")
return 0;
// Check free prototype.
// FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
// attribute will exist.
const FunctionType *FTy = Callee->getFunctionType();
if (!FTy->getReturnType()->isVoidTy())
return 0;
if (FTy->getNumParams() != 1)
return 0;
if (FTy->param_begin()->get() != Type::getInt8PtrTy(Callee->getContext()))
return 0;
return CI;
}
<|endoftext|> |
<commit_before>// Shor's algorithm
// Source: ./examples/shor.cpp
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <vector>
#include "qpp.h"
int main() {
using namespace qpp;
bigint N = 15; // number to factor
bigint a = rand(static_cast<bigint>(3), N - 1); // random co-prime with N
while (gcd(a, N) != 1) {
a = rand(static_cast<bigint>(3), N - 1);
}
// qubits required for half of the circuit, in total we need 2n qubits
// if you know the order 'r' of 'a', then you can take the smallest 'n' s.t.
// 2^n >= 2 * r^2, i.e. n = ceil(log2(2 * r^2))
idx n = static_cast<idx>(std::ceil(2 * std::log2(N)));
idx D = static_cast<idx>(std::llround(std::pow(2, n))); // dimension 2^n
std::cout << ">> Factoring N = " << N << " with coprime a = " << a << '\n';
std::cout << ">> n = " << n << ", D = 2^n = " << D << " and 2^(2n) = ";
std::cout << D * D << '\n';
// vector with labels of the first half of the qubits
std::vector<idx> first_subsys(n);
std::iota(std::begin(first_subsys), std::end(first_subsys), 0);
// vector with labels of the second half of the qubits
std::vector<idx> second_subsys(n);
std::iota(std::begin(second_subsys), std::end(second_subsys), n);
// QUANTUM STAGE
// prepare the initial state |0>^\otimes n \otimes |0...01>
ket psi = kron(st.zero(2 * n - 1), 1_ket);
// apply Hadamards H^\otimes n on first half of the qubits
for (idx i = 0; i < n; ++i) {
psi = apply(psi, gt.H, {i});
}
// perform the modular exponentiation as a sequence of
// modular multiplications
for (idx i = 0; i < n; ++i) {
// compute 2^(n-i-1) mod N
idx j = static_cast<idx>(std::llround(std::pow(2, n - i - 1)));
// compute the a^(2^(n-i-1)) mod N
idx aj = modpow(a, j, N);
// apply the controlled modular multiplication
psi = applyCTRL(psi, gt.MODMUL(aj, N, n), {i}, second_subsys);
}
// apply inverse QFT on first half of the qubits
psi = applyINVQFT(psi, first_subsys);
// END QUANTUM STAGE
// FIRST MEASUREMENT STAGE
auto measured1 = measure_seq(psi, first_subsys); // measure first n qubits
auto list_results1 = std::get<0>(measured1); // measurement results
auto prob1 = std::get<1>(measured1); // probability of the result
idx n1 = multiidx2n(list_results1, std::vector<idx>(n, 2)); // binary to int
double x1 = static_cast<double>(n1) / D;
std::cout << ">> First measurement: " << disp(list_results1, " ") << " ";
std::cout << "i.e. j = " << n1 << " with probability " << prob1;
std::cout << '\n';
bool failed = true;
idx r1, c1;
for (auto&& elem : convergents(x1, 10)) {
std::tie(c1, r1) = elem;
double c1r1 = static_cast<double>(c1) / r1;
if (abs(x1 - c1r1) < 1. / std::pow(2, (n - 1) / 2.)) {
failed = false;
break;
}
}
if (failed) {
std::cout << ">> Factoring failed at stage 1, please try again!\n";
std::exit(EXIT_FAILURE);
}
// END FIRST MEASUREMENT STAGE
// SECOND MEASUREMENT STAGE
auto measured2 = measure_seq(psi, first_subsys); // measure first n qubits
auto list_results2 = std::get<0>(measured2); // measurement results
auto prob2 = std::get<1>(measured2); // probability of the result
idx n2 = multiidx2n(list_results2, std::vector<idx>(n, 2)); // binary to int
double x2 = static_cast<double>(n2) / D;
std::cout << ">> Second measurement: " << disp(list_results2, " ") << " ";
std::cout << "i.e. j = " << n2 << " with probability " << prob2;
std::cout << '\n';
failed = true;
idx r2, c2;
for (auto&& elem : convergents(x2, 10)) {
std::tie(c2, r2) = elem;
double c2r2 = static_cast<double>(c2) / r2;
if (abs(x2 - c2r2) < 1. / std::pow(2, (n - 1) / 2.)) {
failed = false;
break;
}
}
if (failed) {
std::cout << ">> Factoring failed at stage 2, please try again!\n";
std::exit(EXIT_FAILURE);
}
// END SECOND MEASUREMENT STAGE
// THIRD POST-PROCESSING STAGE
idx r = lcm(r1, r2); // candidate order of a mod N
std::cout << ">> r = " << r << '\n';
if (r % 2 == 0 && modpow(a, r / 2, N) != static_cast<bigint>(N - 1)) {
std::cout << ">> Possible factors: ";
std::cout << gcd(modpow(a, r / 2, N) - 1, N) << " ";
std::cout << gcd(modpow(a, r / 2, N) + 1, N) << '\n';
} else {
std::cout << ">> Factoring failed at stage 3, please try again!\n";
std::exit(EXIT_FAILURE);
}
// END THIRD POST-PROCESSING STAGE
}
<commit_msg>commit<commit_after>// Shor's algorithm
// Source: ./examples/shor.cpp
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <tuple>
#include <vector>
#include "qpp.h"
int main() {
using namespace qpp;
bigint N = 15; // number to factor
bigint a = rand(static_cast<bigint>(3), N - 1); // random co-prime with N
while (gcd(a, N) != 1) {
a = rand(static_cast<bigint>(3), N - 1);
}
// qubits required for half of the circuit, in total we need 2n qubits
// if you know the order 'r' of 'a', then you can take the smallest 'n' s.t.
// 2^n >= 2 * r^2, i.e. n = ceil(log2(2 * r^2))
idx n = static_cast<idx>(std::ceil(2 * std::log2(N)));
idx D = static_cast<idx>(std::llround(std::pow(2, n))); // dimension 2^n
std::cout << ">> Factoring N = " << N << " with coprime a = " << a << '\n';
std::cout << ">> n = " << n << ", D = 2^n = " << D << " and 2^(2n) = ";
std::cout << D * D << '\n';
// vector with labels of the first half of the qubits
std::vector<idx> first_subsys(n);
std::iota(std::begin(first_subsys), std::end(first_subsys), 0);
// vector with labels of the second half of the qubits
std::vector<idx> second_subsys(n);
std::iota(std::begin(second_subsys), std::end(second_subsys), n);
// QUANTUM STAGE
// prepare the initial state |0>^\otimes n \otimes |0...01>
ket psi = kron(st.zero(2 * n - 1), 1_ket);
// apply Hadamards H^\otimes n on first half of the qubits
for (idx i = 0; i < n; ++i) {
psi = apply(psi, gt.H, {i});
}
// perform the modular exponentiation as a sequence of
// modular multiplications
for (idx i = 0; i < n; ++i) {
// compute 2^(n-i-1) mod N
idx j = static_cast<idx>(std::llround(std::pow(2, n - i - 1)));
// compute the a^(2^(n-i-1)) mod N
idx aj = modpow(a, j, N);
// apply the controlled modular multiplication
psi = applyCTRL(psi, gt.MODMUL(aj, N, n), {i}, second_subsys);
}
// apply inverse QFT on first half of the qubits
psi = applyINVQFT(psi, first_subsys);
// END QUANTUM STAGE
// FIRST MEASUREMENT STAGE
auto measured1 = measure_seq(psi, first_subsys); // measure first n qubits
auto list_results1 = std::get<0>(measured1); // measurement results
auto prob1 = std::get<1>(measured1); // probability of the result
idx n1 = multiidx2n(list_results1, std::vector<idx>(n, 2)); // binary to int
double x1 = static_cast<double>(n1) / D;
std::cout << ">> First measurement: " << disp(list_results1, " ") << " ";
std::cout << "i.e. j = " << n1 << " with probability " << prob1;
std::cout << '\n';
bool failed = true;
idx r1, c1;
for (auto&& elem : convergents(x1, 10)) {
std::tie(c1, r1) = elem;
double c1r1 = static_cast<double>(c1) / r1;
if (abs(x1 - c1r1) < 1. / std::pow(2, (n - 1) / 2.)) {
failed = false;
break;
}
}
if (failed) {
std::cout << ">> Factoring failed at stage 1, please try again!\n";
std::exit(EXIT_FAILURE);
}
// END FIRST MEASUREMENT STAGE
// SECOND MEASUREMENT STAGE
auto measured2 = measure_seq(psi, first_subsys); // measure first n qubits
auto list_results2 = std::get<0>(measured2); // measurement results
auto prob2 = std::get<1>(measured2); // probability of the result
idx n2 = multiidx2n(list_results2, std::vector<idx>(n, 2)); // binary to int
double x2 = static_cast<double>(n2) / D;
std::cout << ">> Second measurement: " << disp(list_results2, " ") << " ";
std::cout << "i.e. j = " << n2 << " with probability " << prob2;
std::cout << '\n';
failed = true;
idx r2, c2;
for (auto&& elem : convergents(x2, 10)) {
std::tie(c2, r2) = elem;
double c2r2 = static_cast<double>(c2) / r2;
if (abs(x2 - c2r2) < 1. / std::pow(2, (n - 1) / 2.)) {
failed = false;
break;
}
}
if (failed) {
std::cout << ">> Factoring failed at stage 2, please try again!\n";
std::exit(EXIT_FAILURE);
}
// END SECOND MEASUREMENT STAGE
// THIRD POST-PROCESSING STAGE
idx r = lcm(r1, r2); // candidate order of a mod N
std::cout << ">> r = " << r << '\n';
if (r % 2 == 0 && modpow(a, r / 2, N) != static_cast<bigint>(N - 1)) {
std::cout << ">> Possible factors: ";
std::cout << gcd(modpow(a, r / 2, N) - 1, N) << " ";
std::cout << gcd(modpow(a, r / 2, N) + 1, N) << '\n';
} else {
std::cout << ">> Factoring failed at stage 3, please try again!\n";
std::exit(EXIT_FAILURE);
}
// END THIRD POST-PROCESSING STAGE
}
<|endoftext|> |
<commit_before>///
/// A simple clang plugin which will translate the given C file into Zomp
/// definitions
///
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
static std::string errorType(const char* msg)
{
return std::string("error_t(\"") + msg + "\")";
}
static std::string zompTypeName(const Type* t)
{
if( t == 0 )
{
return "type_was_null";
}
if( const BuiltinType* bt = dyn_cast<BuiltinType>(t) )
{
switch(bt->getKind())
{
case BuiltinType::Void: return "void";
case BuiltinType::UShort: return "c_ushort";
case BuiltinType::UInt: return "c_uint";
case BuiltinType::ULong: return "c_ulong";
case BuiltinType::ULongLong: return "c_ulong_long";
case BuiltinType::UInt128: return "u128";
case BuiltinType::Short: return "c_short";
case BuiltinType::Int: return "c_int";
case BuiltinType::Long: return "c_long";
case BuiltinType::LongLong: return "c_long_long";
case BuiltinType::Int128: return "s128";
case BuiltinType::Float: return "float";
case BuiltinType::Double: return "double";
case BuiltinType::LongDouble: return "c_long_double";
case BuiltinType::Char_U: return "c_implicit_uchar";
case BuiltinType::Char_S: return "c_implicit_schar";
case BuiltinType::UChar: return "c_uchar";
case BuiltinType::SChar: return "c_schar";
case BuiltinType::WChar_U:
case BuiltinType::Char16:
case BuiltinType::Char32:
case BuiltinType::WChar_S:
case BuiltinType::NullPtr:
case BuiltinType::Dependent:
case BuiltinType::Overload:
case BuiltinType::ObjCId:
case BuiltinType::ObjCClass:
case BuiltinType::ObjCSel:
default:
return "UnsupportedBuiltinType";
}
}
else if( const PointerType* pt = dyn_cast<PointerType>(t) )
{
QualType base_type = pt->getPointeeType();
return zompTypeName(base_type.getTypePtrOrNull()) + "*";
}
else if( const ArrayType* at = dyn_cast<ArrayType>(t) )
{
assert( at );
return errorType( "bindgen does not support array types, yet" );
}
else if( const FunctionType* ft = dyn_cast<FunctionType>(t) )
{
assert( ft );
return errorType("bindgen does not support function types, yet" );
}
else if( const TypedefType* tt = dyn_cast<TypedefType>(t) )
{
return tt->getDecl()->getName();
// return zompTypeName(
// tt->getDecl()->getCanonicalDecl()->getUnderlyingType().getTypePtrOrNull() );
}
else if( const EnumType* et = dyn_cast<EnumType>(t) )
{
return et->getDecl()->getNameAsString();
}
else if( const RecordType* rt = dyn_cast<RecordType>(t) )
{
return rt->getDecl()->getNameAsString();
}
else
{
return errorType("type not understood by bindgen");
}
}
static std::string zompTypeName( const QualType& qual_type )
{
std::string base_name = zompTypeName( qual_type.getTypePtrOrNull() );
std::string name = base_name;
if( qual_type.isConstQualified() )
{
name = "/* const */" + name;
}
if( qual_type.isRestrictQualified() )
{
name = "/* restrict */" + name;
}
if( qual_type.isVolatileQualified() )
{
name = "/* volatile */" + name;
}
return name;
}
/** Visitor which will handle every top level declaration */
class GenBindingsConsumer : public ASTConsumer
{
ASTContext* m_context;
SourceManager* m_src_manager;
FileID m_main_file_id;
public:
GenBindingsConsumer() : m_context(0), m_src_manager(0)
{
}
virtual void Initialize(ASTContext &context)
{
m_context = &context;
m_src_manager = &context.getSourceManager();
m_main_file_id = m_src_manager->getMainFileID();
const char* main_file_name = m_src_manager->getFileEntryForID( m_main_file_id )->getName();
llvm::outs() << "///\n";
llvm::outs() << "/// Zomp bindings for " << main_file_name << "\n";
llvm::outs() << "///\n";
llvm::outs() << "\n";
}
virtual void HandleTopLevelDecl(DeclGroupRef DG)
{
for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i)
{
const Decl *D = *i;
const TranslationUnitDecl* tu = D->getTranslationUnitDecl();
if( !tu ) {
continue;
}
const SourceLocation& loc = D->getLocation();
if( m_src_manager->getFileID(loc) != m_main_file_id)
{
continue;
}
handleAs<VarDecl>(D) ||
handleAs<FunctionDecl>(D) ||
handleAs<TypedefDecl>(D) ||
handleAs<RecordDecl>(D) ||
handleAs<EnumDecl>(D) ||
handleUnknown(D);
}
}
private:
enum HandlingResult { Handled, CouldNotHandle };
template<typename T>
bool handleAs(const Decl* D)
{
const T* typed_decl = dyn_cast<T>(D);
if(typed_decl)
{
const bool result = handle(typed_decl) == Handled;
// llvm::outs() << "\n";
return result;
}
else
{
return false;
}
}
HandlingResult handle(const FunctionDecl* func_decl)
{
bool ignore = func_decl->isCXXClassMember()
|| func_decl->isCXXInstanceMember()
|| func_decl->isVariadic()
|| func_decl->isMain();
if(ignore) {
return CouldNotHandle;
}
llvm::outs() << "nativeFn ";
llvm::outs() << zompTypeName( func_decl->getResultType() ) << " ";
llvm::outs() << func_decl->getNameAsString() << "(";
bool first_param = true;
for( FunctionDecl::param_const_iterator param_i = func_decl->param_begin(),
pend = func_decl->param_end( );
param_i != pend;
++param_i, first_param = false )
{
ParmVarDecl* param = *param_i;
if( !first_param ) {
llvm::outs() << ", ";
}
QualType typesrc = param->getTypeSourceInfo()->getType();
const Type* type = typesrc.getTypePtrOrNull();
llvm::outs() << zompTypeName(type);
if( param->getIdentifier() )
{
llvm::outs() << " "
<< param->getNameAsString();
}
if ( param->hasDefaultArg() )
{
llvm::outs() << " /* = ... */";
}
}
llvm::outs() << ")\n";
return Handled;
}
HandlingResult handle(const VarDecl* var_decl)
{
llvm::outs() << "nativeVar "
<< zompTypeName( var_decl->getTypeSourceInfo()->getType() )
<< " "
<< var_decl->getNameAsString()
<< "\n";
return Handled;
}
bool handle(const TypedefDecl* type_decl)
{
QualType typesrc = type_decl->getUnderlyingType();
const Type* type = typesrc.getTypePtrOrNull();
std::string zomp_name = zompTypeName(type);
bool handled = false;
if( type )
{
if( zomp_name.empty() )
{
if( const RecordType* record_type = dyn_cast<RecordType>(type) )
{
handled = handle( record_type->getDecl(), type_decl->getName() );
}
else if( const EnumType* enum_type = dyn_cast<EnumType>(type) )
{
handled = handle( enum_type->getDecl(), type_decl->getName() );
}
}
else
{
llvm::outs()
<< "nativeTypedef "
<< type_decl->getName()
<< " " << zomp_name << "\n";
handled = true;
}
}
if( !handled )
{
llvm::outs()
<< "// ignoring typedef " << type_decl->getName() << "\n";
}
return Handled;
}
bool handle(const RecordDecl* record_decl, llvm::StringRef name = "" )
{
if( name == "" )
{
name = record_decl->getName();
}
if( record_decl->isAnonymousStructOrUnion() ||
name.empty() )
{
llvm::outs() << "// ignoring anonymous struct\n";
return Handled;
}
if( record_decl->isDefinition() )
{
llvm::outs() << "nativeStruct " << name << ":\n";
typedef RecordDecl::field_iterator FieldIter;
for( FieldIter fi = record_decl->field_begin(), fi_end = record_decl->field_end();
fi != fi_end;
++fi )
{
const FieldDecl& field = **fi;
if( field.isBitField() )
{
llvm::outs() << " // ignored bitfield, not supported\n";
}
else
{
llvm::outs()
<< " "
<< zompTypeName( field.getType() )
<< " "
<< field.getName()
<< "\n";
}
}
llvm::outs() << "end\n";
}
else
{
llvm::outs() << "nativeStruct " << name << "\n";
}
return Handled;
}
bool handle(const EnumDecl* enum_decl, llvm::StringRef name = "")
{
if( name == "" )
{
name = enum_decl->getName();
}
if( name.empty() )
{
llvm::outs() << "// ignoring name-less enum\n";
}
else if( enum_decl->isComplete() )
{
llvm::outs()
<< "nativeEnum "
<< name << " "
<< zompTypeName( enum_decl->getPromotionType() )
<< ":\n";
typedef EnumDecl::enumerator_iterator EnumIter;
for( EnumIter variant = enum_decl->enumerator_begin(), vend = enum_decl->enumerator_end();
variant != vend;
++variant )
{
EnumConstantDecl* ecd = *variant;
llvm::outs()
<< " "
<< ecd->getName() << " "
<< ecd->getInitVal()
<< "\n";
}
llvm::outs() << "end\n";
}
else
{
llvm::outs()
<< "nativeEnum "
<< name
<< "\n";
}
return Handled;
}
bool handleUnknown(const Decl* D)
{
if(const NamedDecl* n = dyn_cast<NamedDecl>(D))
{
llvm::outs() << "// ignored " << n->getNameAsString() << "\n";
}
else
{
llvm::outs() << "// ignored nameless declaration\n";
}
return Handled;
}
};
/** The plugin class. Will instantiate GenBindingsConsumer and run it */
class GenBindingsAction : public PluginASTAction
{
protected:
ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef)
{
return new GenBindingsConsumer();
}
bool ParseArgs(
const CompilerInstance &CI,
const std::vector<std::string>& args )
{
for (unsigned i = 0, e = args.size(); i != e; ++i) {
llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
// Example error handling.
if (args[i] == "-an-error") {
Diagnostic &D = CI.getDiagnostics();
unsigned DiagID = D.getCustomDiagID(
Diagnostic::Error, "invalid argument '" + args[i] + "'");
D.Report(DiagID);
return false;
}
}
if (args.size() && args[0] == "help")
PrintHelp(llvm::errs());
return true;
}
void PrintHelp(llvm::raw_ostream& ros)
{
ros << "Translates declarations of a C file into Zomp declarations.\n"
"This makes it easy to use C libaries from Zomp.";
}
};
} // anonymous namespace
static FrontendPluginRegistry::Add<GenBindingsAction> X("gen-zomp-bindings", "Generate Zomp bindings");
<commit_msg>Fixing error handling in bindgen<commit_after>///
/// A simple clang plugin which will translate the given C file into Zomp
/// definitions
///
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
static std::string errorType(const char* msg)
{
return std::string("error_t(\"") + msg + "\")";
}
static std::string zompTypeName(const Type* t)
{
if( t == 0 )
{
return "type_was_null";
}
if( const BuiltinType* bt = dyn_cast<BuiltinType>(t) )
{
switch(bt->getKind())
{
case BuiltinType::Void: return "void";
case BuiltinType::UShort: return "c_ushort";
case BuiltinType::UInt: return "c_uint";
case BuiltinType::ULong: return "c_ulong";
case BuiltinType::ULongLong: return "c_ulong_long";
case BuiltinType::UInt128: return "u128";
case BuiltinType::Short: return "c_short";
case BuiltinType::Int: return "c_int";
case BuiltinType::Long: return "c_long";
case BuiltinType::LongLong: return "c_long_long";
case BuiltinType::Int128: return "s128";
case BuiltinType::Float: return "float";
case BuiltinType::Double: return "double";
case BuiltinType::LongDouble: return "c_long_double";
case BuiltinType::Char_U: return "c_implicit_uchar";
case BuiltinType::Char_S: return "c_implicit_schar";
case BuiltinType::UChar: return "c_uchar";
case BuiltinType::SChar: return "c_schar";
case BuiltinType::WChar_U:
case BuiltinType::Char16:
case BuiltinType::Char32:
case BuiltinType::WChar_S:
case BuiltinType::NullPtr:
case BuiltinType::Dependent:
case BuiltinType::Overload:
case BuiltinType::ObjCId:
case BuiltinType::ObjCClass:
case BuiltinType::ObjCSel:
default:
return "UnsupportedBuiltinType";
}
}
else if( const PointerType* pt = dyn_cast<PointerType>(t) )
{
QualType base_type = pt->getPointeeType();
return zompTypeName(base_type.getTypePtrOrNull()) + "*";
}
else if( const ArrayType* at = dyn_cast<ArrayType>(t) )
{
assert( at );
return errorType( "bindgen does not support array types, yet" );
}
else if( const FunctionType* ft = dyn_cast<FunctionType>(t) )
{
assert( ft );
return errorType("bindgen does not support function types, yet" );
}
else if( const TypedefType* tt = dyn_cast<TypedefType>(t) )
{
return tt->getDecl()->getName();
// return zompTypeName(
// tt->getDecl()->getCanonicalDecl()->getUnderlyingType().getTypePtrOrNull() );
}
else if( const EnumType* et = dyn_cast<EnumType>(t) )
{
return et->getDecl()->getNameAsString();
}
else if( const RecordType* rt = dyn_cast<RecordType>(t) )
{
return rt->getDecl()->getNameAsString();
}
else
{
return errorType("type not understood by bindgen");
}
}
static std::string zompTypeName( const QualType& qual_type )
{
std::string base_name = zompTypeName( qual_type.getTypePtrOrNull() );
std::string name = base_name;
if( qual_type.isConstQualified() )
{
name = "/* const */" + name;
}
if( qual_type.isRestrictQualified() )
{
name = "/* restrict */" + name;
}
if( qual_type.isVolatileQualified() )
{
name = "/* volatile */" + name;
}
return name;
}
/** Visitor which will handle every top level declaration */
class GenBindingsConsumer : public ASTConsumer
{
ASTContext* m_context;
SourceManager* m_src_manager;
FileID m_main_file_id;
public:
GenBindingsConsumer() : m_context(0), m_src_manager(0)
{
}
virtual void Initialize(ASTContext &context)
{
m_context = &context;
m_src_manager = &context.getSourceManager();
m_main_file_id = m_src_manager->getMainFileID();
const char* main_file_name = m_src_manager->getFileEntryForID( m_main_file_id )->getName();
llvm::outs() << "///\n";
llvm::outs() << "/// Zomp bindings for " << main_file_name << "\n";
llvm::outs() << "///\n";
llvm::outs() << "\n";
}
virtual void HandleTopLevelDecl(DeclGroupRef DG)
{
for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i)
{
const Decl *D = *i;
const TranslationUnitDecl* tu = D->getTranslationUnitDecl();
if( !tu ) {
continue;
}
const SourceLocation& loc = D->getLocation();
if( m_src_manager->getFileID(loc) != m_main_file_id)
{
continue;
}
handleAs<VarDecl>(D) ||
handleAs<FunctionDecl>(D) ||
handleAs<TypedefDecl>(D) ||
handleAs<RecordDecl>(D) ||
handleAs<EnumDecl>(D) ||
handleUnknown(D);
}
}
private:
enum HandlingResult { Handled, CouldNotHandle };
template<typename T>
bool handleAs(const Decl* D)
{
const T* typed_decl = dyn_cast<T>(D);
if(typed_decl)
{
const bool result = handle(typed_decl) == Handled;
// llvm::outs() << "\n";
return result;
}
else
{
return false;
}
}
HandlingResult handle(const FunctionDecl* func_decl)
{
bool ignore = func_decl->isCXXClassMember()
|| func_decl->isCXXInstanceMember()
|| func_decl->isVariadic()
|| func_decl->isMain();
if(ignore) {
return CouldNotHandle;
}
llvm::outs() << "nativeFn ";
llvm::outs() << zompTypeName( func_decl->getResultType() ) << " ";
llvm::outs() << func_decl->getNameAsString() << "(";
bool first_param = true;
for( FunctionDecl::param_const_iterator param_i = func_decl->param_begin(),
pend = func_decl->param_end( );
param_i != pend;
++param_i, first_param = false )
{
ParmVarDecl* param = *param_i;
if( !first_param ) {
llvm::outs() << ", ";
}
QualType typesrc = param->getTypeSourceInfo()->getType();
const Type* type = typesrc.getTypePtrOrNull();
llvm::outs() << zompTypeName(type);
if( param->getIdentifier() )
{
llvm::outs() << " "
<< param->getNameAsString();
}
if ( param->hasDefaultArg() )
{
llvm::outs() << " /* = ... */";
}
}
llvm::outs() << ")\n";
return Handled;
}
HandlingResult handle(const VarDecl* var_decl)
{
llvm::outs() << "nativeVar "
<< zompTypeName( var_decl->getTypeSourceInfo()->getType() )
<< " "
<< var_decl->getNameAsString()
<< "\n";
return Handled;
}
HandlingResult handle(const TypedefDecl* type_decl)
{
QualType typesrc = type_decl->getUnderlyingType();
const Type* type = typesrc.getTypePtrOrNull();
std::string zomp_name = zompTypeName(type);
bool handled = false;
if( type )
{
if( zomp_name.empty() )
{
if( const RecordType* record_type = dyn_cast<RecordType>(type) )
{
handled = handle( record_type->getDecl(), type_decl->getName() ) == Handled;
}
else if( const EnumType* enum_type = dyn_cast<EnumType>(type) )
{
handled = handle( enum_type->getDecl(), type_decl->getName() ) == Handled;
}
}
else
{
llvm::outs()
<< "nativeTypedef "
<< type_decl->getName()
<< " " << zomp_name << "\n";
handled = true;
}
}
if( !handled )
{
llvm::outs()
<< "// ignoring typedef " << type_decl->getName() << "\n";
}
return Handled;
}
HandlingResult handle(const RecordDecl* record_decl, llvm::StringRef name = "" )
{
if( name == "" )
{
name = record_decl->getName();
}
if( record_decl->isAnonymousStructOrUnion() ||
name.empty() )
{
llvm::outs() << "// ignoring anonymous struct\n";
}
else if( record_decl->isDefinition() )
{
llvm::outs() << "nativeStruct " << name << ":\n";
typedef RecordDecl::field_iterator FieldIter;
for( FieldIter fi = record_decl->field_begin(), fi_end = record_decl->field_end();
fi != fi_end;
++fi )
{
const FieldDecl& field = **fi;
if( field.isBitField() )
{
llvm::outs() << " // ignored bitfield, not supported\n";
}
else
{
llvm::outs()
<< " "
<< zompTypeName( field.getType() )
<< " "
<< field.getName()
<< "\n";
}
}
llvm::outs() << "end\n";
}
else
{
llvm::outs() << "nativeStruct " << name << "\n";
}
return Handled;
}
HandlingResult handle(const EnumDecl* enum_decl, llvm::StringRef name = "")
{
if( name == "" )
{
name = enum_decl->getName();
}
if( name.empty() )
{
llvm::outs() << "// ignoring name-less enum\n";
}
else if( enum_decl->isComplete() )
{
llvm::outs()
<< "nativeEnum "
<< name << " "
<< zompTypeName( enum_decl->getPromotionType() )
<< ":\n";
typedef EnumDecl::enumerator_iterator EnumIter;
for( EnumIter variant = enum_decl->enumerator_begin(), vend = enum_decl->enumerator_end();
variant != vend;
++variant )
{
EnumConstantDecl* ecd = *variant;
llvm::outs()
<< " "
<< ecd->getName() << " "
<< ecd->getInitVal()
<< "\n";
}
llvm::outs() << "end\n";
}
else
{
llvm::outs()
<< "nativeEnum "
<< name
<< "\n";
}
return Handled;
}
bool handleUnknown(const Decl* D)
{
if(const NamedDecl* n = dyn_cast<NamedDecl>(D))
{
llvm::outs() << "// ignored " << n->getNameAsString() << "\n";
}
else
{
llvm::outs() << "// ignored nameless declaration\n";
}
return Handled;
}
};
/** The plugin class. Will instantiate GenBindingsConsumer and run it */
class GenBindingsAction : public PluginASTAction
{
protected:
ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef)
{
return new GenBindingsConsumer();
}
bool ParseArgs(
const CompilerInstance &CI,
const std::vector<std::string>& args )
{
for (unsigned i = 0, e = args.size(); i != e; ++i) {
llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
// Example error handling.
if (args[i] == "-an-error") {
Diagnostic &D = CI.getDiagnostics();
unsigned DiagID = D.getCustomDiagID(
Diagnostic::Error, "invalid argument '" + args[i] + "'");
D.Report(DiagID);
return false;
}
}
if (args.size() && args[0] == "help")
PrintHelp(llvm::errs());
return true;
}
void PrintHelp(llvm::raw_ostream& ros)
{
ros << "Translates declarations of a C file into Zomp declarations.\n"
"This makes it easy to use C libaries from Zomp.";
}
};
} // anonymous namespace
static FrontendPluginRegistry::Add<GenBindingsAction> X("gen-zomp-bindings", "Generate Zomp bindings");
<|endoftext|> |
<commit_before>#include "app.h"
#include "gphotogrid.h"
#include "gputil.h"
#include <iostream>
#include <sstream>
#include <wx/timer.h>
#include <wx/mstream.h>
MainFrame::MainFrame(const wxString& title, App& app) :
wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(1024, 768)), app(app) {
create_menus();
create_panels();
#ifdef LOOP_TIMER
//timer = new RenderTimer(*this);
//timer->start();
#else
frames = 0;
lasttime = Clock::now();
enableRender(true);
Bind(wxEVT_IDLE, &MainFrame::onIdle, this);
#endif
}
#ifdef LOOP_TIMER
RenderTimer::RenderTimer(MainFrame& root) : root(root) {
}
void RenderTimer::Notify() {
std::cout << "NOTIF" << std::endl;
root.refresh();
}
void RenderTimer::start() {
Start(10);
}
#else
void MainFrame::onIdle(wxIdleEvent& ev) {
//std::cout<<"idle"<<std::endl;
refresh();
ev.RequestMore();
}
#endif
// read params from camera 0 and set the same for others
void MainFrame::readCameraParams() {
bool fol = timeline->getFollow();
timeline->Destroy();
timeline = new Timeline(this, app.numcams(), fol);
GetSizer()->Add(timeline, 1, wxEXPAND);
Layout();
if (app.numcams() > 0) {
// assume that all cameras are the same, use only zeroth
auto aperture = app.cams[0].config()["aperture"].get<gp::Aperture>();
for (size_t i = 1; i < app.numcams(); i++)
setRadioConfig<gp::Aperture>(i, aperture.index());
options->setSelections(0, aperture.choices(), aperture.index());
auto shutter = app.cams[0].config()["shutterspeed"].get<gp::ShutterSpeed>();
for (size_t i = 1; i < app.numcams(); i++)
setRadioConfig<gp::ShutterSpeed>(i, shutter.index());
options->setSelections(1, shutter.choices(), shutter.index());
auto iso = app.cams[0].config()["iso"].get<gp::Iso>();
for (size_t i = 1; i < app.numcams(); i++)
setRadioConfig<gp::Iso>(i, iso.index());
options->setSelections(2, iso.choices(), iso.index());
}
Refresh();
}
void MainFrame::create_panels() {
auto horsizer = new wxBoxSizer(wxHORIZONTAL);
// opts lots thinner than image panel
horsizer->Add(options = new OptionsPanel(this), 1, wxEXPAND);
horsizer->Add(create_imagegrid(), 4, wxEXPAND);
auto versizer = new wxBoxSizer(wxVERTICAL);
versizer->Add(horsizer, 4, wxEXPAND);
versizer->Add(timeline = new Timeline(this, app.numcams()));
SetSizer(versizer);
readCameraParams();
}
wxSizer* MainFrame::create_imagegrid() {
int rows = 3, cols = 3;
auto sizer = new wxGridSizer(cols, wxSize(2, 2));
for (int i = 0; i < rows * cols; i++) {
auto panel = new ImagePanel(this);
images.push_back(panel);
sizer->Add(panel, 1, wxEXPAND);
}
return sizer;
}
void MainFrame::create_menus() {
wxMenu *menuFile = new wxMenu();
menuFile->AppendSeparator();
menuFile->Append(1, "foo");
menuFile->Append(2, "bar");
menuFile->Append(wxID_EXIT);
wxMenuBar *menuBar = new wxMenuBar();
menuBar->Append(menuFile, "&File");
SetMenuBar(menuBar);
CreateStatusBar();
SetStatusText("Hello world");
Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::onMenu, this, 1);
Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::onExit, this, wxID_EXIT);
}
void MainFrame::slider(int id, int value) {
std::cout << "slider " << id << " to " << value << std::endl;
if (id < 0 || id > 2)
throw std::out_of_range("slider index bug");
std::vector<std::thread> setters(app.numcams());
for (size_t cam = 0; cam < app.numcams(); cam++) {
setters[cam] = std::thread([=]() {
switch (id) {
case 0:
setRadioConfig<gp::Aperture>(cam, value);
break;
case 1:
setRadioConfig<gp::ShutterSpeed>(cam, value);
break;
case 2:
setRadioConfig<gp::Iso>(cam, value);
break;
}
});
}
for (auto& thr: setters)
thr.join();
}
template <class Obj>
void MainFrame::setRadioConfig(int cam, int value) {
auto cfg = app.cams[cam].config()[Obj::gpname];
auto radio = cfg.template get<Obj>();
if (value >= 0 && value < radio.size()) {
radio.set(value);
cfg.set(radio);
std::cout << "cam " << cam << " new " << Obj::gpname << " " << radio.text() << std::endl;
}
}
void MainFrame::reloadGphoto() {
assert(!app.previewfeed.enabled());
app.reloadGphoto();
for (auto& impanel: images) {
impanel->clearImage();
}
readCameraParams();
}
void MainFrame::refresh() {
updatePhotos();
for (auto im: images) {
im->Refresh();
}
framecalc();
}
float MainFrame::time_since(MainFrame::Clock::time_point now, MainFrame::Clock::time_point before) const {
typedef std::chrono::duration<float> fsec;
fsec fs = now - before;
return fs.count();
}
void MainFrame::framecalc() {
auto clock = Clock::now();
float secs = time_since(clock, lasttime);
frames++;
if (secs > 5.0f) {
std::cout << frames << " in " << secs << " secs = " << (frames / secs) << " fps" << std::endl;
frames = 0;
lasttime = clock;
}
}
void MainFrame::updatePhotos() {
// if no sources, no update needed
if (app.numcams() == 0 || !app.previewfeed.enabled())
return;
// all have the same size
auto newsize = images[0]->GetSize();
for (size_t i = 0; i < std::min(app.numcams(), images.size()); i++) {
PreviewFeed::TimedJpegBuffer capture;
// test if there is anything
if (!app.previewfeed.getQueue(i).try_pop(capture))
continue;
// log timestamps, and slurp further ones, until got the latest
do {
timeline->insert(i, time_since(capture.second, renderinittime));
numpics[i]++;
} while (app.previewfeed.getQueue(i).try_pop(capture));
wxMemoryInputStream stream(&capture.first[0], capture.first.size());
wxImage im(stream, wxBITMAP_TYPE_JPEG);
// XXX: aspect ratio correction?
im.Rescale(newsize.GetWidth(), newsize.GetHeight(), wxIMAGE_QUALITY_NEAREST);
images[i]->setImage(im, i < app.camNames.size() ? app.camNames[i] : "");
}
std::stringstream ss;
ss << app.numcams() << " cameras; frames per cam:";
for (size_t i = 0; i < numpics.size(); i++) {
ss << " " << i << ":" << numpics[i];
}
SetStatusText(ss.str());
}
void MainFrame::enableRender(bool enable) {
if (enable) {
renderinittime = Clock::now();
numpics = std::vector<int>(app.numcams());
timeline->clear();
app.previewfeed.enable();
} else {
app.previewfeed.disable();
}
}
void MainFrame::syncGrabbers(bool sync) {
app.previewfeed.setsync(sync);
}
void MainFrame::timelineFollow(bool follow) {
timeline->followInsertions(follow);
}
void MainFrame::onMenu(wxCommandEvent&) {
std::cout << "menu" << std::endl;
}
void MainFrame::onExit(wxCommandEvent&) {
Close(true);
}
<commit_msg>gpgrid: reorient images if the setting is given<commit_after>#include "app.h"
#include "gphotogrid.h"
#include "gputil.h"
#include <iostream>
#include <sstream>
#include <wx/timer.h>
#include <wx/mstream.h>
MainFrame::MainFrame(const wxString& title, App& app) :
wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(1024, 768)), app(app) {
create_menus();
create_panels();
#ifdef LOOP_TIMER
//timer = new RenderTimer(*this);
//timer->start();
#else
frames = 0;
lasttime = Clock::now();
enableRender(true);
Bind(wxEVT_IDLE, &MainFrame::onIdle, this);
#endif
}
#ifdef LOOP_TIMER
RenderTimer::RenderTimer(MainFrame& root) : root(root) {
}
void RenderTimer::Notify() {
std::cout << "NOTIF" << std::endl;
root.refresh();
}
void RenderTimer::start() {
Start(10);
}
#else
void MainFrame::onIdle(wxIdleEvent& ev) {
//std::cout<<"idle"<<std::endl;
refresh();
ev.RequestMore();
}
#endif
// read params from camera 0 and set the same for others
void MainFrame::readCameraParams() {
bool fol = timeline->getFollow();
timeline->Destroy();
timeline = new Timeline(this, app.numcams(), fol);
GetSizer()->Add(timeline, 1, wxEXPAND);
Layout();
if (app.numcams() > 0) {
// assume that all cameras are the same, use only zeroth
auto aperture = app.cams[0].config()["aperture"].get<gp::Aperture>();
for (size_t i = 1; i < app.numcams(); i++)
setRadioConfig<gp::Aperture>(i, aperture.index());
options->setSelections(0, aperture.choices(), aperture.index());
auto shutter = app.cams[0].config()["shutterspeed"].get<gp::ShutterSpeed>();
for (size_t i = 1; i < app.numcams(); i++)
setRadioConfig<gp::ShutterSpeed>(i, shutter.index());
options->setSelections(1, shutter.choices(), shutter.index());
auto iso = app.cams[0].config()["iso"].get<gp::Iso>();
for (size_t i = 1; i < app.numcams(); i++)
setRadioConfig<gp::Iso>(i, iso.index());
options->setSelections(2, iso.choices(), iso.index());
}
Refresh();
}
void MainFrame::create_panels() {
auto horsizer = new wxBoxSizer(wxHORIZONTAL);
// opts lots thinner than image panel
horsizer->Add(options = new OptionsPanel(this), 1, wxEXPAND);
horsizer->Add(create_imagegrid(), 4, wxEXPAND);
auto versizer = new wxBoxSizer(wxVERTICAL);
versizer->Add(horsizer, 4, wxEXPAND);
versizer->Add(timeline = new Timeline(this, app.numcams()));
SetSizer(versizer);
readCameraParams();
}
wxSizer* MainFrame::create_imagegrid() {
int rows = 3, cols = 3;
auto sizer = new wxGridSizer(cols, wxSize(2, 2));
for (int i = 0; i < rows * cols; i++) {
auto panel = new ImagePanel(this);
images.push_back(panel);
sizer->Add(panel, 1, wxEXPAND);
}
return sizer;
}
void MainFrame::create_menus() {
wxMenu *menuFile = new wxMenu();
menuFile->AppendSeparator();
menuFile->Append(1, "foo");
menuFile->Append(2, "bar");
menuFile->Append(wxID_EXIT);
wxMenuBar *menuBar = new wxMenuBar();
menuBar->Append(menuFile, "&File");
SetMenuBar(menuBar);
CreateStatusBar();
SetStatusText("Hello world");
Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::onMenu, this, 1);
Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::onExit, this, wxID_EXIT);
}
void MainFrame::slider(int id, int value) {
std::cout << "slider " << id << " to " << value << std::endl;
if (id < 0 || id > 2)
throw std::out_of_range("slider index bug");
std::vector<std::thread> setters(app.numcams());
for (size_t cam = 0; cam < app.numcams(); cam++) {
setters[cam] = std::thread([=]() {
switch (id) {
case 0:
setRadioConfig<gp::Aperture>(cam, value);
break;
case 1:
setRadioConfig<gp::ShutterSpeed>(cam, value);
break;
case 2:
setRadioConfig<gp::Iso>(cam, value);
break;
}
});
}
for (auto& thr: setters)
thr.join();
}
template <class Obj>
void MainFrame::setRadioConfig(int cam, int value) {
auto cfg = app.cams[cam].config()[Obj::gpname];
auto radio = cfg.template get<Obj>();
if (value >= 0 && value < radio.size()) {
radio.set(value);
cfg.set(radio);
std::cout << "cam " << cam << " new " << Obj::gpname << " " << radio.text() << std::endl;
}
}
void MainFrame::reloadGphoto() {
assert(!app.previewfeed.enabled());
app.reloadGphoto();
for (auto& impanel: images) {
impanel->clearImage();
}
readCameraParams();
}
void MainFrame::refresh() {
updatePhotos();
for (auto im: images) {
im->Refresh();
}
framecalc();
}
float MainFrame::time_since(MainFrame::Clock::time_point now, MainFrame::Clock::time_point before) const {
typedef std::chrono::duration<float> fsec;
fsec fs = now - before;
return fs.count();
}
void MainFrame::framecalc() {
auto clock = Clock::now();
float secs = time_since(clock, lasttime);
frames++;
if (secs > 5.0f) {
std::cout << frames << " in " << secs << " secs = " << (frames / secs) << " fps" << std::endl;
frames = 0;
lasttime = clock;
}
}
void MainFrame::updatePhotos() {
// if no sources, no update needed
if (app.numcams() == 0 || !app.previewfeed.enabled())
return;
// all have the same size
auto newsize = images[0]->GetSize();
for (size_t i = 0; i < std::min(app.numcams(), images.size()); i++) {
PreviewFeed::TimedJpegBuffer capture;
// test if there is anything
if (!app.previewfeed.getQueue(i).try_pop(capture))
continue;
// log timestamps, and slurp further ones, until got the latest
do {
timeline->insert(i, time_since(capture.second, renderinittime));
numpics[i]++;
} while (app.previewfeed.getQueue(i).try_pop(capture));
wxMemoryInputStream stream(&capture.first[0], capture.first.size());
wxImage im(stream, wxBITMAP_TYPE_JPEG);
// XXX: aspect ratio correction?
if (i < app.camOrientations.size()) {
if (app.camOrientations[i] == "90")
im = im.Rotate90();
else if (app.camOrientations[i] == "-90"
|| app.camOrientations[i] == "270")
im = im.Rotate90(false);
else if (app.camOrientations[i] == "180"
|| app.camOrientations[i] == "-180")
im = im.Rotate180();
}
im.Rescale(newsize.GetWidth(), newsize.GetHeight(), wxIMAGE_QUALITY_NEAREST);
images[i]->setImage(im, i < app.camNames.size() ? app.camNames[i] : "");
}
std::stringstream ss;
ss << app.numcams() << " cameras; frames per cam:";
for (size_t i = 0; i < numpics.size(); i++) {
ss << " " << i << ":" << numpics[i];
}
SetStatusText(ss.str());
}
void MainFrame::enableRender(bool enable) {
if (enable) {
renderinittime = Clock::now();
numpics = std::vector<int>(app.numcams());
timeline->clear();
app.previewfeed.enable();
} else {
app.previewfeed.disable();
}
}
void MainFrame::syncGrabbers(bool sync) {
app.previewfeed.setsync(sync);
}
void MainFrame::timelineFollow(bool follow) {
timeline->followInsertions(follow);
}
void MainFrame::onMenu(wxCommandEvent&) {
std::cout << "menu" << std::endl;
}
void MainFrame::onExit(wxCommandEvent&) {
Close(true);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/image_transport_factory_android.h"
#include "base/lazy_instance.h"
#include "base/memory/singleton.h"
#include "base/strings/stringprintf.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/renderer_host/compositor_impl_android.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "content/common/gpu/gpu_process_launch_causes.h"
#include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/gfx/android/device_display_info.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
namespace content {
base::LazyInstance<ObserverList<ImageTransportFactoryAndroidObserver> >::Leaky
g_factory_observers = LAZY_INSTANCE_INITIALIZER;
class GLContextLostListener
: public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
public:
// WebGraphicsContextLostCallback implementation.
virtual void onContextLost() OVERRIDE;
private:
static void DidLoseContext();
};
namespace {
using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl;
static ImageTransportFactoryAndroid* g_factory = NULL;
class DirectGLImageTransportFactory : public ImageTransportFactoryAndroid {
public:
DirectGLImageTransportFactory();
virtual ~DirectGLImageTransportFactory();
virtual uint32_t InsertSyncPoint() OVERRIDE { return 0; }
virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE {}
virtual uint32_t CreateTexture() OVERRIDE {
return context_->createTexture();
}
virtual void DeleteTexture(uint32_t id) OVERRIDE {
context_->deleteTexture(id);
}
virtual void AcquireTexture(
uint32 texture_id, const signed char* mailbox_name) OVERRIDE {}
virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
return context_.get();
}
virtual GLHelper* GetGLHelper() OVERRIDE { return NULL; }
private:
scoped_ptr<WebKit::WebGraphicsContext3D> context_;
DISALLOW_COPY_AND_ASSIGN(DirectGLImageTransportFactory);
};
DirectGLImageTransportFactory::DirectGLImageTransportFactory() {
WebKit::WebGraphicsContext3D::Attributes attrs;
attrs.shareResources = true;
attrs.noAutomaticFlushes = true;
context_ = webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl::
CreateViewContext(attrs, NULL);
context_->setContextLostCallback(context_lost_listener_.get());
if (context_->makeContextCurrent())
context_->pushGroupMarkerEXT(
base::StringPrintf("DirectGLImageTransportFactory-%p",
context_.get()).c_str());
}
DirectGLImageTransportFactory::~DirectGLImageTransportFactory() {
context_->setContextLostCallback(NULL);
}
class CmdBufferImageTransportFactory : public ImageTransportFactoryAndroid {
public:
CmdBufferImageTransportFactory();
virtual ~CmdBufferImageTransportFactory();
virtual uint32_t InsertSyncPoint() OVERRIDE;
virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE;
virtual uint32_t CreateTexture() OVERRIDE;
virtual void DeleteTexture(uint32_t id) OVERRIDE;
virtual void AcquireTexture(
uint32 texture_id, const signed char* mailbox_name) OVERRIDE;
virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
return context_.get();
}
virtual GLHelper* GetGLHelper() OVERRIDE;
private:
scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
scoped_ptr<GLHelper> gl_helper_;
DISALLOW_COPY_AND_ASSIGN(CmdBufferImageTransportFactory);
};
CmdBufferImageTransportFactory::CmdBufferImageTransportFactory() {
WebKit::WebGraphicsContext3D::Attributes attrs;
attrs.shareResources = true;
GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance();
GURL url("chrome://gpu/ImageTransportFactoryAndroid");
base::WeakPtr<WebGraphicsContext3DSwapBuffersClient> swap_client;
context_.reset(new WebGraphicsContext3DCommandBufferImpl(0, // offscreen
url,
factory,
swap_client));
static const size_t kBytesPerPixel = 4;
gfx::DeviceDisplayInfo display_info;
size_t full_screen_texture_size_in_bytes =
display_info.GetDisplayHeight() *
display_info.GetDisplayWidth() *
kBytesPerPixel;
context_->setContextLostCallback(context_lost_listener_.get());
context_->Initialize(
attrs,
false,
CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE,
64 * 1024, // command buffer size
std::min(full_screen_texture_size_in_bytes,
kDefaultStartTransferBufferSize),
kDefaultMinTransferBufferSize,
std::min(3 * full_screen_texture_size_in_bytes,
kDefaultMaxTransferBufferSize));
if (context_->makeContextCurrent())
context_->pushGroupMarkerEXT(
base::StringPrintf("CmdBufferImageTransportFactory-%p",
context_.get()).c_str());
}
CmdBufferImageTransportFactory::~CmdBufferImageTransportFactory() {
context_->setContextLostCallback(NULL);
}
uint32_t CmdBufferImageTransportFactory::InsertSyncPoint() {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return 0;
}
return context_->insertSyncPoint();
}
void CmdBufferImageTransportFactory::WaitSyncPoint(uint32_t sync_point) {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return;
}
context_->waitSyncPoint(sync_point);
}
uint32_t CmdBufferImageTransportFactory::CreateTexture() {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return false;
}
return context_->createTexture();
}
void CmdBufferImageTransportFactory::DeleteTexture(uint32_t id) {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return;
}
context_->deleteTexture(id);
}
void CmdBufferImageTransportFactory::AcquireTexture(
uint32 texture_id, const signed char* mailbox_name) {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return;
}
context_->bindTexture(GL_TEXTURE_2D, texture_id);
context_->consumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name);
context_->flush();
}
GLHelper* CmdBufferImageTransportFactory::GetGLHelper() {
if (!gl_helper_)
gl_helper_.reset(new GLHelper(context_.get()));
return gl_helper_.get();
}
} // anonymous namespace
// static
ImageTransportFactoryAndroid* ImageTransportFactoryAndroid::GetInstance() {
if (!g_factory) {
if (CompositorImpl::UsesDirectGL())
g_factory = new DirectGLImageTransportFactory();
else
g_factory = new CmdBufferImageTransportFactory();
}
return g_factory;
}
ImageTransportFactoryAndroid::ImageTransportFactoryAndroid()
: context_lost_listener_(new GLContextLostListener()) {}
ImageTransportFactoryAndroid::~ImageTransportFactoryAndroid() {}
void ImageTransportFactoryAndroid::AddObserver(
ImageTransportFactoryAndroidObserver* observer) {
g_factory_observers.Get().AddObserver(observer);
}
void ImageTransportFactoryAndroid::RemoveObserver(
ImageTransportFactoryAndroidObserver* observer) {
g_factory_observers.Get().RemoveObserver(observer);
}
void GLContextLostListener::onContextLost() {
// Need to post a task because the command buffer client cannot be deleted
// from within this callback.
LOG(ERROR) << "Context lost.";
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&GLContextLostListener::DidLoseContext));
}
void GLContextLostListener::DidLoseContext() {
delete g_factory;
g_factory = NULL;
FOR_EACH_OBSERVER(ImageTransportFactoryAndroidObserver,
g_factory_observers.Get(),
OnLostResources());
}
} // namespace content
<commit_msg>Set the start buffer size for the helper context to 64K<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/image_transport_factory_android.h"
#include "base/lazy_instance.h"
#include "base/memory/singleton.h"
#include "base/strings/stringprintf.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/renderer_host/compositor_impl_android.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "content/common/gpu/gpu_process_launch_causes.h"
#include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/gfx/android/device_display_info.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
namespace content {
base::LazyInstance<ObserverList<ImageTransportFactoryAndroidObserver> >::Leaky
g_factory_observers = LAZY_INSTANCE_INITIALIZER;
class GLContextLostListener
: public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
public:
// WebGraphicsContextLostCallback implementation.
virtual void onContextLost() OVERRIDE;
private:
static void DidLoseContext();
};
namespace {
using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl;
static ImageTransportFactoryAndroid* g_factory = NULL;
class DirectGLImageTransportFactory : public ImageTransportFactoryAndroid {
public:
DirectGLImageTransportFactory();
virtual ~DirectGLImageTransportFactory();
virtual uint32_t InsertSyncPoint() OVERRIDE { return 0; }
virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE {}
virtual uint32_t CreateTexture() OVERRIDE {
return context_->createTexture();
}
virtual void DeleteTexture(uint32_t id) OVERRIDE {
context_->deleteTexture(id);
}
virtual void AcquireTexture(
uint32 texture_id, const signed char* mailbox_name) OVERRIDE {}
virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
return context_.get();
}
virtual GLHelper* GetGLHelper() OVERRIDE { return NULL; }
private:
scoped_ptr<WebKit::WebGraphicsContext3D> context_;
DISALLOW_COPY_AND_ASSIGN(DirectGLImageTransportFactory);
};
DirectGLImageTransportFactory::DirectGLImageTransportFactory() {
WebKit::WebGraphicsContext3D::Attributes attrs;
attrs.shareResources = true;
attrs.noAutomaticFlushes = true;
context_ = webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl::
CreateViewContext(attrs, NULL);
context_->setContextLostCallback(context_lost_listener_.get());
if (context_->makeContextCurrent())
context_->pushGroupMarkerEXT(
base::StringPrintf("DirectGLImageTransportFactory-%p",
context_.get()).c_str());
}
DirectGLImageTransportFactory::~DirectGLImageTransportFactory() {
context_->setContextLostCallback(NULL);
}
class CmdBufferImageTransportFactory : public ImageTransportFactoryAndroid {
public:
CmdBufferImageTransportFactory();
virtual ~CmdBufferImageTransportFactory();
virtual uint32_t InsertSyncPoint() OVERRIDE;
virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE;
virtual uint32_t CreateTexture() OVERRIDE;
virtual void DeleteTexture(uint32_t id) OVERRIDE;
virtual void AcquireTexture(
uint32 texture_id, const signed char* mailbox_name) OVERRIDE;
virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
return context_.get();
}
virtual GLHelper* GetGLHelper() OVERRIDE;
private:
scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
scoped_ptr<GLHelper> gl_helper_;
DISALLOW_COPY_AND_ASSIGN(CmdBufferImageTransportFactory);
};
CmdBufferImageTransportFactory::CmdBufferImageTransportFactory() {
WebKit::WebGraphicsContext3D::Attributes attrs;
attrs.shareResources = true;
GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance();
GURL url("chrome://gpu/ImageTransportFactoryAndroid");
base::WeakPtr<WebGraphicsContext3DSwapBuffersClient> swap_client;
context_.reset(new WebGraphicsContext3DCommandBufferImpl(0, // offscreen
url,
factory,
swap_client));
static const size_t kBytesPerPixel = 4;
gfx::DeviceDisplayInfo display_info;
size_t full_screen_texture_size_in_bytes =
display_info.GetDisplayHeight() *
display_info.GetDisplayWidth() *
kBytesPerPixel;
context_->setContextLostCallback(context_lost_listener_.get());
context_->Initialize(
attrs,
false,
CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE,
64 * 1024, // command buffer size
64 * 1024, // starting buffer size
64 * 1024, // min buffer size
std::min(3 * full_screen_texture_size_in_bytes,
kDefaultMaxTransferBufferSize));
if (context_->makeContextCurrent())
context_->pushGroupMarkerEXT(
base::StringPrintf("CmdBufferImageTransportFactory-%p",
context_.get()).c_str());
}
CmdBufferImageTransportFactory::~CmdBufferImageTransportFactory() {
context_->setContextLostCallback(NULL);
}
uint32_t CmdBufferImageTransportFactory::InsertSyncPoint() {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return 0;
}
return context_->insertSyncPoint();
}
void CmdBufferImageTransportFactory::WaitSyncPoint(uint32_t sync_point) {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return;
}
context_->waitSyncPoint(sync_point);
}
uint32_t CmdBufferImageTransportFactory::CreateTexture() {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return false;
}
return context_->createTexture();
}
void CmdBufferImageTransportFactory::DeleteTexture(uint32_t id) {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return;
}
context_->deleteTexture(id);
}
void CmdBufferImageTransportFactory::AcquireTexture(
uint32 texture_id, const signed char* mailbox_name) {
if (!context_->makeContextCurrent()) {
LOG(ERROR) << "Failed to make helper context current.";
return;
}
context_->bindTexture(GL_TEXTURE_2D, texture_id);
context_->consumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name);
context_->flush();
}
GLHelper* CmdBufferImageTransportFactory::GetGLHelper() {
if (!gl_helper_)
gl_helper_.reset(new GLHelper(context_.get()));
return gl_helper_.get();
}
} // anonymous namespace
// static
ImageTransportFactoryAndroid* ImageTransportFactoryAndroid::GetInstance() {
if (!g_factory) {
if (CompositorImpl::UsesDirectGL())
g_factory = new DirectGLImageTransportFactory();
else
g_factory = new CmdBufferImageTransportFactory();
}
return g_factory;
}
ImageTransportFactoryAndroid::ImageTransportFactoryAndroid()
: context_lost_listener_(new GLContextLostListener()) {}
ImageTransportFactoryAndroid::~ImageTransportFactoryAndroid() {}
void ImageTransportFactoryAndroid::AddObserver(
ImageTransportFactoryAndroidObserver* observer) {
g_factory_observers.Get().AddObserver(observer);
}
void ImageTransportFactoryAndroid::RemoveObserver(
ImageTransportFactoryAndroidObserver* observer) {
g_factory_observers.Get().RemoveObserver(observer);
}
void GLContextLostListener::onContextLost() {
// Need to post a task because the command buffer client cannot be deleted
// from within this callback.
LOG(ERROR) << "Context lost.";
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&GLContextLostListener::DidLoseContext));
}
void GLContextLostListener::DidLoseContext() {
delete g_factory;
g_factory = NULL;
FOR_EACH_OBSERVER(ImageTransportFactoryAndroidObserver,
g_factory_observers.Get(),
OnLostResources());
}
} // namespace content
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
dialogs/signcertificatedialog.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "certifycertificatedialog.h"
#include "certifycertificatedialog_p.h"
#include <utils/formatting.h>
#include <KDebug>
#include <KLocalizedString>
#include <QGridLayout>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QListView>
#include <QListWidgetItem>
#include <QVBoxLayout>
#include <QWizardPage>
#include <QTextDocument> // Qt::escape
#include <cassert>
using namespace boost;
using namespace GpgME;
using namespace Kleo;
using namespace Kleo::Dialogs;
using namespace Kleo::Dialogs::CertifyCertificateDialogPrivate;
void UserIDModel::setCertificateToCertify( const Key & key ) {
m_key = key;
clear();
const std::vector<UserID> ids = key.userIDs();
for ( unsigned int i = 0; i < ids.size(); ++i ) {
QStandardItem * const item = new QStandardItem;
item->setText( Formatting::prettyUserID( key.userID( i ) ) );
item->setData( i, UserIDIndex );
item->setCheckable( true );
item->setEditable( false );
appendRow( item );
}
}
std::vector<unsigned int> UserIDModel::checkedUserIDs() const {
std::vector<unsigned int> ids;
for ( int i = 0; i < rowCount(); ++i )
if ( item( i )->checkState() == Qt::Checked )
ids.push_back( item( i )->data( UserIDIndex ).toUInt() );
return ids;
}
void SecretKeysModel::setSecretKeys( const std::vector<Key> & keys ) {
clear();
m_secretKeys = keys;
for ( unsigned int i = 0; i < m_secretKeys.size(); ++i ) {
const Key key = m_secretKeys[i];
QStandardItem * const item = new QStandardItem;
item->setText( Formatting::prettyNameAndEMail( key ) );
item->setData( i, IndexRole );
item->setEditable( false );
appendRow( item );
}
}
Key SecretKeysModel::keyFromItem( const QStandardItem * item ) const {
assert( item );
const unsigned int idx = item->data( IndexRole ).toUInt();
assert( idx < m_secretKeys.size() );
return m_secretKeys[idx];
}
Key SecretKeysModel::keyFromIndex( const QModelIndex & idx ) const {
return keyFromItem( itemFromIndex( idx ) );
}
SelectUserIDsPage::SelectUserIDsPage( QWidget * parent ) : QWizardPage( parent ), m_userIDModel() {
QVBoxLayout * const layout = new QVBoxLayout ( this );
QLabel * const label = new QLabel;
label->setText( i18n( "<b>Step 1:</b> Please select the user IDs you wish to certify." ) );
m_listView = new QListView;
m_listView->setModel( &m_userIDModel );
connect( &m_userIDModel, SIGNAL(itemChanged(QStandardItem*)), this, SIGNAL(completeChanged()) );
layout->addWidget( m_listView );
}
bool SelectUserIDsPage::isComplete() const {
return !selectedUserIDs().empty();
}
std::vector<unsigned int> SelectUserIDsPage::selectedUserIDs() const {
return m_userIDModel.checkedUserIDs();
}
void SelectUserIDsPage::setCertificateToCertify( const Key & key ) {
m_userIDModel.setCertificateToCertify( key );
}
SelectCheckLevelPage::SelectCheckLevelPage( QWidget * parent ) : QWizardPage( parent ), m_ui() {
m_ui.setupUi( this );
}
unsigned int SelectCheckLevelPage::checkLevel() const {
if ( m_ui.checkLevelNotCheckedRB->isChecked() )
return 1;
if ( m_ui.checkLevelCasualRB->isChecked() )
return 2;
if ( m_ui.checkLevelThoroughlyRB->isChecked() )
return 3;
assert( !"No check level radiobutton checked" );
return 0;
}
OptionsPage::OptionsPage( QWidget * parent ) : QWizardPage( parent ), m_ui() {
m_ui.setupUi( this );
m_ui.keyListView->setModel( &m_model );
connect( m_ui.keyListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(completeChanged()) );
setCommitPage( true );
setButtonText( QWizard::CommitButton, i18n( "Certify" ) );
}
bool OptionsPage::exportableCertificationSelected() const {
return m_ui.exportableSignatureRB->isChecked();
}
void OptionsPage::setCertificatesWithSecretKeys( const std::vector<Key> & keys ) {
assert( !keys.empty() );
m_model.setSecretKeys( keys );
if ( keys.size() == 1 ) {
m_ui.stackedWidget->setCurrentWidget( m_ui.singleKeyPage );
m_ui.singleKeyLabel->setText( i18n( "Certification will be performed using certificate %1.", Formatting::prettyNameAndEMail( keys[0] ) ) );
} else {
m_ui.stackedWidget->setCurrentWidget( m_ui.multipleKeysPage );
}
emit completeChanged();
}
Key OptionsPage::selectedSecretKey() const {
const QModelIndexList idxs = m_ui.keyListView->selectionModel()->selectedIndexes();
assert( idxs.size() <= 1 );
return idxs.isEmpty() ? Key() : m_model.keyFromIndex( idxs[0] );
}
bool OptionsPage::sendToServer() const {
return m_ui.sendToServerCB->isChecked();
}
bool OptionsPage::validatePage() {
emit nextClicked();
return true;
}
bool OptionsPage::isComplete() const {
return !selectedSecretKey().isNull();
}
SummaryPage::SummaryPage( QWidget * parent ) : QWizardPage( parent ), m_complete( false ) {
QGridLayout * const layout = new QGridLayout( this );
QLabel * const uidLabelLabel = new QLabel( i18n( "Signed user IDs:" ) );
uidLabelLabel->setAlignment( Qt::AlignTop );
layout->addWidget( uidLabelLabel, 0, 0 );
layout->addWidget( m_userIDsLabel = new QLabel, 0, 1 );
layout->addWidget( new QLabel( i18n( "Check level:" )), 1, 0 );
layout->addWidget( m_checkLevelLabel = new QLabel, 1, 1 );
layout->addWidget( new QLabel( i18n( "Selected secret certificate:" ) ), 2, 0 );
layout->addWidget( m_secretKeyLabel = new QLabel, 2, 1 );
m_secretKeyLabel->setTextFormat( Qt::PlainText );
layout->addWidget( m_resultLabel = new QLabel, 3, 0, 2, 1 );
}
bool SummaryPage::isComplete() const {
return m_complete;
}
void SummaryPage::setSummary( const SummaryPage::Summary & sum ) {
const Key key = sum.certificateToCertify;
QStringList ids;
Q_FOREACH ( const unsigned int i, sum.selectedUserIDs )
ids += Qt::escape( Formatting::prettyUserID( key.userID( i ) ) );
m_userIDsLabel->setText( "<qt>" + ids.join( "<br/>" ) + "</qt>" );
m_secretKeyLabel->setText( sum.secretKey.isNull() ? i18n( "Default certificate" ) : Formatting::prettyNameAndEMail( sum.secretKey ) );
switch( sum.checkLevel ) {
case 0:
m_checkLevelLabel->setText( i18n( "No statement made" ) );
break;
case 1:
m_checkLevelLabel->setText( i18n( "Not checked" ) );
break;
case 2:
m_checkLevelLabel->setText( i18n( "Casually checked" ) );
break;
case 3:
m_checkLevelLabel->setText( i18n( "Thoroughly checked" ) );
break;
}
}
void SummaryPage::setComplete( bool complete ) {
if ( complete == m_complete )
return;
m_complete = complete;
emit completeChanged();
}
void SummaryPage::setResult( const Error & err ) {
if ( err && !err.isCanceled() )
m_resultLabel->setText( i18n( "<b>Error</b>: %1", Qt::escape( QString::fromLocal8Bit( err.asString() ) ) ) );
else if ( err.isCanceled() )
m_resultLabel->setText( "Certification canceled." );
else
m_resultLabel->setText("Certification finished." );
}
class CertifyCertificateDialog::Private {
friend class ::Kleo::Dialogs::CertifyCertificateDialog;
CertifyCertificateDialog * const q;
public:
explicit Private( CertifyCertificateDialog * qq )
: q( qq ),
summaryPageId( 0 ),
selectUserIDsPage( 0 ),
selectCheckLevelPage( 0 ),
optionsPage( 0 ),
summaryPage( 0 )
{
selectUserIDsPage = new SelectUserIDsPage( q );
q->addPage( selectUserIDsPage );
selectCheckLevelPage = new SelectCheckLevelPage( q );
q->addPage( selectCheckLevelPage );
optionsPage = new OptionsPage( q );
q->addPage( optionsPage );
summaryPage = new SummaryPage( q );
summaryPageId = q->addPage( summaryPage );
connect( optionsPage, SIGNAL(nextClicked()), q, SIGNAL(certificationPrepared()) );
}
void ensureSummaryPageVisible();
void certificationResult( const Error & error );
void setOperationCompleted() {
summaryPage->setComplete( true );
}
SummaryPage::Summary createSummary() const {
SummaryPage::Summary sum;
sum.selectedUserIDs = selectUserIDsPage->selectedUserIDs();
sum.secretKey = optionsPage->selectedSecretKey();
sum.certificateToCertify = selectUserIDsPage->certificateToCertify();
sum.checkLevel = selectCheckLevelPage->checkLevel();
sum.exportable = optionsPage->exportableCertificationSelected();
sum.sendToServer = optionsPage->sendToServer();
return sum;
}
int summaryPageId;
SelectUserIDsPage * selectUserIDsPage;
SelectCheckLevelPage * selectCheckLevelPage;
OptionsPage * optionsPage;
SummaryPage * summaryPage;
};
CertifyCertificateDialog::CertifyCertificateDialog( QWidget * p, Qt::WindowFlags f )
: QWizard( p, f ), d( new Private( this ) )
{
}
CertifyCertificateDialog::~CertifyCertificateDialog() {}
void CertifyCertificateDialog::setCertificateToCertify( const Key & key ) {
setWindowTitle( i18nc( "arg is name, email of certificate holder", "Certify Certificate: %1", Formatting::prettyName( key ) ) );
d->selectUserIDsPage->setCertificateToCertify( key );
}
void CertifyCertificateDialog::setCertificatesWithSecretKeys( const std::vector<Key> & keys ) {
d->optionsPage->setCertificatesWithSecretKeys( keys );
}
bool CertifyCertificateDialog::exportableCertificationSelected() const {
return d->optionsPage->exportableCertificationSelected();
}
bool CertifyCertificateDialog::trustCertificationSelected() const {
return false;
}
bool CertifyCertificateDialog::nonRevocableCertificationSelected() const {
return false;
}
Key CertifyCertificateDialog::selectedSecretKey() const {
return d->optionsPage->selectedSecretKey();
}
bool CertifyCertificateDialog::sendToServer() const {
return d->optionsPage->sendToServer();
}
unsigned int CertifyCertificateDialog::selectedCheckLevel() const {
return d->selectCheckLevelPage->checkLevel();
}
void CertifyCertificateDialog::connectJob( SignKeyJob * job ) {
connect( job, SIGNAL(result(GpgME::Error)), this, SLOT(certificationResult(GpgME::Error)) );
d->summaryPage->setSummary( d->createSummary() );
}
void CertifyCertificateDialog::setError( const Error & error ) {
d->setOperationCompleted();
d->summaryPage->setResult( error );
d->ensureSummaryPageVisible();
if ( error.isCanceled() )
close();
}
void CertifyCertificateDialog::Private::certificationResult( const Error & err ) {
setOperationCompleted();
summaryPage->setResult( err );
ensureSummaryPageVisible();
}
std::vector<unsigned int> CertifyCertificateDialog::selectedUserIDs() const {
return d->selectUserIDsPage->selectedUserIDs();
}
void CertifyCertificateDialog::Private::ensureSummaryPageVisible() {
while ( q->currentId() != summaryPageId )
q->next();
}
#include "moc_certifycertificatedialog.cpp"
#include "moc_certifycertificatedialog_p.cpp"
<commit_msg>add label to layout<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
dialogs/signcertificatedialog.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "certifycertificatedialog.h"
#include "certifycertificatedialog_p.h"
#include <utils/formatting.h>
#include <KDebug>
#include <KLocalizedString>
#include <QGridLayout>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QListView>
#include <QListWidgetItem>
#include <QVBoxLayout>
#include <QWizardPage>
#include <QTextDocument> // Qt::escape
#include <cassert>
using namespace boost;
using namespace GpgME;
using namespace Kleo;
using namespace Kleo::Dialogs;
using namespace Kleo::Dialogs::CertifyCertificateDialogPrivate;
void UserIDModel::setCertificateToCertify( const Key & key ) {
m_key = key;
clear();
const std::vector<UserID> ids = key.userIDs();
for ( unsigned int i = 0; i < ids.size(); ++i ) {
QStandardItem * const item = new QStandardItem;
item->setText( Formatting::prettyUserID( key.userID( i ) ) );
item->setData( i, UserIDIndex );
item->setCheckable( true );
item->setEditable( false );
appendRow( item );
}
}
std::vector<unsigned int> UserIDModel::checkedUserIDs() const {
std::vector<unsigned int> ids;
for ( int i = 0; i < rowCount(); ++i )
if ( item( i )->checkState() == Qt::Checked )
ids.push_back( item( i )->data( UserIDIndex ).toUInt() );
return ids;
}
void SecretKeysModel::setSecretKeys( const std::vector<Key> & keys ) {
clear();
m_secretKeys = keys;
for ( unsigned int i = 0; i < m_secretKeys.size(); ++i ) {
const Key key = m_secretKeys[i];
QStandardItem * const item = new QStandardItem;
item->setText( Formatting::prettyNameAndEMail( key ) );
item->setData( i, IndexRole );
item->setEditable( false );
appendRow( item );
}
}
Key SecretKeysModel::keyFromItem( const QStandardItem * item ) const {
assert( item );
const unsigned int idx = item->data( IndexRole ).toUInt();
assert( idx < m_secretKeys.size() );
return m_secretKeys[idx];
}
Key SecretKeysModel::keyFromIndex( const QModelIndex & idx ) const {
return keyFromItem( itemFromIndex( idx ) );
}
SelectUserIDsPage::SelectUserIDsPage( QWidget * parent ) : QWizardPage( parent ), m_userIDModel() {
QVBoxLayout * const layout = new QVBoxLayout ( this );
QLabel * const label = new QLabel;
label->setText( i18n( "<b>Step 1:</b> Please select the user IDs you wish to certify." ) );
layout->addWidget( label );
m_listView = new QListView;
m_listView->setModel( &m_userIDModel );
connect( &m_userIDModel, SIGNAL(itemChanged(QStandardItem*)), this, SIGNAL(completeChanged()) );
layout->addWidget( m_listView );
}
bool SelectUserIDsPage::isComplete() const {
return !selectedUserIDs().empty();
}
std::vector<unsigned int> SelectUserIDsPage::selectedUserIDs() const {
return m_userIDModel.checkedUserIDs();
}
void SelectUserIDsPage::setCertificateToCertify( const Key & key ) {
m_userIDModel.setCertificateToCertify( key );
}
SelectCheckLevelPage::SelectCheckLevelPage( QWidget * parent ) : QWizardPage( parent ), m_ui() {
m_ui.setupUi( this );
}
unsigned int SelectCheckLevelPage::checkLevel() const {
if ( m_ui.checkLevelNotCheckedRB->isChecked() )
return 1;
if ( m_ui.checkLevelCasualRB->isChecked() )
return 2;
if ( m_ui.checkLevelThoroughlyRB->isChecked() )
return 3;
assert( !"No check level radiobutton checked" );
return 0;
}
OptionsPage::OptionsPage( QWidget * parent ) : QWizardPage( parent ), m_ui() {
m_ui.setupUi( this );
m_ui.keyListView->setModel( &m_model );
connect( m_ui.keyListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(completeChanged()) );
setCommitPage( true );
setButtonText( QWizard::CommitButton, i18n( "Certify" ) );
}
bool OptionsPage::exportableCertificationSelected() const {
return m_ui.exportableSignatureRB->isChecked();
}
void OptionsPage::setCertificatesWithSecretKeys( const std::vector<Key> & keys ) {
assert( !keys.empty() );
m_model.setSecretKeys( keys );
if ( keys.size() == 1 ) {
m_ui.stackedWidget->setCurrentWidget( m_ui.singleKeyPage );
m_ui.singleKeyLabel->setText( i18n( "Certification will be performed using certificate %1.", Formatting::prettyNameAndEMail( keys[0] ) ) );
} else {
m_ui.stackedWidget->setCurrentWidget( m_ui.multipleKeysPage );
}
emit completeChanged();
}
Key OptionsPage::selectedSecretKey() const {
const QModelIndexList idxs = m_ui.keyListView->selectionModel()->selectedIndexes();
assert( idxs.size() <= 1 );
return idxs.isEmpty() ? Key() : m_model.keyFromIndex( idxs[0] );
}
bool OptionsPage::sendToServer() const {
return m_ui.sendToServerCB->isChecked();
}
bool OptionsPage::validatePage() {
emit nextClicked();
return true;
}
bool OptionsPage::isComplete() const {
return !selectedSecretKey().isNull();
}
SummaryPage::SummaryPage( QWidget * parent ) : QWizardPage( parent ), m_complete( false ) {
QGridLayout * const layout = new QGridLayout( this );
QLabel * const uidLabelLabel = new QLabel( i18n( "Signed user IDs:" ) );
uidLabelLabel->setAlignment( Qt::AlignTop );
layout->addWidget( uidLabelLabel, 0, 0 );
layout->addWidget( m_userIDsLabel = new QLabel, 0, 1 );
layout->addWidget( new QLabel( i18n( "Check level:" )), 1, 0 );
layout->addWidget( m_checkLevelLabel = new QLabel, 1, 1 );
layout->addWidget( new QLabel( i18n( "Selected secret certificate:" ) ), 2, 0 );
layout->addWidget( m_secretKeyLabel = new QLabel, 2, 1 );
m_secretKeyLabel->setTextFormat( Qt::PlainText );
layout->addWidget( m_resultLabel = new QLabel, 3, 0, 2, 1 );
}
bool SummaryPage::isComplete() const {
return m_complete;
}
void SummaryPage::setSummary( const SummaryPage::Summary & sum ) {
const Key key = sum.certificateToCertify;
QStringList ids;
Q_FOREACH ( const unsigned int i, sum.selectedUserIDs )
ids += Qt::escape( Formatting::prettyUserID( key.userID( i ) ) );
m_userIDsLabel->setText( "<qt>" + ids.join( "<br/>" ) + "</qt>" );
m_secretKeyLabel->setText( sum.secretKey.isNull() ? i18n( "Default certificate" ) : Formatting::prettyNameAndEMail( sum.secretKey ) );
switch( sum.checkLevel ) {
case 0:
m_checkLevelLabel->setText( i18n( "No statement made" ) );
break;
case 1:
m_checkLevelLabel->setText( i18n( "Not checked" ) );
break;
case 2:
m_checkLevelLabel->setText( i18n( "Casually checked" ) );
break;
case 3:
m_checkLevelLabel->setText( i18n( "Thoroughly checked" ) );
break;
}
}
void SummaryPage::setComplete( bool complete ) {
if ( complete == m_complete )
return;
m_complete = complete;
emit completeChanged();
}
void SummaryPage::setResult( const Error & err ) {
if ( err && !err.isCanceled() )
m_resultLabel->setText( i18n( "<b>Error</b>: %1", Qt::escape( QString::fromLocal8Bit( err.asString() ) ) ) );
else if ( err.isCanceled() )
m_resultLabel->setText( "Certification canceled." );
else
m_resultLabel->setText("Certification finished." );
}
class CertifyCertificateDialog::Private {
friend class ::Kleo::Dialogs::CertifyCertificateDialog;
CertifyCertificateDialog * const q;
public:
explicit Private( CertifyCertificateDialog * qq )
: q( qq ),
summaryPageId( 0 ),
selectUserIDsPage( 0 ),
selectCheckLevelPage( 0 ),
optionsPage( 0 ),
summaryPage( 0 )
{
selectUserIDsPage = new SelectUserIDsPage( q );
q->addPage( selectUserIDsPage );
selectCheckLevelPage = new SelectCheckLevelPage( q );
q->addPage( selectCheckLevelPage );
optionsPage = new OptionsPage( q );
q->addPage( optionsPage );
summaryPage = new SummaryPage( q );
summaryPageId = q->addPage( summaryPage );
connect( optionsPage, SIGNAL(nextClicked()), q, SIGNAL(certificationPrepared()) );
}
void ensureSummaryPageVisible();
void certificationResult( const Error & error );
void setOperationCompleted() {
summaryPage->setComplete( true );
}
SummaryPage::Summary createSummary() const {
SummaryPage::Summary sum;
sum.selectedUserIDs = selectUserIDsPage->selectedUserIDs();
sum.secretKey = optionsPage->selectedSecretKey();
sum.certificateToCertify = selectUserIDsPage->certificateToCertify();
sum.checkLevel = selectCheckLevelPage->checkLevel();
sum.exportable = optionsPage->exportableCertificationSelected();
sum.sendToServer = optionsPage->sendToServer();
return sum;
}
int summaryPageId;
SelectUserIDsPage * selectUserIDsPage;
SelectCheckLevelPage * selectCheckLevelPage;
OptionsPage * optionsPage;
SummaryPage * summaryPage;
};
CertifyCertificateDialog::CertifyCertificateDialog( QWidget * p, Qt::WindowFlags f )
: QWizard( p, f ), d( new Private( this ) )
{
}
CertifyCertificateDialog::~CertifyCertificateDialog() {}
void CertifyCertificateDialog::setCertificateToCertify( const Key & key ) {
setWindowTitle( i18nc( "arg is name, email of certificate holder", "Certify Certificate: %1", Formatting::prettyName( key ) ) );
d->selectUserIDsPage->setCertificateToCertify( key );
}
void CertifyCertificateDialog::setCertificatesWithSecretKeys( const std::vector<Key> & keys ) {
d->optionsPage->setCertificatesWithSecretKeys( keys );
}
bool CertifyCertificateDialog::exportableCertificationSelected() const {
return d->optionsPage->exportableCertificationSelected();
}
bool CertifyCertificateDialog::trustCertificationSelected() const {
return false;
}
bool CertifyCertificateDialog::nonRevocableCertificationSelected() const {
return false;
}
Key CertifyCertificateDialog::selectedSecretKey() const {
return d->optionsPage->selectedSecretKey();
}
bool CertifyCertificateDialog::sendToServer() const {
return d->optionsPage->sendToServer();
}
unsigned int CertifyCertificateDialog::selectedCheckLevel() const {
return d->selectCheckLevelPage->checkLevel();
}
void CertifyCertificateDialog::connectJob( SignKeyJob * job ) {
connect( job, SIGNAL(result(GpgME::Error)), this, SLOT(certificationResult(GpgME::Error)) );
d->summaryPage->setSummary( d->createSummary() );
}
void CertifyCertificateDialog::setError( const Error & error ) {
d->setOperationCompleted();
d->summaryPage->setResult( error );
d->ensureSummaryPageVisible();
if ( error.isCanceled() )
close();
}
void CertifyCertificateDialog::Private::certificationResult( const Error & err ) {
setOperationCompleted();
summaryPage->setResult( err );
ensureSummaryPageVisible();
}
std::vector<unsigned int> CertifyCertificateDialog::selectedUserIDs() const {
return d->selectUserIDsPage->selectedUserIDs();
}
void CertifyCertificateDialog::Private::ensureSummaryPageVisible() {
while ( q->currentId() != summaryPageId )
q->next();
}
#include "moc_certifycertificatedialog.cpp"
#include "moc_certifycertificatedialog_p.cpp"
<|endoftext|> |
<commit_before>/**
* kmacctimap.cpp
*
* Copyright (c) 2000-2002 Michael Haeckel <haeckel@kde.org>
*
* This file is based on kmacctexppop.cpp by Don Sanders
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmacctimap.h"
using KMail::SieveConfig;
#include "kmbroadcaststatus.h"
#include "kmfoldertree.h"
#include "kmfoldermgr.h"
#include "kmfolderimap.h"
#include "kmmainwin.h"
#include "folderstorage.h"
#include "imapjob.h"
using KMail::ImapJob;
#include "progressmanager.h"
using KPIM::ProgressItem;
using KPIM::ProgressManager;
#include <kio/scheduler.h>
#include <kio/slave.h>
#include <kmessagebox.h>
#include <kdebug.h>
//-----------------------------------------------------------------------------
KMAcctImap::KMAcctImap(KMAcctMgr* aOwner, const QString& aAccountName, uint id):
KMail::ImapAccountBase(aOwner, aAccountName, id),
mCountRemainChecks( 0 )
{
mFolder = 0;
mOpenFolders.setAutoDelete(true);
connect(kmkernel->imapFolderMgr(), SIGNAL(changed()),
this, SLOT(slotUpdateFolderList()));
}
//-----------------------------------------------------------------------------
KMAcctImap::~KMAcctImap()
{
killAllJobs( true );
}
//-----------------------------------------------------------------------------
QString KMAcctImap::type() const
{
return "imap";
}
//-----------------------------------------------------------------------------
void KMAcctImap::pseudoAssign( const KMAccount * a ) {
mIdleTimer.stop();
killAllJobs( true );
if (mFolder)
{
mFolder->setContentState(KMFolderImap::imapNoInformation);
mFolder->setSubfolderState(KMFolderImap::imapNoInformation);
}
ImapAccountBase::pseudoAssign( a );
}
//-----------------------------------------------------------------------------
void KMAcctImap::setImapFolder(KMFolderImap *aFolder)
{
mFolder = aFolder;
mFolder->setImapPath(mPrefix);
}
//-----------------------------------------------------------------------------
bool KMAcctImap::handleError( int errorCode, const QString &errorMsg, KIO::Job* job, const QString& context, bool abortSync )
{
/* TODO check where to handle this one better. */
if ( errorCode == KIO::ERR_DOES_NOT_EXIST ) {
// folder is gone, so reload the folderlist
if ( mFolder )
mFolder->listDirectory();
return true;
}
return ImapAccountBase::handleError( errorCode, errorMsg, job, context, abortSync );
}
//-----------------------------------------------------------------------------
void KMAcctImap::killAllJobs( bool disconnectSlave )
{
QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
for ( ; it != mapJobData.end(); ++it)
{
QPtrList<KMMessage> msgList = (*it).msgList;
QPtrList<KMMessage>::Iterator it2 = msgList.begin();
for ( ; it2 != msgList.end(); ++it2 ) {
KMMessage *msg = *it2;
if ( msg->transferInProgress() ) {
kdDebug(5006) << "KMAcctImap::killAllJobs - resetting mail" << endl;
msg->setTransferInProgress( false );
}
}
if ((*it).parent)
{
// clear folder state
KMFolderImap *fld = static_cast<KMFolderImap*>((*it).parent->storage());
fld->setCheckingValidity(false);
fld->setContentState(KMFolderImap::imapNoInformation);
fld->setSubfolderState(KMFolderImap::imapNoInformation);
fld->sendFolderComplete(FALSE);
fld->removeJobs();
}
}
if (mSlave && mapJobData.begin() != mapJobData.end())
{
mSlave->kill();
mSlave = 0;
}
// remove the jobs
mapJobData.clear();
KMAccount::deleteFolderJobs();
// make sure that no new-mail-check is blocked
if (mCountRemainChecks > 0)
{
checkDone( false, CheckOK ); // returned 0 new messages
mCountRemainChecks = 0;
}
if ( disconnectSlave && slave() ) {
KIO::Scheduler::disconnectSlave( slave() );
mSlave = 0;
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForMessage( KMMessage* msg )
{
if (!msg) return;
QPtrListIterator<ImapJob> it( mJobList );
while ( it.current() )
{
ImapJob *job = it.current();
++it;
if ( job->msgList().findRef( msg ) != -1 )
{
if ( job->mJob )
removeJob( job->mJob );
mJobList.remove( job );
job->kill();
}
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForFolder( KMFolder* folder )
{
QPtrListIterator<ImapJob> it( mJobList );
while ( it.current() )
{
ImapJob *job = it.current();
++it;
if ( !job->msgList().isEmpty() && job->msgList().first()->parent() == folder )
{
if ( job->mJob )
removeJob( job->mJob );
mJobList.remove( job );
job->kill();
}
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::removeSlaveJobsForFolder( KMFolder* folder )
{
// Make sure the folder is not referenced in any kio slave jobs
QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
while ( it != mapJobData.end() ) {
QMap<KIO::Job*, jobData>::Iterator i = it;
it++;
if ( (*i).parent ) {
if ( (*i).parent == folder ) {
mapJobData.remove(i);
}
}
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::cancelMailCheck()
{
// Make list of folders to reset, like in killAllJobs
QValueList<KMFolderImap*> folderList;
QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
for (; it != mapJobData.end(); ++it) {
if ( (*it).cancellable && (*it).parent ) {
folderList << static_cast<KMFolderImap*>((*it).parent->storage());
}
}
// Kill jobs
// FIXME
// ImapAccountBase::cancelMailCheck();
killAllJobs( true );
// emit folderComplete, this is important for
// KMAccount::checkingMail() to be reset, in case we restart checking mail later.
for( QValueList<KMFolderImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {
KMFolderImap *fld = *it;
fld->sendFolderComplete(FALSE);
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::processNewMail(bool interactive)
{
if (!mFolder || !mFolder->folder() || !mFolder->folder()->child() ||
makeConnection() == ImapAccountBase::Error)
{
mCountRemainChecks = 0;
checkDone( false, CheckError );
return;
}
// if necessary then initialize the list of folders which should be checked
if( mMailCheckFolders.isEmpty() )
{
slotUpdateFolderList();
// if no folders should be checked then the check is finished
if( mMailCheckFolders.isEmpty() )
{
checkDone( false, CheckOK );
}
}
// Ok, we're really checking, get a progress item;
Q_ASSERT( !mMailCheckProgressItem );
mMailCheckProgressItem =
ProgressManager::createProgressItem(
"MailCheckAccount" + name(),
i18n("Checking account: " ) + name(),
QString::null, // status
true, // can be canceled
useSSL() || useTLS() );
mMailCheckProgressItem->setTotalItems( mMailCheckFolders.count() );
connect ( mMailCheckProgressItem,
SIGNAL( progressItemCanceled( ProgressItem*) ),
this,
SLOT( slotMailCheckCanceled() ) );
QValueList<QGuardedPtr<KMFolder> >::Iterator it;
// first get the current count of unread-messages
mCountRemainChecks = 0;
mCountUnread = 0;
mUnreadBeforeCheck.clear();
for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); it++)
{
KMFolder *folder = *it;
if (folder && !folder->noContent())
{
mUnreadBeforeCheck[folder->idString()] = folder->countUnread();
}
}
bool gotError = false;
// then check for new mails
for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); it++)
{
KMFolder *folder = *it;
if (folder && !folder->noContent())
{
KMFolderImap *imapFolder = static_cast<KMFolderImap*>(folder->storage());
if (imapFolder->getContentState() != KMFolderImap::imapInProgress)
{
// connect the result-signals for new-mail-notification
mCountRemainChecks++;
if (imapFolder->isSelected()) {
connect(imapFolder, SIGNAL(folderComplete(KMFolderImap*, bool)),
this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
imapFolder->getFolder();
}
else {
connect(imapFolder, SIGNAL(numUnreadMsgsChanged(KMFolder*)),
this, SLOT(postProcessNewMail(KMFolder*)));
bool ok = imapFolder->processNewMail(interactive);
if (!ok)
{
// there was an error so cancel
mCountRemainChecks--;
gotError = true;
}
}
}
}
} // end for
if ( gotError )
slotUpdateFolderList();
}
//-----------------------------------------------------------------------------
void KMAcctImap::postProcessNewMail(KMFolderImap* folder, bool)
{
disconnect(folder, SIGNAL(folderComplete(KMFolderImap*, bool)),
this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
postProcessNewMail(static_cast<KMFolder*>(folder->folder()));
}
void KMAcctImap::postProcessNewMail( KMFolder * folder ) {
disconnect( folder->storage(), SIGNAL(numUnreadMsgsChanged(KMFolder*)),
this, SLOT(postProcessNewMail(KMFolder*)) );
if ( mMailCheckProgressItem ) {
mMailCheckProgressItem->incCompletedItems();
mMailCheckProgressItem->updateProgress();
mMailCheckProgressItem->setStatus( folder->prettyURL() + i18n(" completed") );
}
mCountRemainChecks--;
// count the unread messages
const QString folderId = folder->idString();
int newInFolder = folder->countUnread();
if ( mUnreadBeforeCheck.find( folderId ) != mUnreadBeforeCheck.end() )
newInFolder -= mUnreadBeforeCheck[folderId];
if ( newInFolder > 0 ) {
addToNewInFolder( folderId, newInFolder );
mCountUnread += newInFolder;
}
if (mCountRemainChecks == 0)
{
// all checks are done
mCountLastUnread = 0; // => mCountUnread - mCountLastUnread == new count
ImapAccountBase::postProcessNewMail();
mUnreadBeforeCheck.clear();
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::slotUpdateFolderList()
{
if (!mFolder || !mFolder->folder() || !mFolder->folder()->child() ||
makeConnection() != ImapAccountBase::Connected)
return;
QStringList strList;
mMailCheckFolders.clear();
kmkernel->imapFolderMgr()->createFolderList(&strList, &mMailCheckFolders,
mFolder->folder()->child(), QString::null, false);
// the new list
QValueList<QGuardedPtr<KMFolder> > includedFolders;
// check for excluded folders
QValueList<QGuardedPtr<KMFolder> >::Iterator it;
for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); it++)
{
KMFolderImap* folder = static_cast<KMFolderImap*>(((KMFolder*)(*it))->storage());
if (folder->includeInMailCheck())
includedFolders.append(*it);
}
mMailCheckFolders = includedFolders;
}
//-----------------------------------------------------------------------------
void KMAcctImap::listDirectory()
{
mFolder->listDirectory();
}
//-----------------------------------------------------------------------------
void KMAcctImap::setPrefixHook() {
if ( mFolder ) mFolder->setImapPath( prefix() );
}
//-----------------------------------------------------------------------------
void KMAcctImap::readConfig(KConfig& config)
{
ImapAccountBase::readConfig( config );
if ( checkExclude() ) {
disconnect(kmkernel->imapFolderMgr(), SIGNAL(changed()),
this, SLOT(slotUpdateFolderList()));
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::slotMailCheckCanceled()
{
if( mMailCheckProgressItem )
mMailCheckProgressItem->setComplete();
cancelMailCheck();
}
//-----------------------------------------------------------------------------
FolderStorage* KMAcctImap::rootFolder()
{
return mFolder;
}
#include "kmacctimap.moc"
<commit_msg>Send a noop every 60 sec. Pretty basic solution but should work. CCMAIL: 82805-done@bugs.kde.org<commit_after>/**
* kmacctimap.cpp
*
* Copyright (c) 2000-2002 Michael Haeckel <haeckel@kde.org>
*
* This file is based on kmacctexppop.cpp by Don Sanders
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmacctimap.h"
using KMail::SieveConfig;
#include "kmbroadcaststatus.h"
#include "kmfoldertree.h"
#include "kmfoldermgr.h"
#include "kmfolderimap.h"
#include "kmmainwin.h"
#include "folderstorage.h"
#include "imapjob.h"
using KMail::ImapJob;
#include "progressmanager.h"
using KPIM::ProgressItem;
using KPIM::ProgressManager;
#include <kio/scheduler.h>
#include <kio/slave.h>
#include <kmessagebox.h>
#include <kdebug.h>
//-----------------------------------------------------------------------------
KMAcctImap::KMAcctImap(KMAcctMgr* aOwner, const QString& aAccountName, uint id):
KMail::ImapAccountBase(aOwner, aAccountName, id),
mCountRemainChecks( 0 )
{
mFolder = 0;
mIdle = false; // never disconnect
mIdleTimer.start( 60000 ); // // send a noop every minute
mOpenFolders.setAutoDelete(true);
connect(kmkernel->imapFolderMgr(), SIGNAL(changed()),
this, SLOT(slotUpdateFolderList()));
}
//-----------------------------------------------------------------------------
KMAcctImap::~KMAcctImap()
{
killAllJobs( true );
}
//-----------------------------------------------------------------------------
QString KMAcctImap::type() const
{
return "imap";
}
//-----------------------------------------------------------------------------
void KMAcctImap::pseudoAssign( const KMAccount * a ) {
killAllJobs( true );
if (mFolder)
{
mFolder->setContentState(KMFolderImap::imapNoInformation);
mFolder->setSubfolderState(KMFolderImap::imapNoInformation);
}
ImapAccountBase::pseudoAssign( a );
}
//-----------------------------------------------------------------------------
void KMAcctImap::setImapFolder(KMFolderImap *aFolder)
{
mFolder = aFolder;
mFolder->setImapPath(mPrefix);
}
//-----------------------------------------------------------------------------
bool KMAcctImap::handleError( int errorCode, const QString &errorMsg, KIO::Job* job, const QString& context, bool abortSync )
{
/* TODO check where to handle this one better. */
if ( errorCode == KIO::ERR_DOES_NOT_EXIST ) {
// folder is gone, so reload the folderlist
if ( mFolder )
mFolder->listDirectory();
return true;
}
return ImapAccountBase::handleError( errorCode, errorMsg, job, context, abortSync );
}
//-----------------------------------------------------------------------------
void KMAcctImap::killAllJobs( bool disconnectSlave )
{
QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
for ( ; it != mapJobData.end(); ++it)
{
QPtrList<KMMessage> msgList = (*it).msgList;
QPtrList<KMMessage>::Iterator it2 = msgList.begin();
for ( ; it2 != msgList.end(); ++it2 ) {
KMMessage *msg = *it2;
if ( msg->transferInProgress() ) {
kdDebug(5006) << "KMAcctImap::killAllJobs - resetting mail" << endl;
msg->setTransferInProgress( false );
}
}
if ((*it).parent)
{
// clear folder state
KMFolderImap *fld = static_cast<KMFolderImap*>((*it).parent->storage());
fld->setCheckingValidity(false);
fld->setContentState(KMFolderImap::imapNoInformation);
fld->setSubfolderState(KMFolderImap::imapNoInformation);
fld->sendFolderComplete(FALSE);
fld->removeJobs();
}
}
if (mSlave && mapJobData.begin() != mapJobData.end())
{
mSlave->kill();
mSlave = 0;
}
// remove the jobs
mapJobData.clear();
KMAccount::deleteFolderJobs();
// make sure that no new-mail-check is blocked
if (mCountRemainChecks > 0)
{
checkDone( false, CheckOK ); // returned 0 new messages
mCountRemainChecks = 0;
}
if ( disconnectSlave && slave() ) {
KIO::Scheduler::disconnectSlave( slave() );
mSlave = 0;
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForMessage( KMMessage* msg )
{
if (!msg) return;
QPtrListIterator<ImapJob> it( mJobList );
while ( it.current() )
{
ImapJob *job = it.current();
++it;
if ( job->msgList().findRef( msg ) != -1 )
{
if ( job->mJob )
removeJob( job->mJob );
mJobList.remove( job );
job->kill();
}
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForFolder( KMFolder* folder )
{
QPtrListIterator<ImapJob> it( mJobList );
while ( it.current() )
{
ImapJob *job = it.current();
++it;
if ( !job->msgList().isEmpty() && job->msgList().first()->parent() == folder )
{
if ( job->mJob )
removeJob( job->mJob );
mJobList.remove( job );
job->kill();
}
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::removeSlaveJobsForFolder( KMFolder* folder )
{
// Make sure the folder is not referenced in any kio slave jobs
QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
while ( it != mapJobData.end() ) {
QMap<KIO::Job*, jobData>::Iterator i = it;
it++;
if ( (*i).parent ) {
if ( (*i).parent == folder ) {
mapJobData.remove(i);
}
}
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::cancelMailCheck()
{
// Make list of folders to reset, like in killAllJobs
QValueList<KMFolderImap*> folderList;
QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
for (; it != mapJobData.end(); ++it) {
if ( (*it).cancellable && (*it).parent ) {
folderList << static_cast<KMFolderImap*>((*it).parent->storage());
}
}
// Kill jobs
// FIXME
// ImapAccountBase::cancelMailCheck();
killAllJobs( true );
// emit folderComplete, this is important for
// KMAccount::checkingMail() to be reset, in case we restart checking mail later.
for( QValueList<KMFolderImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {
KMFolderImap *fld = *it;
fld->sendFolderComplete(FALSE);
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::processNewMail(bool interactive)
{
if (!mFolder || !mFolder->folder() || !mFolder->folder()->child() ||
makeConnection() == ImapAccountBase::Error)
{
mCountRemainChecks = 0;
checkDone( false, CheckError );
return;
}
// if necessary then initialize the list of folders which should be checked
if( mMailCheckFolders.isEmpty() )
{
slotUpdateFolderList();
// if no folders should be checked then the check is finished
if( mMailCheckFolders.isEmpty() )
{
checkDone( false, CheckOK );
}
}
// Ok, we're really checking, get a progress item;
Q_ASSERT( !mMailCheckProgressItem );
mMailCheckProgressItem =
ProgressManager::createProgressItem(
"MailCheckAccount" + name(),
i18n("Checking account: " ) + name(),
QString::null, // status
true, // can be canceled
useSSL() || useTLS() );
mMailCheckProgressItem->setTotalItems( mMailCheckFolders.count() );
connect ( mMailCheckProgressItem,
SIGNAL( progressItemCanceled( ProgressItem*) ),
this,
SLOT( slotMailCheckCanceled() ) );
QValueList<QGuardedPtr<KMFolder> >::Iterator it;
// first get the current count of unread-messages
mCountRemainChecks = 0;
mCountUnread = 0;
mUnreadBeforeCheck.clear();
for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); it++)
{
KMFolder *folder = *it;
if (folder && !folder->noContent())
{
mUnreadBeforeCheck[folder->idString()] = folder->countUnread();
}
}
bool gotError = false;
// then check for new mails
for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); it++)
{
KMFolder *folder = *it;
if (folder && !folder->noContent())
{
KMFolderImap *imapFolder = static_cast<KMFolderImap*>(folder->storage());
if (imapFolder->getContentState() != KMFolderImap::imapInProgress)
{
// connect the result-signals for new-mail-notification
mCountRemainChecks++;
if (imapFolder->isSelected()) {
connect(imapFolder, SIGNAL(folderComplete(KMFolderImap*, bool)),
this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
imapFolder->getFolder();
}
else {
connect(imapFolder, SIGNAL(numUnreadMsgsChanged(KMFolder*)),
this, SLOT(postProcessNewMail(KMFolder*)));
bool ok = imapFolder->processNewMail(interactive);
if (!ok)
{
// there was an error so cancel
mCountRemainChecks--;
gotError = true;
}
}
}
}
} // end for
if ( gotError )
slotUpdateFolderList();
}
//-----------------------------------------------------------------------------
void KMAcctImap::postProcessNewMail(KMFolderImap* folder, bool)
{
disconnect(folder, SIGNAL(folderComplete(KMFolderImap*, bool)),
this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
postProcessNewMail(static_cast<KMFolder*>(folder->folder()));
}
void KMAcctImap::postProcessNewMail( KMFolder * folder ) {
disconnect( folder->storage(), SIGNAL(numUnreadMsgsChanged(KMFolder*)),
this, SLOT(postProcessNewMail(KMFolder*)) );
if ( mMailCheckProgressItem ) {
mMailCheckProgressItem->incCompletedItems();
mMailCheckProgressItem->updateProgress();
mMailCheckProgressItem->setStatus( folder->prettyURL() + i18n(" completed") );
}
mCountRemainChecks--;
// count the unread messages
const QString folderId = folder->idString();
int newInFolder = folder->countUnread();
if ( mUnreadBeforeCheck.find( folderId ) != mUnreadBeforeCheck.end() )
newInFolder -= mUnreadBeforeCheck[folderId];
if ( newInFolder > 0 ) {
addToNewInFolder( folderId, newInFolder );
mCountUnread += newInFolder;
}
if (mCountRemainChecks == 0)
{
// all checks are done
mCountLastUnread = 0; // => mCountUnread - mCountLastUnread == new count
ImapAccountBase::postProcessNewMail();
mUnreadBeforeCheck.clear();
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::slotUpdateFolderList()
{
if (!mFolder || !mFolder->folder() || !mFolder->folder()->child() ||
makeConnection() != ImapAccountBase::Connected)
return;
QStringList strList;
mMailCheckFolders.clear();
kmkernel->imapFolderMgr()->createFolderList(&strList, &mMailCheckFolders,
mFolder->folder()->child(), QString::null, false);
// the new list
QValueList<QGuardedPtr<KMFolder> > includedFolders;
// check for excluded folders
QValueList<QGuardedPtr<KMFolder> >::Iterator it;
for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); it++)
{
KMFolderImap* folder = static_cast<KMFolderImap*>(((KMFolder*)(*it))->storage());
if (folder->includeInMailCheck())
includedFolders.append(*it);
}
mMailCheckFolders = includedFolders;
}
//-----------------------------------------------------------------------------
void KMAcctImap::listDirectory()
{
mFolder->listDirectory();
}
//-----------------------------------------------------------------------------
void KMAcctImap::setPrefixHook() {
if ( mFolder ) mFolder->setImapPath( prefix() );
}
//-----------------------------------------------------------------------------
void KMAcctImap::readConfig(KConfig& config)
{
ImapAccountBase::readConfig( config );
if ( checkExclude() ) {
disconnect(kmkernel->imapFolderMgr(), SIGNAL(changed()),
this, SLOT(slotUpdateFolderList()));
}
}
//-----------------------------------------------------------------------------
void KMAcctImap::slotMailCheckCanceled()
{
if( mMailCheckProgressItem )
mMailCheckProgressItem->setComplete();
cancelMailCheck();
}
//-----------------------------------------------------------------------------
FolderStorage* KMAcctImap::rootFolder()
{
return mFolder;
}
#include "kmacctimap.moc"
<|endoftext|> |
<commit_before>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
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 "traitcolumn.h"
#include "columntypes.h"
#include "viewcolumnset.h"
#include "dwarfmodel.h"
#include "dwarf.h"
#include "trait.h"
#include "gamedatareader.h"
TraitColumn::TraitColumn(const QString &title, const short &trait_id, ViewColumnSet *set, QObject *parent)
: ViewColumn(title, CT_TRAIT, set, parent)
, m_trait_id(trait_id)
, m_trait(0)
{
m_trait = GameDataReader::ptr()->get_trait(trait_id);
}
TraitColumn::TraitColumn(QSettings &s, ViewColumnSet *set, QObject *parent)
: ViewColumn(s, set, parent)
, m_trait_id(s.value("trait_id", -1).toInt())
, m_trait(0)
{
m_trait = GameDataReader::ptr()->get_trait(m_trait_id);
}
TraitColumn::TraitColumn(const TraitColumn &to_copy)
: ViewColumn(to_copy)
, m_trait_id(to_copy.m_trait_id)
, m_trait(to_copy.m_trait)
{}
QStandardItem *TraitColumn::build_cell(Dwarf *d) {
QStandardItem *item = init_cell(d);
short score = d->trait(m_trait_id);
if (score == -1) // not an active trait...
item->setText("");
else
item->setText(QString::number(score));
item->setData(CT_TRAIT, DwarfModel::DR_COL_TYPE);
item->setData(score, DwarfModel::DR_SORT_VALUE);
QString msg = "???";
if (m_trait)
msg = m_trait->level_message(score);
if (score == -1)
msg = "Not an active trait for this dwarf";
QString tooltip = QString("<h3>%1</h3>%2 (%3)<h4>%4</h4>")
.arg(m_title)
.arg(msg)
.arg(score)
.arg(d->nice_name());
item->setToolTip(tooltip);
return item;
}
QStandardItem *TraitColumn::build_aggregate(const QString &group_name, const QVector<Dwarf*> &dwarves) {
Q_UNUSED(group_name);
Q_UNUSED(dwarves);
QStandardItem *item = new QStandardItem;
item->setData(m_bg_color, DwarfModel::DR_DEFAULT_BG_COLOR);
return item;
}
<commit_msg> * treat inactive dwarf traits as a value of 50 rather than -1 (Fixed issue 149)<commit_after>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
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 "traitcolumn.h"
#include "columntypes.h"
#include "viewcolumnset.h"
#include "dwarfmodel.h"
#include "dwarf.h"
#include "trait.h"
#include "gamedatareader.h"
TraitColumn::TraitColumn(const QString &title, const short &trait_id, ViewColumnSet *set, QObject *parent)
: ViewColumn(title, CT_TRAIT, set, parent)
, m_trait_id(trait_id)
, m_trait(0)
{
m_trait = GameDataReader::ptr()->get_trait(trait_id);
}
TraitColumn::TraitColumn(QSettings &s, ViewColumnSet *set, QObject *parent)
: ViewColumn(s, set, parent)
, m_trait_id(s.value("trait_id", -1).toInt())
, m_trait(0)
{
m_trait = GameDataReader::ptr()->get_trait(m_trait_id);
}
TraitColumn::TraitColumn(const TraitColumn &to_copy)
: ViewColumn(to_copy)
, m_trait_id(to_copy.m_trait_id)
, m_trait(to_copy.m_trait)
{}
QStandardItem *TraitColumn::build_cell(Dwarf *d) {
QStandardItem *item = init_cell(d);
item->setData(CT_TRAIT, DwarfModel::DR_COL_TYPE);
short score = d->trait(m_trait_id);
QString msg = "???";
if (m_trait)
msg = m_trait->level_message(score);
if (score == -1) { // not an active trait...
item->setText("");
item->setData(50, DwarfModel::DR_SORT_VALUE);
msg = tr("Not an active trait for this dwarf");
} else {
item->setText(QString::number(score));
item->setData(score, DwarfModel::DR_SORT_VALUE);
}
QString tooltip = QString("<h3>%1</h3>%2 (%3)<h4>%4</h4>")
.arg(m_title)
.arg(msg)
.arg(score)
.arg(d->nice_name());
item->setToolTip(tooltip);
return item;
}
QStandardItem *TraitColumn::build_aggregate(const QString &group_name, const QVector<Dwarf*> &dwarves) {
Q_UNUSED(group_name);
Q_UNUSED(dwarves);
QStandardItem *item = new QStandardItem;
item->setData(m_bg_color, DwarfModel::DR_DEFAULT_BG_COLOR);
return item;
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <unordered_map>
#include "core/future.hh"
#include "net/api.hh"
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/shared_ptr.hh"
namespace rpc {
using id_type = int64_t;
struct SerializerConcept {
template<typename T>
future<> operator()(output_stream<char>& out, T&& v);
template<typename T>
future<> operator()(input_stream<char>& in, T& v);
// id_type and sstring are needed for compilation to succeed
future<> operator()(output_stream<char>& out, id_type& v);
future<> operator()(input_stream<char>& in, id_type& v);
future<> operator()(output_stream<char>& out, sstring& v);
future<> operator()(input_stream<char>& in, sstring& v);
};
struct client_info {
socket_address addr;
};
// MsgType is a type that holds type of a message. The type should be hashable
// and serializable. It is preferable to use enum for message types, but
// do not forget to provide hash function for it
template<typename Serializer, typename MsgType = uint32_t>
class protocol {
class connection {
protected:
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
future<> _output_ready = make_ready_future<>();
bool _error = false;
protocol& _proto;
public:
connection(connected_socket&& fd, protocol& proto) : _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf(_fd.output()), _proto(proto) {}
connection(protocol& proto) : _proto(proto) {}
// functions below are public because they are used by external heavily templated functions
// and I am not smart enough to know how to define them as friends
auto& in() { return _read_buf; }
auto& out() { return _write_buf; }
auto& out_ready() { return _output_ready; }
bool error() { return _error; }
auto& serializer() { return _proto._serializer; }
auto& get_protocol() { return _proto; }
};
friend connection;
public:
class server {
private:
protocol& _proto;
public:
class connection : public protocol::connection, public enable_lw_shared_from_this<connection> {
server& _server;
MsgType _type;
client_info _info;
public:
connection(server& s, connected_socket&& fd, socket_address&& addr, protocol& proto);
future<> process();
auto& info() { return _info; }
};
server(protocol& proto, ipv4_addr addr);
void accept(server_socket&& ss);
friend connection;
};
class client : public protocol::connection {
promise<> _connected;
id_type _message_id = 1;
id_type _rcv_msg_id = 0;
struct reply_handler_base {
virtual future<> operator()(client&, id_type) = 0;
};
public:
template<typename Reply, typename Func>
struct reply_handler final : reply_handler_base {
Func func;
Reply reply;
reply_handler(Func&& f) : func(std::move(f)) {}
virtual future<> operator()(client& client, id_type msg_id) override {
return func(reply, client, msg_id);
}
};
private:
std::unordered_map<id_type, std::unique_ptr<reply_handler_base>> _outstanding;
public:
client(protocol& proto, ipv4_addr addr);
auto next_message_id() { return _message_id++; }
void wait_for_reply(id_type id, std::unique_ptr<reply_handler_base>&& h) {
_outstanding.emplace(id, std::move(h));
}
};
friend server;
private:
using rpc_handler = std::function<future<>(lw_shared_ptr<typename server::connection>)>;
std::unordered_map<MsgType, rpc_handler> _handlers;
Serializer _serializer;
std::function<void(const sstring&)> _logger;
public:
protocol(Serializer&& serializer) : _serializer(std::forward<Serializer>(serializer)) {}
template<typename Func>
auto make_client(MsgType t);
// returns a function which type depends on Func
// if Func == Ret(Args...) then return function is
// future<Ret>(protocol::client&, Args...)
template<typename Func>
auto register_handler(MsgType t, Func&& func);
void set_logger(std::function<void(const sstring&)> logger) {
_logger = logger;
}
void log(const sstring& str) {
if (_logger) {
_logger(str);
_logger("\n");
}
}
void log(const client_info& info, id_type msg_id, const sstring& str) {
log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + " msg_id " + to_sstring(msg_id) + ": " + str);
}
private:
void register_receiver(MsgType t, rpc_handler&& handler) {
_handlers.emplace(t, std::move(handler));
}
};
class error : public std::runtime_error {
public:
error(const std::string& msg) : std::runtime_error(msg) {}
};
class closed_error : public error {
public:
closed_error() : error("connection is closed") {}
};
struct no_wait_type {};
// return this from a callback if client does not want to waiting for a reply
extern no_wait_type no_wait;
}
#include "rpc_impl.hh"
<commit_msg>rpc: add virtual destructor for reply_handler<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <unordered_map>
#include "core/future.hh"
#include "net/api.hh"
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/shared_ptr.hh"
namespace rpc {
using id_type = int64_t;
struct SerializerConcept {
template<typename T>
future<> operator()(output_stream<char>& out, T&& v);
template<typename T>
future<> operator()(input_stream<char>& in, T& v);
// id_type and sstring are needed for compilation to succeed
future<> operator()(output_stream<char>& out, id_type& v);
future<> operator()(input_stream<char>& in, id_type& v);
future<> operator()(output_stream<char>& out, sstring& v);
future<> operator()(input_stream<char>& in, sstring& v);
};
struct client_info {
socket_address addr;
};
// MsgType is a type that holds type of a message. The type should be hashable
// and serializable. It is preferable to use enum for message types, but
// do not forget to provide hash function for it
template<typename Serializer, typename MsgType = uint32_t>
class protocol {
class connection {
protected:
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
future<> _output_ready = make_ready_future<>();
bool _error = false;
protocol& _proto;
public:
connection(connected_socket&& fd, protocol& proto) : _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf(_fd.output()), _proto(proto) {}
connection(protocol& proto) : _proto(proto) {}
// functions below are public because they are used by external heavily templated functions
// and I am not smart enough to know how to define them as friends
auto& in() { return _read_buf; }
auto& out() { return _write_buf; }
auto& out_ready() { return _output_ready; }
bool error() { return _error; }
auto& serializer() { return _proto._serializer; }
auto& get_protocol() { return _proto; }
};
friend connection;
public:
class server {
private:
protocol& _proto;
public:
class connection : public protocol::connection, public enable_lw_shared_from_this<connection> {
server& _server;
MsgType _type;
client_info _info;
public:
connection(server& s, connected_socket&& fd, socket_address&& addr, protocol& proto);
future<> process();
auto& info() { return _info; }
};
server(protocol& proto, ipv4_addr addr);
void accept(server_socket&& ss);
friend connection;
};
class client : public protocol::connection {
promise<> _connected;
id_type _message_id = 1;
id_type _rcv_msg_id = 0;
struct reply_handler_base {
virtual future<> operator()(client&, id_type) = 0;
virtual ~reply_handler_base() {};
};
public:
template<typename Reply, typename Func>
struct reply_handler final : reply_handler_base {
Func func;
Reply reply;
reply_handler(Func&& f) : func(std::move(f)) {}
virtual future<> operator()(client& client, id_type msg_id) override {
return func(reply, client, msg_id);
}
virtual ~reply_handler() {}
};
private:
std::unordered_map<id_type, std::unique_ptr<reply_handler_base>> _outstanding;
public:
client(protocol& proto, ipv4_addr addr);
auto next_message_id() { return _message_id++; }
void wait_for_reply(id_type id, std::unique_ptr<reply_handler_base>&& h) {
_outstanding.emplace(id, std::move(h));
}
};
friend server;
private:
using rpc_handler = std::function<future<>(lw_shared_ptr<typename server::connection>)>;
std::unordered_map<MsgType, rpc_handler> _handlers;
Serializer _serializer;
std::function<void(const sstring&)> _logger;
public:
protocol(Serializer&& serializer) : _serializer(std::forward<Serializer>(serializer)) {}
template<typename Func>
auto make_client(MsgType t);
// returns a function which type depends on Func
// if Func == Ret(Args...) then return function is
// future<Ret>(protocol::client&, Args...)
template<typename Func>
auto register_handler(MsgType t, Func&& func);
void set_logger(std::function<void(const sstring&)> logger) {
_logger = logger;
}
void log(const sstring& str) {
if (_logger) {
_logger(str);
_logger("\n");
}
}
void log(const client_info& info, id_type msg_id, const sstring& str) {
log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + " msg_id " + to_sstring(msg_id) + ": " + str);
}
private:
void register_receiver(MsgType t, rpc_handler&& handler) {
_handlers.emplace(t, std::move(handler));
}
};
class error : public std::runtime_error {
public:
error(const std::string& msg) : std::runtime_error(msg) {}
};
class closed_error : public error {
public:
closed_error() : error("connection is closed") {}
};
struct no_wait_type {};
// return this from a callback if client does not want to waiting for a reply
extern no_wait_type no_wait;
}
#include "rpc_impl.hh"
<|endoftext|> |
<commit_before>#include "player.h"
void Player::update(const CarPosition& now) {
if (nticks == 0) {
// HACK. CI starts in random positions
// don't mess up speed etc starting in the middle of something
// just get prev ok during this tick
return;
}
curspeed = compute_travel(now);
estimate_coefs(now);
prevspeed = curspeed;
tottravel += curspeed;
}
void Player::estimate_coefs(const CarPosition& now) {
if (nticks == COEF_MEAS_TICKS) {
double initial_thrust = 1.0;
// start pos is not always 0; speed in tick delta units
double x1 = prevspeed;//prev.inPieceDistance;
double x2 = prevspeed+curspeed;//now.inPieceDistance;
// v1 = x1, as x0 = 0
double v2 = x2 - x1;
power = x1 / initial_thrust; // v += power * thrust, initially v zero so no drag
drag = (v2 - x1) / x1; // v2 = drag * v1 + accel, accel = increase in one step = x1
std::cout << "COEF: p=" << power << " d=" << drag << std::endl;
}
}
double Player::compute_travel(const CarPosition& now) const {
// TODO lane switching
double lanedist = track->lanedist[now.startLane];
double travel;
if (now.pieceIndex == prev.pieceIndex) {
travel = now.inPieceDistance - prev.inPieceDistance;
} else {
// changed piece between ticks
double last_remaining = track->track[prev.pieceIndex].travel(lanedist) - prev.inPieceDistance;
double in_this = now.inPieceDistance;
travel = last_remaining + in_this;
}
return travel;
}
double Player::compute_throttle(const CarPosition& now) const {
#if 0
return throttle_for_speed((nticks / 200) * topspeed() / 10.0);
#endif
// safest throttle based on all the future track.
// probably do not need to look ahead the whole track, but what the hell
double best_throttle = 1.0;
// track has >= 1 pieces for sure
for (size_t i = 0; i < track->track.size() - 1; i++) {
double thr = throttle_for_piece(now, i);
best_throttle = std::min(best_throttle, thr);
}
return best_throttle;
}
double Player::throttle_for_piece(const CarPosition& now, int lookahead) const {
int next = (now.pieceIndex + lookahead) % track->track.size();
// straights do not need braking
if (track->track[next].length != 0.0)
return 1.0;
double topspeed = speed_for_bend(track->track[next].radius);
if (lookahead == 0) // already in this bend
return throttle_for_speed(topspeed);
double dist_to_next = dist_to_piece(now, next);
int ticks = ticks_to_slow_down(curspeed, topspeed);
double brake_dist = brake_travel(curspeed, ticks);
if (dist_to_next > brake_dist)
return 1.0;
return 0.0;
}
double Player::dist_to_piece(const CarPosition& now, int target) const {
if (now.pieceIndex == target)
return 0.0;
double lanedist = track->lanedist[now.startLane]; // close enough estimate to hold current lane
double dist = track->track[now.pieceIndex].travel(lanedist) - now.inPieceDistance;
int idx = (now.pieceIndex + 1) % track->track.size();
while (idx != target) {
dist += track->track[idx].travel(lanedist);
idx = (idx + 1) % track->track.size();
}
return dist;
}
double Player::throttle_for_speed(double speed) const {
double thr = (speed - drag * curspeed) / power;
return std::min(std::max(thr, 0.0), 1.0);
}
double Player::topspeed() const {
// v_n+1 = v_n - (1-d)v_n + p*t
// 0 = -(1-d)v_n + p*t
return power * 1.0 / (1 - drag);
}
double Player::brake_travel(double startspeed, int ticks) const {
// sum of the first n terms of a geometric series
return (1 - std::pow(drag, ticks)) / (1 - drag) * startspeed;
}
int Player::ticks_to_slow_down(double cur, double target) const {
// reach slower speed from current:
// d^n * cur = target
// log d^n = log target / cur
return ceil(log(target / cur) / log(drag));
}
double Player::speed_for_bend(double radius) const {
return 0.62 * std::sqrt(radius);
}
int Player::next_bend(int curridx) const {
while (track->track[curridx].angle == 0)
curridx = (curridx + 1) % track->track.size();
return curridx;
}
void Player::endtick(const CarPosition& now) {
prev = now;
prevspeed = curspeed;
nticks++;
}
<commit_msg>print out max possible speed (terminal velocity)<commit_after>#include "player.h"
void Player::update(const CarPosition& now) {
if (nticks == 0) {
// HACK. CI starts in random positions
// don't mess up speed etc starting in the middle of something
// just get prev ok during this tick
return;
}
curspeed = compute_travel(now);
estimate_coefs(now);
prevspeed = curspeed;
tottravel += curspeed;
}
void Player::estimate_coefs(const CarPosition& now) {
if (nticks == COEF_MEAS_TICKS) {
double initial_thrust = 1.0;
// start pos is not always 0; speed in tick delta units
double x1 = prevspeed;//prev.inPieceDistance;
double x2 = prevspeed+curspeed;//now.inPieceDistance;
// v1 = x1, as x0 = 0
double v2 = x2 - x1;
power = x1 / initial_thrust; // v += power * thrust, initially v zero so no drag
drag = (v2 - x1) / x1; // v2 = drag * v1 + accel, accel = increase in one step = x1
double max = power / (1 - drag);
std::cout << "COEF: p=" << power << " d=" << drag << " maxspd=" << max << std::endl;
}
}
double Player::compute_travel(const CarPosition& now) const {
// TODO lane switching
double lanedist = track->lanedist[now.startLane];
double travel;
if (now.pieceIndex == prev.pieceIndex) {
travel = now.inPieceDistance - prev.inPieceDistance;
} else {
// changed piece between ticks
double last_remaining = track->track[prev.pieceIndex].travel(lanedist) - prev.inPieceDistance;
double in_this = now.inPieceDistance;
travel = last_remaining + in_this;
}
return travel;
}
double Player::compute_throttle(const CarPosition& now) const {
#if 0
return throttle_for_speed((nticks / 200) * topspeed() / 10.0);
#endif
// safest throttle based on all the future track.
// probably do not need to look ahead the whole track, but what the hell
double best_throttle = 1.0;
// track has >= 1 pieces for sure
for (size_t i = 0; i < track->track.size() - 1; i++) {
double thr = throttle_for_piece(now, i);
best_throttle = std::min(best_throttle, thr);
}
return best_throttle;
}
double Player::throttle_for_piece(const CarPosition& now, int lookahead) const {
int next = (now.pieceIndex + lookahead) % track->track.size();
// straights do not need braking
if (track->track[next].length != 0.0)
return 1.0;
double topspeed = speed_for_bend(track->track[next].radius);
if (lookahead == 0) // already in this bend
return throttle_for_speed(topspeed);
double dist_to_next = dist_to_piece(now, next);
int ticks = ticks_to_slow_down(curspeed, topspeed);
double brake_dist = brake_travel(curspeed, ticks);
if (dist_to_next > brake_dist)
return 1.0;
return 0.0;
}
double Player::dist_to_piece(const CarPosition& now, int target) const {
if (now.pieceIndex == target)
return 0.0;
double lanedist = track->lanedist[now.startLane]; // close enough estimate to hold current lane
double dist = track->track[now.pieceIndex].travel(lanedist) - now.inPieceDistance;
int idx = (now.pieceIndex + 1) % track->track.size();
while (idx != target) {
dist += track->track[idx].travel(lanedist);
idx = (idx + 1) % track->track.size();
}
return dist;
}
double Player::throttle_for_speed(double speed) const {
double thr = (speed - drag * curspeed) / power;
return std::min(std::max(thr, 0.0), 1.0);
}
double Player::topspeed() const {
// v_n+1 = v_n - (1-d)v_n + p*t
// 0 = -(1-d)v_n + p*t
return power * 1.0 / (1 - drag);
}
double Player::brake_travel(double startspeed, int ticks) const {
// sum of the first n terms of a geometric series
return (1 - std::pow(drag, ticks)) / (1 - drag) * startspeed;
}
int Player::ticks_to_slow_down(double cur, double target) const {
// reach slower speed from current:
// d^n * cur = target
// log d^n = log target / cur
return ceil(log(target / cur) / log(drag));
}
double Player::speed_for_bend(double radius) const {
return 0.62 * std::sqrt(radius);
}
int Player::next_bend(int curridx) const {
while (track->track[curridx].angle == 0)
curridx = (curridx + 1) % track->track.size();
return curridx;
}
void Player::endtick(const CarPosition& now) {
prev = now;
prevspeed = curspeed;
nticks++;
}
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the QtMediaHub project on http://www.gitorious.org.
Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Nokia Corporation (qt-info@nokia.com)**
You may use this file under the terms of the BSD license as follows:
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
****************************************************************************/
#include "httpclient.h"
#include <QtSql>
#include "backend.h"
#include "httpserver.h"
HttpClient::HttpClient(int sockfd, HttpServer *server, QObject *parent) :
QObject(parent)
{
m_server = server;
m_socket = new QTcpSocket(this);
if (!m_socket->setSocketDescriptor(sockfd)) {
emit error(m_socket->error());
return;
}
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(m_socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
}
void HttpClient::readClient()
{
if (m_socket->canReadLine()) {
QByteArray bytesRead = m_socket->readLine();
QStringList tokens = QString(bytesRead).split(QRegExp("[ \r\n][ \r\n]*"));
while(m_socket->canReadLine()) {
bytesRead = m_socket->readLine();
QList<QByteArray> lineTokens = bytesRead.split(':');
if (lineTokens.size() == 2) {
m_request.insert(lineTokens[0], lineTokens[1].trimmed().replace("\r\n",""));
}
}
qDebug() << m_request;
if (tokens[0] == "GET") {
m_get = tokens[1];
qDebug() << "GET" << m_get;
if (m_get.startsWith("/video"))
readVideoRequest();
else if(m_get.startsWith("/music"))
readMusicRequest();
else if(m_get.startsWith("/picture"))
readPictureRequest();
}
}
m_socket->close();
discardClient();
return;
}
void HttpClient::discardClient()
{
m_file.close();
m_socket->deleteLater();
emit disconnected();
qDebug() << "Connection closed";
}
void HttpClient::readVideoRequest()
{
QString id = m_get.right(m_get.length()-m_get.lastIndexOf("/")-1);
if (m_request.contains("Range")) {
QString offsetString = m_request.value("Range");
offsetString.remove(0, 6);
qint64 offset = offsetString.split("-").at(0).toLongLong();
sendPartial(getMediaUrl("video", id.toInt()).toLocalFile(), offset);
} else {
sendFile(getMediaUrl("video", id.toInt()).toLocalFile());
}
m_socket->close();
}
void HttpClient::readMusicRequest()
{
QString id = m_get.right(m_get.length()-m_get.lastIndexOf("/")-1);
sendFile(getMediaUrl("music", id.toInt()).toLocalFile());
m_socket->close();
}
void HttpClient::readPictureRequest()
{
}
void HttpClient::answerOk(qint64 length)
{
QByteArray answer;
answer += "HTTP/1.1 200 OK \r\n";
answer += "Server: QtMediaHub (Unix) \r\n";
answer += "Content-Length: " + QString::number(length) +"\r\n";
answer += "Connection: close \r\n";
answer += "Content-Type: application/octet-stream \r\n";
answer += "Accept-Ranges: bytes \r\n";
answer += "\r\n";
m_socket->write(answer);
m_socket->waitForBytesWritten();
}
void HttpClient::answerNotFound()
{
QByteArray answer;
answer += "HTTP/1.1 404 Not Found \r\n";
answer += "Server: QtMediaHub (Unix) \r\n";
answer += "Connection: close \r\n";
answer += "\r\n";
m_socket->write(answer);
m_socket->waitForBytesWritten();
}
QUrl HttpClient::getMediaUrl(QString mediaType, int id, QString field)
{
QSqlQuery query(Backend::instance()->mediaDatabase());
query.setForwardOnly(true);
QString queryString;
queryString.append("SELECT * FROM " + mediaType);
queryString.append(" WHERE id = " + QString::number(id) + "");
query.prepare(queryString);
if (!query.exec()) {
qWarning("Error executing query: %s", qPrintable(query.lastQuery()));
return QUrl();
}
// we should have just one result set
if (!query.next()) {
qWarning("No records found: %s", qPrintable(query.lastQuery()));
return QUrl();
}
return QUrl::fromEncoded(query.record().value(field).toByteArray());
}
bool HttpClient::sendFile(QString fileName)
{
int chunk = 1024*16;
qDebug() << "start send file";
m_file.setFileName(fileName);
m_file.open(QIODevice::ReadOnly);
if (!m_file.isOpen()) {
qDebug() << "could not open file" << m_file.fileName();
answerNotFound();
return false;
}
answerOk(m_file.size());
QByteArray ba;
ba.resize(chunk);
while (m_file.read(ba.data(), chunk) && m_socket->state() == QAbstractSocket::ConnectedState) {
m_socket->write(ba);
m_socket->waitForBytesWritten();
sleep(0.1);
}
if (m_socket->state() != QAbstractSocket::ConnectedState)
qDebug() << "fully sent connection closed";
return true;
}
bool HttpClient::sendPartial(QString fileName, qint64 offset)
{
int chunk = 1024*16;
m_file.setFileName(fileName);
m_file.open(QIODevice::ReadOnly);
if (!m_file.isOpen()) {
qDebug() << "could not open file" << m_file.fileName();
answerNotFound();
return false;
}
qDebug() << "sendPartial offset" << offset;
QByteArray ba;
ba.resize(chunk);
if (!m_file.seek(offset)) {
qDebug() << "could not seek to offset";
return false;
}
QByteArray answer = "";
answer += "HTTP/1.1 206 Partial content \r\n";
answer += "Server: QtMediaHub (Unix) \r\n";
answer += "Content-Length: " + QString::number(m_file.size()-offset) +"\r\n";
answer += "Connection: close \r\n";
answer += "Content-Range: bytes " + QString::number(offset) + "-" + QString::number(m_file.size()-1) + "/" + QString::number(m_file.size()) + " \t\n";
answer += "Content-Type: application/octet-stream \r\n";
answer += "Accept-Ranges: bytes \r\n";
answer += "\r\n";
m_socket->write(answer);
while (m_file.read(ba.data(), chunk) && m_socket->state() == QAbstractSocket::ConnectedState) {
m_socket->write(ba);
m_socket->waitForBytesWritten();
sleep(0.1);
}
qDebug() << "sendPartial sent" << (m_socket->state() == QAbstractSocket::ConnectedState);
return true;
}
<commit_msg>make music seekable<commit_after>/****************************************************************************
This file is part of the QtMediaHub project on http://www.gitorious.org.
Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Nokia Corporation (qt-info@nokia.com)**
You may use this file under the terms of the BSD license as follows:
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
****************************************************************************/
#include "httpclient.h"
#include <QtSql>
#include "backend.h"
#include "httpserver.h"
HttpClient::HttpClient(int sockfd, HttpServer *server, QObject *parent) :
QObject(parent)
{
m_server = server;
m_socket = new QTcpSocket(this);
if (!m_socket->setSocketDescriptor(sockfd)) {
emit error(m_socket->error());
return;
}
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(m_socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
}
void HttpClient::readClient()
{
if (m_socket->canReadLine()) {
QByteArray bytesRead = m_socket->readLine();
QStringList tokens = QString(bytesRead).split(QRegExp("[ \r\n][ \r\n]*"));
while(m_socket->canReadLine()) {
bytesRead = m_socket->readLine();
QList<QByteArray> lineTokens = bytesRead.split(':');
if (lineTokens.size() == 2) {
m_request.insert(lineTokens[0], lineTokens[1].trimmed().replace("\r\n",""));
}
}
qDebug() << m_request;
if (tokens[0] == "GET") {
m_get = tokens[1];
qDebug() << "GET" << m_get;
if (m_get.startsWith("/video"))
readVideoRequest();
else if(m_get.startsWith("/music"))
readMusicRequest();
else if(m_get.startsWith("/picture"))
readPictureRequest();
}
}
m_socket->close();
discardClient();
return;
}
void HttpClient::discardClient()
{
m_file.close();
m_socket->deleteLater();
emit disconnected();
qDebug() << "Connection closed";
}
void HttpClient::readVideoRequest()
{
QString id = m_get.right(m_get.length()-m_get.lastIndexOf("/")-1);
if (m_request.contains("Range")) {
QString offsetString = m_request.value("Range");
offsetString.remove(0, 6);
qint64 offset = offsetString.split("-").at(0).toLongLong();
sendPartial(getMediaUrl("video", id.toInt()).toLocalFile(), offset);
} else {
sendFile(getMediaUrl("video", id.toInt()).toLocalFile());
}
m_socket->close();
}
void HttpClient::readMusicRequest()
{
QString id = m_get.right(m_get.length()-m_get.lastIndexOf("/")-1);
if (m_request.contains("Range")) {
QString offsetString = m_request.value("Range");
offsetString.remove(0, 6);
qint64 offset = offsetString.split("-").at(0).toLongLong();
sendPartial(getMediaUrl("music", id.toInt()).toLocalFile(), offset);
} else {
sendFile(getMediaUrl("music", id.toInt()).toLocalFile());
}
m_socket->close();
}
void HttpClient::readPictureRequest()
{
}
void HttpClient::answerOk(qint64 length)
{
QByteArray answer;
answer += "HTTP/1.1 200 OK \r\n";
answer += "Server: QtMediaHub (Unix) \r\n";
answer += "Content-Length: " + QString::number(length) +"\r\n";
answer += "Connection: close \r\n";
answer += "Content-Type: application/octet-stream \r\n";
answer += "Accept-Ranges: bytes \r\n";
answer += "\r\n";
m_socket->write(answer);
m_socket->waitForBytesWritten();
}
void HttpClient::answerNotFound()
{
QByteArray answer;
answer += "HTTP/1.1 404 Not Found \r\n";
answer += "Server: QtMediaHub (Unix) \r\n";
answer += "Connection: close \r\n";
answer += "\r\n";
m_socket->write(answer);
m_socket->waitForBytesWritten();
}
QUrl HttpClient::getMediaUrl(QString mediaType, int id, QString field)
{
QSqlQuery query(Backend::instance()->mediaDatabase());
query.setForwardOnly(true);
QString queryString;
queryString.append("SELECT * FROM " + mediaType);
queryString.append(" WHERE id = " + QString::number(id) + "");
query.prepare(queryString);
if (!query.exec()) {
qWarning("Error executing query: %s", qPrintable(query.lastQuery()));
return QUrl();
}
// we should have just one result set
if (!query.next()) {
qWarning("No records found: %s", qPrintable(query.lastQuery()));
return QUrl();
}
return QUrl::fromEncoded(query.record().value(field).toByteArray());
}
bool HttpClient::sendFile(QString fileName)
{
int chunk = 1024*16;
qDebug() << "start send file";
m_file.setFileName(fileName);
m_file.open(QIODevice::ReadOnly);
if (!m_file.isOpen()) {
qDebug() << "could not open file" << m_file.fileName();
answerNotFound();
return false;
}
answerOk(m_file.size());
QByteArray ba;
ba.resize(chunk);
while (m_file.read(ba.data(), chunk) && m_socket->state() == QAbstractSocket::ConnectedState) {
m_socket->write(ba);
m_socket->waitForBytesWritten();
sleep(0.1);
}
if (m_socket->state() != QAbstractSocket::ConnectedState)
qDebug() << "fully sent connection closed";
return true;
}
bool HttpClient::sendPartial(QString fileName, qint64 offset)
{
int chunk = 1024*16;
m_file.setFileName(fileName);
m_file.open(QIODevice::ReadOnly);
if (!m_file.isOpen()) {
qDebug() << "could not open file" << m_file.fileName();
answerNotFound();
return false;
}
qDebug() << "sendPartial offset" << offset;
QByteArray ba;
ba.resize(chunk);
if (!m_file.seek(offset)) {
qDebug() << "could not seek to offset";
return false;
}
QByteArray answer = "";
answer += "HTTP/1.1 206 Partial content \r\n";
answer += "Server: QtMediaHub (Unix) \r\n";
answer += "Content-Length: " + QString::number(m_file.size()-offset) +"\r\n";
answer += "Connection: close \r\n";
answer += "Content-Range: bytes " + QString::number(offset) + "-" + QString::number(m_file.size()-1) + "/" + QString::number(m_file.size()) + " \t\n";
answer += "Content-Type: application/octet-stream \r\n";
answer += "Accept-Ranges: bytes \r\n";
answer += "\r\n";
m_socket->write(answer);
while (m_file.read(ba.data(), chunk) && m_socket->state() == QAbstractSocket::ConnectedState) {
m_socket->write(ba);
m_socket->waitForBytesWritten();
sleep(0.1);
}
qDebug() << "sendPartial sent" << (m_socket->state() == QAbstractSocket::ConnectedState);
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#define DEF_REGMEMBER(n, clazz, elem, getter) ::rs::LuaImport::RegisterMember<getter,clazz>(lsc, BOOST_PP_STRINGIZE(elem), &clazz::elem);
#define DEF_REGMEMBER_HDL(n, data, elem) DEF_REGMEMBER(n, BOOST_PP_SEQ_ELEM(1,data), elem, ::rs::LI_GetHandle<BOOST_PP_SEQ_ELEM(0,data)>)
#define DEF_REGMEMBER_PTR(n, clazz, elem) DEF_REGMEMBER(n, clazz, elem, ::rs::LI_GetPtr<clazz>)
#define DEF_LUAIMPORT_BASE namespace rs{ \
class LuaState; \
namespace lua{ \
template <class T> \
void LuaExport(LuaState& lsc, T*); \
template <class T> \
const char* LuaName(T*); \
}}
#define DEF_LUAIMPORT(clazz) \
DEF_LUAIMPORT_BASE \
namespace rs { \
namespace lua { \
template <> \
const char* LuaName(clazz*); \
template <> \
void LuaExport(LuaState& lsc, clazz*); \
}}
#define DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, base, seq_member, seq_method, seq_ctor, makeobj) \
namespace rs{ namespace lua{ \
template <> \
const char* LuaName(clazz*) { return #class_name; } \
template <> \
void LuaExport(LuaState& lsc, clazz*) { \
lsc.getGlobal(::rs::luaNS::DerivedHandle); \
lsc.getGlobal(base); \
lsc.push(#class_name); \
lsc.call(2,1); \
lsc.push(::rs::luaNS::objBase::_New); \
lsc.push(makeobj<BOOST_PP_SEQ_ENUM((mgr)(clazz)seq_ctor)>); \
lsc.setTable(-3); \
\
lsc.getField(-1, ::rs::luaNS::objBase::ValueR); \
lsc.getField(-2, ::rs::luaNS::objBase::ValueW); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_HDL, (typename mgr::data_type)(clazz), seq_member) \
lsc.pop(2); \
\
lsc.getField(-1, ::rs::luaNS::objBase::Func); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_HDL, (typename mgr::data_type)(clazz), seq_method) \
lsc.pop(1); \
\
lsc.setGlobal(#class_name); \
} \
}}
#define DEF_LUAIMPLEMENT_HDL(mgr, clazz, class_name, base, seq_member, seq_method, seq_ctor) \
DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, base, seq_member, seq_method, seq_ctor, ::rs::MakeHandle)
#define DEF_LUAIMPLEMENT_HDL_NOBASE(mgr, clazz, class_name, seq_member, seq_method, seq_ctor) \
DEF_LUAIMPLEMENT_HDL(mgr, clazz, class_name, ::rs::luaNS::ObjectBase, seq_member, seq_method, seq_ctor)
#define DEF_LUAIMPLEMENT_HDL_NOCTOR(mgr, clazz, class_name, base, seq_member, seq_method) \
DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, base, seq_member, seq_method, NOTHING, ::rs::MakeHandle_Fake)
#define DEF_LUAIMPLEMENT_HDL_NOBASE_NOCTOR(mgr, clazz, class_name, seq_member, seq_method) \
DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, ::rs::luaNS::ObjectBase, seq_member, seq_method, NOTHING, ::rs::MakeHandle_Fake)
#define DEF_LUAIMPLEMENT_PTR(clazz, class_name, seq_member, seq_method) \
namespace rs{ namespace lua{ \
template <> \
const char* LuaName(clazz*) { return #class_name; } \
template <> \
void LuaExport(LuaState& lsc, clazz*) { \
lsc.getGlobal(::rs::luaNS::DerivedHandle); \
lsc.getGlobal(::rs::luaNS::ObjectBase); \
lsc.push(#class_name); \
lsc.call(2,1); \
\
lsc.getField(-1, ::rs::luaNS::objBase::ValueR); \
lsc.getField(-2, ::rs::luaNS::objBase::ValueW); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_PTR, clazz, seq_member) \
lsc.pop(2); \
\
lsc.getField(-1, ::rs::luaNS::objBase::Func); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_PTR, clazz, seq_method) \
lsc.pop(1); \
\
lsc.setGlobal(#class_name); \
} \
}}
<commit_msg>LuaExport: クラスがLuaExport()というstaticメソッドを持っていればエクスポート時にそれを呼ぶ仕様とした<commit_after>#pragma once
#define DEF_REGMEMBER(n, clazz, elem, getter) ::rs::LuaImport::RegisterMember<getter,clazz>(lsc, BOOST_PP_STRINGIZE(elem), &clazz::elem);
#define DEF_REGMEMBER_HDL(n, data, elem) DEF_REGMEMBER(n, BOOST_PP_SEQ_ELEM(1,data), elem, ::rs::LI_GetHandle<BOOST_PP_SEQ_ELEM(0,data)>)
#define DEF_REGMEMBER_PTR(n, clazz, elem) DEF_REGMEMBER(n, clazz, elem, ::rs::LI_GetPtr<clazz>)
#define DEF_LUAIMPORT_BASE namespace rs{ \
class LuaState; \
namespace lua{ \
template <class T> \
void LuaExport(LuaState& lsc, T*); \
template <class T> \
const char* LuaName(T*); \
}}
#define DEF_LUAIMPORT(clazz) \
DEF_LUAIMPORT_BASE \
namespace rs { \
namespace lua { \
template <> \
const char* LuaName(clazz*); \
template <> \
void LuaExport(LuaState& lsc, clazz*); \
}}
#include "spinner/check_macro.hpp"
namespace rs {
DEF_HASMETHOD(LuaExport)
class LuaState;
template <class T>
void CallLuaExport(LuaState& lsc, std::true_type) {
T::LuaExport(lsc);
}
template <class T>
void CallLuaExport(LuaState&, std::false_type) {}
}
#define DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, base, seq_member, seq_method, seq_ctor, makeobj) \
namespace rs{ namespace lua{ \
template <> \
const char* LuaName(clazz*) { return #class_name; } \
template <> \
void LuaExport(LuaState& lsc, clazz*) { \
lsc.getGlobal(::rs::luaNS::DerivedHandle); \
lsc.getGlobal(base); \
lsc.push(#class_name); \
lsc.call(2,1); \
lsc.push(::rs::luaNS::objBase::_New); \
lsc.push(makeobj<BOOST_PP_SEQ_ENUM((mgr)(clazz)seq_ctor)>); \
lsc.setTable(-3); \
\
lsc.getField(-1, ::rs::luaNS::objBase::ValueR); \
lsc.getField(-2, ::rs::luaNS::objBase::ValueW); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_HDL, (typename mgr::data_type)(clazz), seq_member) \
lsc.pop(2); \
\
lsc.getField(-1, ::rs::luaNS::objBase::Func); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_HDL, (typename mgr::data_type)(clazz), seq_method) \
lsc.pop(1); \
\
CallLuaExport<clazz>(lsc, rs::HasMethod_LuaExport_t<clazz>()); \
lsc.setGlobal(#class_name); \
} \
}}
#define DEF_LUAIMPLEMENT_HDL(mgr, clazz, class_name, base, seq_member, seq_method, seq_ctor) \
DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, base, seq_member, seq_method, seq_ctor, ::rs::MakeHandle)
#define DEF_LUAIMPLEMENT_HDL_NOBASE(mgr, clazz, class_name, seq_member, seq_method, seq_ctor) \
DEF_LUAIMPLEMENT_HDL(mgr, clazz, class_name, ::rs::luaNS::ObjectBase, seq_member, seq_method, seq_ctor)
#define DEF_LUAIMPLEMENT_HDL_NOCTOR(mgr, clazz, class_name, base, seq_member, seq_method) \
DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, base, seq_member, seq_method, NOTHING, ::rs::MakeHandle_Fake)
#define DEF_LUAIMPLEMENT_HDL_NOBASE_NOCTOR(mgr, clazz, class_name, seq_member, seq_method) \
DEF_LUAIMPLEMENT_HDL_IMPL(mgr, clazz, class_name, ::rs::luaNS::ObjectBase, seq_member, seq_method, NOTHING, ::rs::MakeHandle_Fake)
#define DEF_LUAIMPLEMENT_PTR(clazz, class_name, seq_member, seq_method) \
namespace rs{ namespace lua{ \
template <> \
const char* LuaName(clazz*) { return #class_name; } \
template <> \
void LuaExport(LuaState& lsc, clazz*) { \
lsc.getGlobal(::rs::luaNS::DerivedHandle); \
lsc.getGlobal(::rs::luaNS::ObjectBase); \
lsc.push(#class_name); \
lsc.call(2,1); \
\
lsc.getField(-1, ::rs::luaNS::objBase::ValueR); \
lsc.getField(-2, ::rs::luaNS::objBase::ValueW); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_PTR, clazz, seq_member) \
lsc.pop(2); \
\
lsc.getField(-1, ::rs::luaNS::objBase::Func); \
BOOST_PP_SEQ_FOR_EACH(DEF_REGMEMBER_PTR, clazz, seq_method) \
lsc.pop(1); \
\
CallLuaExport<clazz>(lsc, rs::HasMethod_LuaExport_t<clazz>()); \
lsc.setGlobal(#class_name); \
} \
}}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "Cutie.hpp"
//#include "Main.hpp"
enum Move {ROCK, PAPER, SCISSORS};
// void getPlayerTurn(enum Move & temp);
// void outputScore(int myScore, int theirScore);
// void updateScore(bool winner, int & myScore, int & theirScore);
void getPlayerTurn(Move & temp)
{
int choice = 1;
std::cout << "Please enter your move!" << std::endl;
std::cout << "1: ROCK" << std::endl;
std::cout << "2: PAPER" << std::endl;
std::cout << "3: SCISSORS!" << std::endl;
std::cin >> choice;
if (choice == 1) {
temp = ROCK;
}
else if (choice == 2) {
temp = PAPER;
}
else {
temp = SCISSORS;
}
}
void outputScore(int myScore, int theirScore)
{
std::cout << "YOU: " << myScore << std::endl;
std::cout << "OPPONENT: " << theirScore << std:: endl;
}
void updateScore(bool winner, int & myScore, int & theirScore)
{
if (winner) {
myScore++;
return;
}
theirScore++;
return;
}
// bool compareTurn(Move player){
// }
int main(int argc, char *argv[])
{
//cutie::connect();
//if(cutie::connect(address, timeout)) {
bool gameStarted = true;//gameInit(0,0);
bool gameActive = true;
if (gameStarted) {
int myScore = 0;
int theirScore = 0;
bool winner = false;
Move myTurn = ROCK;
Move theirTurn = ROCK;
while (gameActive) {
outputScore(myScore, theirScore);
getPlayerTurn(myTurn);
//theirTurn = cutie::doTurn(myTurn);
if (myTurn == theirTurn) {
winner = false;
}
else if (myTurn == ROCK) {
winner = (theirTurn == SCISSORS)? true : false;
}
else if (myTurn == PAPER) {
winner = (theirTurn == ROCK)? true : false;
}
else {
winner = (theirTurn == PAPER)? true : false;
}
updateScore(winner, myScore, theirScore);
}
}
//}
return 0;
}
<commit_msg>Added choice menu<commit_after>#include <iostream>
#include <string>
#include "Cutie.hpp"
//#include "Main.hpp"
enum Move {
ROCK,
PAPER,
SCISSORS
};
enum SessionType {
JOIN,
CREATE
};
// void getPlayerTurn(enum Move & temp);
// void outputScore(int myScore, int theirScore);
// void updateScore(bool winner, int & myScore, int & theirScore);
//
int choice()
{
int res = 0;
std::cout << "Would you like to create a game or join a game?" << endl;
std::cout << "1: Join\n2:Create\n> ";
std::cin >> res;
cin >> res;
cin.clear();
cin.ignore(256, '\n');
switch (res) {
case 1:
return JOIN;
case 2:
return CREATE;
default:
return -1;
}
}
void getPlayerTurn(Move& temp)
{
int choice = 1;
std::cout << "Please enter your move!" << std::endl;
std::cout << "1: ROCK" << std::endl;
std::cout << "2: PAPER" << std::endl;
std::cout << "3: SCISSORS!" << std::endl;
std::cin >> choice;
if (choice == 1) {
temp = ROCK;
}
else if (choice == 2) {
temp = PAPER;
}
else {
temp = SCISSORS;
}
}
void outputScore(int myScore, int theirScore)
{
std::cout << "YOU: " << myScore << std::endl;
std::cout << "OPPONENT: " << theirScore << std:: endl;
}
void updateScore(bool winner, int & myScore, int & theirScore)
{
if (winner) {
myScore++;
return;
}
theirScore++;
return;
}
// bool compareTurn(Move player){
// }
int main(int argc, char *argv[])
{
SessionType type = choice();
//cutie::connect();
//if(cutie::connect(address, timeout)) {
bool gameStarted = true;//gameInit(0,0);
bool gameActive = true;
if (gameStarted) {
int myScore = 0;
int theirScore = 0;
bool winner = false;
Move myTurn = ROCK;
Move theirTurn = ROCK;
while (gameActive) {
outputScore(myScore, theirScore);
getPlayerTurn(myTurn);
//theirTurn = cutie::doTurn(myTurn);
if (myTurn == theirTurn) {
winner = false;
}
else if (myTurn == ROCK) {
winner = (theirTurn == SCISSORS)? true : false;
}
else if (myTurn == PAPER) {
winner = (theirTurn == ROCK)? true : false;
}
else {
winner = (theirTurn == PAPER)? true : false;
}
updateScore(winner, myScore, theirScore);
}
}
//}
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************
Purpose:
Look for a "core" file at a given location. Return TRUE if it
exists and appears complete and correct, and FALSE otherwise.
The SUN core consists of a header, the data and stack segments
and finally the uarea. We check the magic number in the header
first. If that's OK we then calculate what the size of the
core should be using the size of the header, the sizes of the
data and stack areas recorded in the header and the size of the
uarea as defined in "sys/param.h". We then compare this
calculation with the actual size of the file.
Portability:
This code depends upon the core format for SUNOS4.1 systems,
and is not portable to other systems.
Modified for Solaris by : Dhaval N. Shah
University of Wisconsin, Madison
** Computer Sciences Department
******************************************************************/
#define _ALL_SOURCE
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_constants.h"
#include "condor_jobqueue.h"
#include <sys/file.h>
#include <sys/core.h>
#include <sys/param.h>
#include "proto.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#if defined(Solaris)
#define UPAGES 4
#define NBPG 0x1000 /*couldnt get this val from header files. Rough
estimate from Suns header files - Raghu */
#undef CORE_MAGIC
#if defined(X86)
#define CORE_MAGIC 0x7f454c46 /* at least, this is the magic for my
core file - Jim B. */
#else
#define CORE_MAGIC 0x464c457f
#endif
#endif
const int UAREA_SIZE = UPAGES * NBPG;
const int HEADER_SIZE = sizeof(struct core);
int
core_is_valid( char *name )
{
struct core header;
int fd;
int total_size;
off_t file_size;
dprintf( D_ALWAYS,
"Analyzing core file \"%s\" for existence and completeness\n", name
);
if( (fd=open(name,O_RDONLY)) < 0 ) {
dprintf( D_ALWAYS, "Can't open core file \"%s\"", name );
return FALSE;
}
if( read(fd,(char *)&header,HEADER_SIZE) != HEADER_SIZE ) {
dprintf( D_ALWAYS, "Can't read header from core file\n" );
(void)close( fd );
return FALSE;
}
file_size = lseek( fd, (off_t)0, SEEK_END );
(void)close( fd );
if( header.c_magic != CORE_MAGIC ) {
dprintf( D_ALWAYS,
"Core file - bad magic number (0x%x)\n", header.c_magic
);
return FALSE;
}
dprintf( D_ALWAYS,
"Core file - magic number OK\n"
);
/* the size test is bogus on Solaris -- there is something wrong
with the header information -- I'm taking it out. -Jim B. */
/* total_size = header.c_len + header.c_dsize + header.c_ssize + UAREA_SIZE;
if( file_size != total_size ) {
dprintf( D_ALWAYS,
"file_size should be %d, but is %d\n", total_size, file_size
);
return FALSE;
} else {
dprintf( D_ALWAYS,
"Core file_size of %d is correct\n", file_size
); */
return TRUE;
/* } */
#if 0
dprintf( D_ALWAYS, "c_len = %d bytes\n", header.c_len );
dprintf( D_ALWAYS, "c_dsize = %d bytes\n", header.c_dsize );
dprintf( D_ALWAYS, "c_ssize = %d bytes\n", header.c_ssize );
dprintf( D_ALWAYS, "UAREA_SIZE = %d bytes\n", UAREA_SIZE );
dprintf( D_ALWAYS, "total_size = %d bytes\n", total_size );
#endif
}
<commit_msg>I had the corefile magic numbers exactly backwards for x86 Solaris vs. sparc Solaris. This update should set the numbers straight.<commit_after>/****************************************************************
Purpose:
Look for a "core" file at a given location. Return TRUE if it
exists and appears complete and correct, and FALSE otherwise.
The SUN core consists of a header, the data and stack segments
and finally the uarea. We check the magic number in the header
first. If that's OK we then calculate what the size of the
core should be using the size of the header, the sizes of the
data and stack areas recorded in the header and the size of the
uarea as defined in "sys/param.h". We then compare this
calculation with the actual size of the file.
Portability:
This code depends upon the core format for SUNOS4.1 systems,
and is not portable to other systems.
Modified for Solaris by : Dhaval N. Shah
University of Wisconsin, Madison
** Computer Sciences Department
******************************************************************/
#define _ALL_SOURCE
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_constants.h"
#include "condor_jobqueue.h"
#include <sys/file.h>
#include <sys/core.h>
#include <sys/param.h>
#include "proto.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#if defined(Solaris)
#define UPAGES 4
#define NBPG 0x1000 /*couldnt get this val from header files. Rough
estimate from Suns header files - Raghu */
#undef CORE_MAGIC
#if defined(X86)
#define CORE_MAGIC 0x464c457f /* at least, this is the magic for my
core file - Jim B. */
#else
#define CORE_MAGIC 0x7f454c46
#endif
#endif
const int UAREA_SIZE = UPAGES * NBPG;
const int HEADER_SIZE = sizeof(struct core);
int
core_is_valid( char *name )
{
struct core header;
int fd;
int total_size;
off_t file_size;
dprintf( D_ALWAYS,
"Analyzing core file \"%s\" for existence and completeness\n", name
);
if( (fd=open(name,O_RDONLY)) < 0 ) {
dprintf( D_ALWAYS, "Can't open core file \"%s\"", name );
return FALSE;
}
if( read(fd,(char *)&header,HEADER_SIZE) != HEADER_SIZE ) {
dprintf( D_ALWAYS, "Can't read header from core file\n" );
(void)close( fd );
return FALSE;
}
file_size = lseek( fd, (off_t)0, SEEK_END );
(void)close( fd );
if( header.c_magic != CORE_MAGIC ) {
dprintf( D_ALWAYS,
"Core file - bad magic number (0x%x)\n", header.c_magic
);
return FALSE;
}
dprintf( D_ALWAYS,
"Core file - magic number OK\n"
);
/* the size test is bogus on Solaris -- there is something wrong
with the header information -- I'm taking it out. -Jim B. */
/* total_size = header.c_len + header.c_dsize + header.c_ssize + UAREA_SIZE;
if( file_size != total_size ) {
dprintf( D_ALWAYS,
"file_size should be %d, but is %d\n", total_size, file_size
);
return FALSE;
} else {
dprintf( D_ALWAYS,
"Core file_size of %d is correct\n", file_size
); */
return TRUE;
/* } */
#if 0
dprintf( D_ALWAYS, "c_len = %d bytes\n", header.c_len );
dprintf( D_ALWAYS, "c_dsize = %d bytes\n", header.c_dsize );
dprintf( D_ALWAYS, "c_ssize = %d bytes\n", header.c_ssize );
dprintf( D_ALWAYS, "UAREA_SIZE = %d bytes\n", UAREA_SIZE );
dprintf( D_ALWAYS, "total_size = %d bytes\n", total_size );
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer;
// redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution;
// neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Copyright (c) 2015-2016 ARM Limited
// All rights reserved.
//
// The license below extends only to copyright in the software and shall
// not be construed as granting a license to any other intellectual
// property including but not limited to intellectual property relating
// to a hardware implementation of the functionality of the software
// licensed hereunder. You may use the software subject to the license
// terms below provided that you ensure that this notice is replicated
// unmodified and in its entirety in all distributions of the software,
// modified or unmodified, in source code or in binary form.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer;
// redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution;
// neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Copyright 2009-2014 Sandia Coporation. Under the terms
// of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2014, Sandia Corporation
// All rights reserved.
//
// For license information, see the LICENSE file in the current directory.
#include <sst/core/sst_config.h>
#include <sst/core/componentInfo.h>
#include <sst/core/interfaces/simpleMem.h>
#include <sst/elements/memHierarchy/memEvent.h>
#include <sst/elements/memHierarchy/memTypes.h>
#include <sst/elements/memHierarchy/util.h>
#include <Python.h> // Before serialization to prevent spurious warnings
#include "gem5.hh"
#include "util.hh"
// System headers
#include <algorithm>
#include <fstream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
// gem5 Headers
#include <sim/core.hh>
#include <sim/init.hh>
#include <sim/init_signals.hh>
#include <sim/root.hh>
#include <sim/system.hh>
#include <sim/sim_events.hh>
#include <sim/sim_object.hh>
#include <base/logging.hh>
#include <base/debug.hh>
#include <base/pollevent.hh>
#include <base/types.hh>
#include <sim/async.hh>
#include <sim/eventq.hh>
#include <sim/sim_exit.hh>
#include <sim/stat_control.hh>
#include <sst/outgoing_request_bridge.hh>
#include <cassert>
#ifdef fatal // gem5 sets this
#undef fatal
#endif
// More SST Headers
#include <core/timeConverter.h>
namespace py = pybind11;
gem5Component::gem5Component(SST::ComponentId_t id, SST::Params& params):
SST::Component(id), threadInitialized(false)
{
output.init("gem5Component-" + getName() + "->", 1, 0,
SST::Output::STDOUT);
std::string cpu_frequency = params.find<std::string>("frequency", "");
if (cpu_frequency.empty()) {
output.fatal(
CALL_INFO, -1, "The frequency of the CPU must be specified.\n"
);
}
// Register a handler to be called on a set frequency.
timeConverter = registerClock(
cpu_frequency,
new SST::Clock::Handler<gem5Component>(this, &gem5Component::clockTick)
);
// "cmd" -> gem5's Python
std::string cmd = params.find<std::string>("cmd", "");
if (cmd.empty()) {
output.fatal(
CALL_INFO, -1, "Component %s must have a 'cmd' parameter.\n",
getName().c_str()
);
}
// Telling SST the command line call to gem5
args.push_back(const_cast<char*>("sst.x"));
splitCommandArgs(cmd, args);
output.output(CALL_INFO, "Command string: [sst.x %s]\n", cmd.c_str());
for (size_t i = 0; i < args.size(); ++i) {
output.output(CALL_INFO, " Arg [%02zu] = %s\n", i, args[i]);
}
// Parsing and setting gem5 debug flags
std::string gem5_debug_flags = params.find<std::string>("debug_flags", "");
for (auto const debug_flag: tokenizeString(gem5_debug_flags, {' ', ','})) {
output.output(CALL_INFO, "Debug flag += %s\n", debug_flag.c_str());
gem5::setDebugFlag(debug_flag.c_str());
}
registerAsPrimaryComponent();
primaryComponentDoNotEndSim();
systemPort = \
loadUserSubComponent<SSTResponderSubComponent>("system_port",0);
cachePort = \
loadUserSubComponent<SSTResponderSubComponent>("cache_port", 0);
systemPort->setTimeConverter(timeConverter);
systemPort->setOutputStream(&(output));
cachePort->setTimeConverter(timeConverter);
cachePort->setOutputStream(&(output));
}
gem5Component::~gem5Component()
{
}
void
gem5Component::init(unsigned phase)
{
output.output(CALL_INFO," init phase: %u\n", phase);
if (phase == 0) {
initPython(args.size(), &args[0]);
const std::vector<std::string> m5_instantiate_commands = {
"m5.instantiate()"
};
execPythonCommands(m5_instantiate_commands);
// calling SimObject.startup()
const std::vector<std::string> simobject_setup_commands = {
"import atexit",
"import _m5",
"root = m5.objects.Root.getInstance()",
"for obj in root.descendants(): obj.startup()",
"atexit.register(m5.stats.dump)",
"atexit.register(_m5.core.doExitCleanup)",
"m5.stats.reset()"
};
execPythonCommands(simobject_setup_commands);
// find the corresponding SimObject for each SSTResponderSubComponent
gem5::Root* gem5_root = gem5::Root::root();
systemPort->findCorrespondingSimObject(gem5_root);
cachePort->findCorrespondingSimObject(gem5_root);
// initialize the gem5 event queue
if (!(threadInitialized)) {
threadInitialized = true;
gem5::simulate_limit_event = new gem5::GlobalSimLoopExitEvent(
gem5::mainEventQueue[0]->getCurTick(),
"simulate() limit reached",
0
);
}
}
systemPort->init(phase);
cachePort->init(phase);
}
void
gem5Component::setup()
{
output.verbose(CALL_INFO, 1, 0, "Component is being setup.\n");
systemPort->setup();
cachePort->setup();
}
void
gem5Component::finish()
{
output.verbose(CALL_INFO, 1, 0, "Component is being finished.\n");
}
bool
gem5Component::clockTick(SST::Cycle_t currentCycle)
{
// what to do in a SST's cycle
gem5::GlobalSimLoopExitEvent *event = simulateGem5(currentCycle);
clocksProcessed++;
// gem5 exits due to reasons other than reaching simulation limit
if (event != gem5::simulate_limit_event) {
output.output("exiting: curTick()=%lu cause=`%s` code=%d\n",
gem5::curTick(), event->getCause().c_str(), event->getCode()
);
// output gem5 stats
const std::vector<std::string> output_stats_commands = {
"m5.stats.dump()"
};
execPythonCommands(output_stats_commands);
primaryComponentOKToEndSim();
return true;
}
// returning False means the simulation should go on
return false;
}
#define PyCC(x) (const_cast<char *>(x))
gem5::GlobalSimLoopExitEvent*
gem5Component::simulateGem5(uint64_t current_cycle)
{
// This function should be similar to simulate() of src/sim/simulate.cc
// with synchronization barriers removed.
inform_once("Entering event queue @ %d. Starting simulation...\n",
gem5::curTick());
// Tick conversion
// The main logic for synchronize SST Tick and gem5 Tick is here.
// next_end_tick = current_cycle * timeConverter->getFactor()
uint64_t next_end_tick = \
timeConverter->convertToCoreTime(current_cycle);
// Here, if the next event in gem5's queue is not executed within the next
// cycle, there's no need to enter the gem5's sim loop.
if (gem5::mainEventQueue[0]->empty() ||
next_end_tick < gem5::mainEventQueue[0]->getHead()->when()) {
return gem5::simulate_limit_event;
}
gem5::simulate_limit_event->reschedule(next_end_tick);
gem5::Event *local_event = doSimLoop(gem5::mainEventQueue[0]);
gem5::BaseGlobalEvent *global_event = local_event->globalEvent();
gem5::GlobalSimLoopExitEvent *global_exit_event =
dynamic_cast<gem5::GlobalSimLoopExitEvent *>(global_event);
return global_exit_event;
}
gem5::Event*
gem5Component::doSimLoop(gem5::EventQueue* eventq)
{
// This function should be similar to doSimLoop() in src/sim/simulate.cc
// with synchronization barriers removed.
gem5::curEventQueue(eventq);
eventq->handleAsyncInsertions();
while (true)
{
// there should always be at least one event (the SimLoopExitEvent
// we just scheduled) in the queue
assert(!eventq->empty());
assert(gem5::curTick() <= eventq->nextTick() &&
"event scheduled in the past");
if (gem5::async_event) {
// Take the event queue lock in case any of the service
// routines want to schedule new events.
if (gem5::async_statdump || gem5::async_statreset) {
gem5::statistics::schedStatEvent(gem5::async_statdump,
gem5::async_statreset);
gem5::async_statdump = false;
gem5::async_statreset = false;
}
if (gem5::async_io) {
gem5::async_io = false;
gem5::pollQueue.service();
}
if (gem5::async_exit) {
gem5::async_exit = false;
gem5::exitSimLoop("user interrupt received");
}
if (gem5::async_exception) {
gem5::async_exception = false;
return NULL;
}
}
gem5::Event *exit_event = eventq->serviceOne();
if (exit_event != NULL) {
return exit_event;
}
}
}
int
gem5Component::execPythonCommands(const std::vector<std::string>& commands)
{
static PyObject *dict =
py::module_::import("__main__").attr("__dict__").ptr();
PyObject *result;
for (auto const command: commands) {
result = PyRun_String(command.c_str(), Py_file_input, dict, dict);
if (!result) {
PyErr_Print();
return 1;
}
Py_DECREF(result);
}
return 0;
}
void
gem5Component::initPython(int argc, char *_argv[])
{
// Initialize gem5 special signal handling.
gem5::initSignals();
if (!Py_IsInitialized())
py::initialize_interpreter(false, argc, _argv);
auto importer = py::module_::import("importer");
importer.attr("install")();
try {
py::module_::import("m5").attr("main")();
} catch (py::error_already_set &e) {
if (!e.matches(PyExc_SystemExit)) {
std::cerr << e.what();
output.output(CALL_INFO, "Calling m5.main(...) failed.\n");
}
}
}
void
gem5Component::splitCommandArgs(std::string &cmd, std::vector<char*> &args)
{
std::vector<std::string> parsed_args = tokenizeString(
cmd, {'\\', ' ', '\'', '\"'}
);
for (auto part: parsed_args)
args.push_back(strdup(part.c_str()));
}
<commit_msg>ext: In sst, don't assume existing imports in python blobs.<commit_after>// Copyright (c) 2021 The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer;
// redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution;
// neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Copyright (c) 2015-2016 ARM Limited
// All rights reserved.
//
// The license below extends only to copyright in the software and shall
// not be construed as granting a license to any other intellectual
// property including but not limited to intellectual property relating
// to a hardware implementation of the functionality of the software
// licensed hereunder. You may use the software subject to the license
// terms below provided that you ensure that this notice is replicated
// unmodified and in its entirety in all distributions of the software,
// modified or unmodified, in source code or in binary form.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer;
// redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution;
// neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Copyright 2009-2014 Sandia Coporation. Under the terms
// of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2014, Sandia Corporation
// All rights reserved.
//
// For license information, see the LICENSE file in the current directory.
#include <sst/core/sst_config.h>
#include <sst/core/componentInfo.h>
#include <sst/core/interfaces/simpleMem.h>
#include <sst/elements/memHierarchy/memEvent.h>
#include <sst/elements/memHierarchy/memTypes.h>
#include <sst/elements/memHierarchy/util.h>
#include <Python.h> // Before serialization to prevent spurious warnings
#include "gem5.hh"
#include "util.hh"
// System headers
#include <algorithm>
#include <fstream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
// gem5 Headers
#include <sim/core.hh>
#include <sim/init.hh>
#include <sim/init_signals.hh>
#include <sim/root.hh>
#include <sim/system.hh>
#include <sim/sim_events.hh>
#include <sim/sim_object.hh>
#include <base/logging.hh>
#include <base/debug.hh>
#include <base/pollevent.hh>
#include <base/types.hh>
#include <sim/async.hh>
#include <sim/eventq.hh>
#include <sim/sim_exit.hh>
#include <sim/stat_control.hh>
#include <sst/outgoing_request_bridge.hh>
#include <cassert>
#ifdef fatal // gem5 sets this
#undef fatal
#endif
// More SST Headers
#include <core/timeConverter.h>
namespace py = pybind11;
gem5Component::gem5Component(SST::ComponentId_t id, SST::Params& params):
SST::Component(id), threadInitialized(false)
{
output.init("gem5Component-" + getName() + "->", 1, 0,
SST::Output::STDOUT);
std::string cpu_frequency = params.find<std::string>("frequency", "");
if (cpu_frequency.empty()) {
output.fatal(
CALL_INFO, -1, "The frequency of the CPU must be specified.\n"
);
}
// Register a handler to be called on a set frequency.
timeConverter = registerClock(
cpu_frequency,
new SST::Clock::Handler<gem5Component>(this, &gem5Component::clockTick)
);
// "cmd" -> gem5's Python
std::string cmd = params.find<std::string>("cmd", "");
if (cmd.empty()) {
output.fatal(
CALL_INFO, -1, "Component %s must have a 'cmd' parameter.\n",
getName().c_str()
);
}
// Telling SST the command line call to gem5
args.push_back(const_cast<char*>("sst.x"));
splitCommandArgs(cmd, args);
output.output(CALL_INFO, "Command string: [sst.x %s]\n", cmd.c_str());
for (size_t i = 0; i < args.size(); ++i) {
output.output(CALL_INFO, " Arg [%02zu] = %s\n", i, args[i]);
}
// Parsing and setting gem5 debug flags
std::string gem5_debug_flags = params.find<std::string>("debug_flags", "");
for (auto const debug_flag: tokenizeString(gem5_debug_flags, {' ', ','})) {
output.output(CALL_INFO, "Debug flag += %s\n", debug_flag.c_str());
gem5::setDebugFlag(debug_flag.c_str());
}
registerAsPrimaryComponent();
primaryComponentDoNotEndSim();
systemPort = \
loadUserSubComponent<SSTResponderSubComponent>("system_port",0);
cachePort = \
loadUserSubComponent<SSTResponderSubComponent>("cache_port", 0);
systemPort->setTimeConverter(timeConverter);
systemPort->setOutputStream(&(output));
cachePort->setTimeConverter(timeConverter);
cachePort->setOutputStream(&(output));
}
gem5Component::~gem5Component()
{
}
void
gem5Component::init(unsigned phase)
{
output.output(CALL_INFO," init phase: %u\n", phase);
if (phase == 0) {
initPython(args.size(), &args[0]);
const std::vector<std::string> m5_instantiate_commands = {
"import m5",
"m5.instantiate()"
};
execPythonCommands(m5_instantiate_commands);
// calling SimObject.startup()
const std::vector<std::string> simobject_setup_commands = {
"import atexit",
"import _m5.core",
"import m5",
"import m5.stats",
"import m5.objects.Root",
"root = m5.objects.Root.getInstance()",
"for obj in root.descendants(): obj.startup()",
"atexit.register(m5.stats.dump)",
"atexit.register(_m5.core.doExitCleanup)",
"m5.stats.reset()"
};
execPythonCommands(simobject_setup_commands);
// find the corresponding SimObject for each SSTResponderSubComponent
gem5::Root* gem5_root = gem5::Root::root();
systemPort->findCorrespondingSimObject(gem5_root);
cachePort->findCorrespondingSimObject(gem5_root);
// initialize the gem5 event queue
if (!(threadInitialized)) {
threadInitialized = true;
gem5::simulate_limit_event = new gem5::GlobalSimLoopExitEvent(
gem5::mainEventQueue[0]->getCurTick(),
"simulate() limit reached",
0
);
}
}
systemPort->init(phase);
cachePort->init(phase);
}
void
gem5Component::setup()
{
output.verbose(CALL_INFO, 1, 0, "Component is being setup.\n");
systemPort->setup();
cachePort->setup();
}
void
gem5Component::finish()
{
output.verbose(CALL_INFO, 1, 0, "Component is being finished.\n");
}
bool
gem5Component::clockTick(SST::Cycle_t currentCycle)
{
// what to do in a SST's cycle
gem5::GlobalSimLoopExitEvent *event = simulateGem5(currentCycle);
clocksProcessed++;
// gem5 exits due to reasons other than reaching simulation limit
if (event != gem5::simulate_limit_event) {
output.output("exiting: curTick()=%lu cause=`%s` code=%d\n",
gem5::curTick(), event->getCause().c_str(), event->getCode()
);
// output gem5 stats
const std::vector<std::string> output_stats_commands = {
"import m5.stats"
"m5.stats.dump()"
};
execPythonCommands(output_stats_commands);
primaryComponentOKToEndSim();
return true;
}
// returning False means the simulation should go on
return false;
}
#define PyCC(x) (const_cast<char *>(x))
gem5::GlobalSimLoopExitEvent*
gem5Component::simulateGem5(uint64_t current_cycle)
{
// This function should be similar to simulate() of src/sim/simulate.cc
// with synchronization barriers removed.
inform_once("Entering event queue @ %d. Starting simulation...\n",
gem5::curTick());
// Tick conversion
// The main logic for synchronize SST Tick and gem5 Tick is here.
// next_end_tick = current_cycle * timeConverter->getFactor()
uint64_t next_end_tick = \
timeConverter->convertToCoreTime(current_cycle);
// Here, if the next event in gem5's queue is not executed within the next
// cycle, there's no need to enter the gem5's sim loop.
if (gem5::mainEventQueue[0]->empty() ||
next_end_tick < gem5::mainEventQueue[0]->getHead()->when()) {
return gem5::simulate_limit_event;
}
gem5::simulate_limit_event->reschedule(next_end_tick);
gem5::Event *local_event = doSimLoop(gem5::mainEventQueue[0]);
gem5::BaseGlobalEvent *global_event = local_event->globalEvent();
gem5::GlobalSimLoopExitEvent *global_exit_event =
dynamic_cast<gem5::GlobalSimLoopExitEvent *>(global_event);
return global_exit_event;
}
gem5::Event*
gem5Component::doSimLoop(gem5::EventQueue* eventq)
{
// This function should be similar to doSimLoop() in src/sim/simulate.cc
// with synchronization barriers removed.
gem5::curEventQueue(eventq);
eventq->handleAsyncInsertions();
while (true)
{
// there should always be at least one event (the SimLoopExitEvent
// we just scheduled) in the queue
assert(!eventq->empty());
assert(gem5::curTick() <= eventq->nextTick() &&
"event scheduled in the past");
if (gem5::async_event) {
// Take the event queue lock in case any of the service
// routines want to schedule new events.
if (gem5::async_statdump || gem5::async_statreset) {
gem5::statistics::schedStatEvent(gem5::async_statdump,
gem5::async_statreset);
gem5::async_statdump = false;
gem5::async_statreset = false;
}
if (gem5::async_io) {
gem5::async_io = false;
gem5::pollQueue.service();
}
if (gem5::async_exit) {
gem5::async_exit = false;
gem5::exitSimLoop("user interrupt received");
}
if (gem5::async_exception) {
gem5::async_exception = false;
return NULL;
}
}
gem5::Event *exit_event = eventq->serviceOne();
if (exit_event != NULL) {
return exit_event;
}
}
}
int
gem5Component::execPythonCommands(const std::vector<std::string>& commands)
{
static PyObject *dict =
py::module_::import("__main__").attr("__dict__").ptr();
PyObject *result;
for (auto const command: commands) {
result = PyRun_String(command.c_str(), Py_file_input, dict, dict);
if (!result) {
PyErr_Print();
return 1;
}
Py_DECREF(result);
}
return 0;
}
void
gem5Component::initPython(int argc, char *_argv[])
{
// Initialize gem5 special signal handling.
gem5::initSignals();
if (!Py_IsInitialized())
py::initialize_interpreter(false, argc, _argv);
auto importer = py::module_::import("importer");
importer.attr("install")();
try {
py::module_::import("m5").attr("main")();
} catch (py::error_already_set &e) {
if (!e.matches(PyExc_SystemExit)) {
std::cerr << e.what();
output.output(CALL_INFO, "Calling m5.main(...) failed.\n");
}
}
}
void
gem5Component::splitCommandArgs(std::string &cmd, std::vector<char*> &args)
{
std::vector<std::string> parsed_args = tokenizeString(
cmd, {'\\', ' ', '\'', '\"'}
);
for (auto part: parsed_args)
args.push_back(strdup(part.c_str()));
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module 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 qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\class QPropertyAnimation
\brief The QPropertyAnimation class animates Qt properties
\since 4.6
\ingroup animation
QPropertyAnimation interpolates over \l{Qt's Property System}{Qt
properties}. As property values are stored in \l{QVariant}s, the
class inherits QVariantAnimation, and supports animation of the
same \l{QVariant::Type}{variant types} as its super class.
A class declaring properties must be a QObject. To make it
possible to animate a property, it must provide a setter (so that
QPropertyAnimation can set the property's value). Note that this
makes it possible to animate many of Qt's widgets. Let's look at
an example:
\code
QPropertyAnimation animation(myWidget, "geometry");
animation.setDuration(10000);
animation.setStartValue(QRect(0, 0, 100, 30));
animation.setEndValue(QRect(250, 250, 100, 30));
animation.start();
\endcode
The property name and the QObject instance of which property
should be animated are passed to the constructor. You can then
specify the start and end value of the property. The procedure is
equal for properties in classes you have implemented
yourself--just check with QVariantAnimation that your QVariant
type is supported.
The QVariantAnimation class description explains how to set up the
animation in detail. Note, however, that if a start value is not
set, the property will start at the value it had when the
QPropertyAnimation instance was created.
QPropertyAnimation works like a charm on its own. For complex
animations that, for instance, contain several objects,
QAnimationGroup is provided. An animation group is an animation
that can contain other animations, and that can manage when its
animations are played. Look at QParallelAnimationGroup for an
example.
\sa QVariantAnimation, QAnimationGroup, {The Animation Framework}
*/
#include "qpropertyanimation.h"
#include "qanimationgroup.h"
#include "qpropertyanimation_p.h"
#include <private/qmutexpool_p.h>
#ifndef QT_NO_ANIMATION
QT_BEGIN_NAMESPACE
void QPropertyAnimationPrivate::updateMetaProperty()
{
if (!target || propertyName.isEmpty()) {
propertyType = QVariant::Invalid;
propertyIndex = -1;
return;
}
//propertyType will be set to a valid type only if there is a Q_PROPERTY
//otherwise it will be set to QVariant::Invalid at the end of this function
propertyType = targetValue->property(propertyName).userType();
propertyIndex = targetValue->metaObject()->indexOfProperty(propertyName);
if (propertyType != QVariant::Invalid)
convertValues(propertyType);
if (propertyIndex == -1) {
//there is no Q_PROPERTY on the object
propertyType = QVariant::Invalid;
if (!targetValue->dynamicPropertyNames().contains(propertyName))
qWarning("QPropertyAnimation: you're trying to animate a non-existing property %s of your QObject", propertyName.constData());
}
}
void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue)
{
if (state == QAbstractAnimation::Stopped)
return;
if (!target) {
q_func()->stop(); //the target was destroyed we need to stop the animation
return;
}
if (newValue.userType() == propertyType) {
//no conversion is needed, we directly call the QObject::qt_metacall
void *data = const_cast<void*>(newValue.constData());
targetValue->qt_metacall(QMetaObject::WriteProperty, propertyIndex, &data);
} else {
targetValue->setProperty(propertyName.constData(), newValue);
}
}
/*!
Construct a QPropertyAnimation object. \a parent is passed to QObject's
constructor.
*/
QPropertyAnimation::QPropertyAnimation(QObject *parent)
: QVariantAnimation(*new QPropertyAnimationPrivate, parent)
{
}
/*!
Construct a QPropertyAnimation object. \a parent is passed to QObject's
constructor. The animation changes the property \a propertyName on \a
target. The default duration is 250ms.
\sa targetObject, propertyName
*/
QPropertyAnimation::QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent)
: QVariantAnimation(*new QPropertyAnimationPrivate, parent)
{
setTargetObject(target);
setPropertyName(propertyName);
}
/*!
Destroys the QPropertyAnimation instance.
*/
QPropertyAnimation::~QPropertyAnimation()
{
stop();
}
/*!
\property QPropertyAnimation::targetObject
\brief the target QObject for this animation.
This property defines the target QObject for this animation.
*/
QObject *QPropertyAnimation::targetObject() const
{
return d_func()->target.data();
}
void QPropertyAnimation::setTargetObject(QObject *target)
{
Q_D(QPropertyAnimation);
if (d->targetValue == target)
return;
if (d->state != QAbstractAnimation::Stopped) {
qWarning("QPropertyAnimation::setTargetObject: you can't change the target of a running animation");
return;
}
d->target = d->targetValue = target;
d->updateMetaProperty();
}
/*!
\property QPropertyAnimation::propertyName
\brief the target property name for this animation
This property defines the target property name for this animation. The
property name is required for the animation to operate.
*/
QByteArray QPropertyAnimation::propertyName() const
{
Q_D(const QPropertyAnimation);
return d->propertyName;
}
void QPropertyAnimation::setPropertyName(const QByteArray &propertyName)
{
Q_D(QPropertyAnimation);
if (d->state != QAbstractAnimation::Stopped) {
qWarning("QPropertyAnimation::setPropertyName: you can't change the property name of a running animation");
return;
}
d->propertyName = propertyName;
d->updateMetaProperty();
}
/*!
\reimp
*/
bool QPropertyAnimation::event(QEvent *event)
{
return QVariantAnimation::event(event);
}
/*!
This virtual function is called by QVariantAnimation whenever the current value
changes. \a value is the new, updated value. It updates the current value
of the property on the target object.
\sa currentValue, currentTime
*/
void QPropertyAnimation::updateCurrentValue(const QVariant &value)
{
Q_D(QPropertyAnimation);
d->updateProperty(value);
}
/*!
\reimp
If the startValue is not defined when the state of the animation changes from Stopped to Running,
the current property value is used as the initial value for the animation.
*/
void QPropertyAnimation::updateState(QAbstractAnimation::State oldState,
QAbstractAnimation::State newState)
{
Q_D(QPropertyAnimation);
if (!d->target && oldState == Stopped) {
qWarning("QPropertyAnimation::updateState: Changing state of an animation without target");
return;
}
QVariantAnimation::updateState(oldState, newState);
QPropertyAnimation *animToStop = 0;
{
QMutexLocker locker(QMutexPool::globalInstanceGet(&staticMetaObject));
typedef QPair<QObject *, QByteArray> QPropertyAnimationPair;
typedef QHash<QPropertyAnimationPair, QPropertyAnimation*> QPropertyAnimationHash;
static QPropertyAnimationHash hash;
//here we need to use value because we need to know to which pointer
//the animation was referring in case stopped because the target was destroyed
QPropertyAnimationPair key(d->targetValue, d->propertyName);
if (newState == Running) {
d->updateMetaProperty();
animToStop = hash.value(key, 0);
hash.insert(key, this);
// update the default start value
if (oldState == Stopped) {
d->setDefaultStartEndValue(d->targetValue->property(d->propertyName.constData()));
//let's check if we have a start value and an end value
if (!startValue().isValid() && (d->direction == Backward || !d->defaultStartEndValue.isValid()))
qWarning("QPropertyAnimation::updateState: starting an animation without start value");
if (!endValue().isValid() && (d->direction == Forward || !d->defaultStartEndValue.isValid()))
qWarning("QPropertyAnimation::updateState: starting an animation without end value");
}
} else if (hash.value(key) == this) {
hash.remove(key);
}
}
//we need to do that after the mutex was unlocked
if (animToStop) {
// try to stop the top level group
QAbstractAnimation *current = animToStop;
while (current->group() && current->state() != Stopped)
current = current->group();
current->stop();
}
}
#include "moc_qpropertyanimation.cpp"
QT_END_NAMESPACE
#endif //QT_NO_ANIMATION
<commit_msg>QPropertyAnimation now uses QMetaObject::metacall instead of qt_metacall<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module 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 qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\class QPropertyAnimation
\brief The QPropertyAnimation class animates Qt properties
\since 4.6
\ingroup animation
QPropertyAnimation interpolates over \l{Qt's Property System}{Qt
properties}. As property values are stored in \l{QVariant}s, the
class inherits QVariantAnimation, and supports animation of the
same \l{QVariant::Type}{variant types} as its super class.
A class declaring properties must be a QObject. To make it
possible to animate a property, it must provide a setter (so that
QPropertyAnimation can set the property's value). Note that this
makes it possible to animate many of Qt's widgets. Let's look at
an example:
\code
QPropertyAnimation animation(myWidget, "geometry");
animation.setDuration(10000);
animation.setStartValue(QRect(0, 0, 100, 30));
animation.setEndValue(QRect(250, 250, 100, 30));
animation.start();
\endcode
The property name and the QObject instance of which property
should be animated are passed to the constructor. You can then
specify the start and end value of the property. The procedure is
equal for properties in classes you have implemented
yourself--just check with QVariantAnimation that your QVariant
type is supported.
The QVariantAnimation class description explains how to set up the
animation in detail. Note, however, that if a start value is not
set, the property will start at the value it had when the
QPropertyAnimation instance was created.
QPropertyAnimation works like a charm on its own. For complex
animations that, for instance, contain several objects,
QAnimationGroup is provided. An animation group is an animation
that can contain other animations, and that can manage when its
animations are played. Look at QParallelAnimationGroup for an
example.
\sa QVariantAnimation, QAnimationGroup, {The Animation Framework}
*/
#include "qpropertyanimation.h"
#include "qanimationgroup.h"
#include "qpropertyanimation_p.h"
#include <private/qmutexpool_p.h>
#ifndef QT_NO_ANIMATION
QT_BEGIN_NAMESPACE
void QPropertyAnimationPrivate::updateMetaProperty()
{
if (!target || propertyName.isEmpty()) {
propertyType = QVariant::Invalid;
propertyIndex = -1;
return;
}
//propertyType will be set to a valid type only if there is a Q_PROPERTY
//otherwise it will be set to QVariant::Invalid at the end of this function
propertyType = targetValue->property(propertyName).userType();
propertyIndex = targetValue->metaObject()->indexOfProperty(propertyName);
if (propertyType != QVariant::Invalid)
convertValues(propertyType);
if (propertyIndex == -1) {
//there is no Q_PROPERTY on the object
propertyType = QVariant::Invalid;
if (!targetValue->dynamicPropertyNames().contains(propertyName))
qWarning("QPropertyAnimation: you're trying to animate a non-existing property %s of your QObject", propertyName.constData());
}
}
void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue)
{
if (state == QAbstractAnimation::Stopped)
return;
if (!target) {
q_func()->stop(); //the target was destroyed we need to stop the animation
return;
}
if (newValue.userType() == propertyType) {
//no conversion is needed, we directly call the QMetaObject::metacall
void *data = const_cast<void*>(newValue.constData());
QMetaObject::metacall(targetValue, QMetaObject::WriteProperty, propertyIndex, &data);
} else {
targetValue->setProperty(propertyName.constData(), newValue);
}
}
/*!
Construct a QPropertyAnimation object. \a parent is passed to QObject's
constructor.
*/
QPropertyAnimation::QPropertyAnimation(QObject *parent)
: QVariantAnimation(*new QPropertyAnimationPrivate, parent)
{
}
/*!
Construct a QPropertyAnimation object. \a parent is passed to QObject's
constructor. The animation changes the property \a propertyName on \a
target. The default duration is 250ms.
\sa targetObject, propertyName
*/
QPropertyAnimation::QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent)
: QVariantAnimation(*new QPropertyAnimationPrivate, parent)
{
setTargetObject(target);
setPropertyName(propertyName);
}
/*!
Destroys the QPropertyAnimation instance.
*/
QPropertyAnimation::~QPropertyAnimation()
{
stop();
}
/*!
\property QPropertyAnimation::targetObject
\brief the target QObject for this animation.
This property defines the target QObject for this animation.
*/
QObject *QPropertyAnimation::targetObject() const
{
return d_func()->target.data();
}
void QPropertyAnimation::setTargetObject(QObject *target)
{
Q_D(QPropertyAnimation);
if (d->targetValue == target)
return;
if (d->state != QAbstractAnimation::Stopped) {
qWarning("QPropertyAnimation::setTargetObject: you can't change the target of a running animation");
return;
}
d->target = d->targetValue = target;
d->updateMetaProperty();
}
/*!
\property QPropertyAnimation::propertyName
\brief the target property name for this animation
This property defines the target property name for this animation. The
property name is required for the animation to operate.
*/
QByteArray QPropertyAnimation::propertyName() const
{
Q_D(const QPropertyAnimation);
return d->propertyName;
}
void QPropertyAnimation::setPropertyName(const QByteArray &propertyName)
{
Q_D(QPropertyAnimation);
if (d->state != QAbstractAnimation::Stopped) {
qWarning("QPropertyAnimation::setPropertyName: you can't change the property name of a running animation");
return;
}
d->propertyName = propertyName;
d->updateMetaProperty();
}
/*!
\reimp
*/
bool QPropertyAnimation::event(QEvent *event)
{
return QVariantAnimation::event(event);
}
/*!
This virtual function is called by QVariantAnimation whenever the current value
changes. \a value is the new, updated value. It updates the current value
of the property on the target object.
\sa currentValue, currentTime
*/
void QPropertyAnimation::updateCurrentValue(const QVariant &value)
{
Q_D(QPropertyAnimation);
d->updateProperty(value);
}
/*!
\reimp
If the startValue is not defined when the state of the animation changes from Stopped to Running,
the current property value is used as the initial value for the animation.
*/
void QPropertyAnimation::updateState(QAbstractAnimation::State oldState,
QAbstractAnimation::State newState)
{
Q_D(QPropertyAnimation);
if (!d->target && oldState == Stopped) {
qWarning("QPropertyAnimation::updateState: Changing state of an animation without target");
return;
}
QVariantAnimation::updateState(oldState, newState);
QPropertyAnimation *animToStop = 0;
{
QMutexLocker locker(QMutexPool::globalInstanceGet(&staticMetaObject));
typedef QPair<QObject *, QByteArray> QPropertyAnimationPair;
typedef QHash<QPropertyAnimationPair, QPropertyAnimation*> QPropertyAnimationHash;
static QPropertyAnimationHash hash;
//here we need to use value because we need to know to which pointer
//the animation was referring in case stopped because the target was destroyed
QPropertyAnimationPair key(d->targetValue, d->propertyName);
if (newState == Running) {
d->updateMetaProperty();
animToStop = hash.value(key, 0);
hash.insert(key, this);
// update the default start value
if (oldState == Stopped) {
d->setDefaultStartEndValue(d->targetValue->property(d->propertyName.constData()));
//let's check if we have a start value and an end value
if (!startValue().isValid() && (d->direction == Backward || !d->defaultStartEndValue.isValid()))
qWarning("QPropertyAnimation::updateState: starting an animation without start value");
if (!endValue().isValid() && (d->direction == Forward || !d->defaultStartEndValue.isValid()))
qWarning("QPropertyAnimation::updateState: starting an animation without end value");
}
} else if (hash.value(key) == this) {
hash.remove(key);
}
}
//we need to do that after the mutex was unlocked
if (animToStop) {
// try to stop the top level group
QAbstractAnimation *current = animToStop;
while (current->group() && current->state() != Stopped)
current = current->group();
current->stop();
}
}
#include "moc_qpropertyanimation.cpp"
QT_END_NAMESPACE
#endif //QT_NO_ANIMATION
<|endoftext|> |
<commit_before>//===-- asan_asm_test.cc --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"
#if defined(__linux__)
// Assembly instrumentation is broken on x86 Android (x86 + PIC + shared runtime
// library). See https://github.com/google/sanitizers/issues/353
#if defined(__x86_64__) || \
(defined(__i386__) && defined(__SSE2__) && !defined(__ANDROID__))
#include <emmintrin.h>
namespace {
template<typename T> void asm_write(T *ptr, T val);
template<typename T> T asm_read(T *ptr);
template<typename T> void asm_rep_movs(T *dst, T *src, size_t n);
} // End of anonymous namespace
#endif // defined(__x86_64__) || (defined(__i386__) && defined(__SSE2__))
#if defined(__x86_64__)
namespace {
#define DECLARE_ASM_WRITE(Type, Size, Mov, Reg) \
template<> void asm_write<Type>(Type *ptr, Type val) { \
__asm__( \
Mov " %[val], (%[ptr]) \n\t" \
: \
: [ptr] "r" (ptr), [val] Reg (val) \
: "memory" \
); \
}
#define DECLARE_ASM_READ(Type, Size, Mov, Reg) \
template<> Type asm_read<Type>(Type *ptr) { \
Type res; \
__asm__( \
Mov " (%[ptr]), %[res] \n\t" \
: [res] Reg (res) \
: [ptr] "r" (ptr) \
: "memory" \
); \
return res; \
}
#define DECLARE_ASM_REP_MOVS(Type, Movs) \
template <> void asm_rep_movs<Type>(Type * dst, Type * src, size_t size) { \
__asm__("rep " Movs " \n\t" \
: \
: "D"(dst), "S"(src), "c"(size) \
: "memory"); \
}
DECLARE_ASM_WRITE(U8, "8", "movq", "r");
DECLARE_ASM_READ(U8, "8", "movq", "=r");
DECLARE_ASM_REP_MOVS(U8, "movsq");
} // End of anonymous namespace
#endif // defined(__x86_64__)
#if defined(__i386__) && defined(__SSE2__) && !defined(__ANDROID__)
namespace {
#define DECLARE_ASM_WRITE(Type, Size, Mov, Reg) \
template<> void asm_write<Type>(Type *ptr, Type val) { \
__asm__( \
Mov " %[val], (%[ptr]) \n\t" \
: \
: [ptr] "r" (ptr), [val] Reg (val) \
: "memory" \
); \
}
#define DECLARE_ASM_READ(Type, Size, Mov, Reg) \
template<> Type asm_read<Type>(Type *ptr) { \
Type res; \
__asm__( \
Mov " (%[ptr]), %[res] \n\t" \
: [res] Reg (res) \
: [ptr] "r" (ptr) \
: "memory" \
); \
return res; \
}
#define DECLARE_ASM_REP_MOVS(Type, Movs) \
template <> void asm_rep_movs<Type>(Type * dst, Type * src, size_t size) { \
__asm__("rep " Movs " \n\t" \
: \
: "D"(dst), "S"(src), "c"(size) \
: "memory"); \
}
} // End of anonymous namespace
#endif // defined(__i386__) && defined(__SSE2__)
#if defined(__x86_64__) || \
(defined(__i386__) && defined(__SSE2__) && !defined(__ANDROID__))
namespace {
DECLARE_ASM_WRITE(U1, "1", "movb", "r");
DECLARE_ASM_WRITE(U2, "2", "movw", "r");
DECLARE_ASM_WRITE(U4, "4", "movl", "r");
DECLARE_ASM_WRITE(__m128i, "16", "movaps", "x");
DECLARE_ASM_READ(U1, "1", "movb", "=r");
DECLARE_ASM_READ(U2, "2", "movw", "=r");
DECLARE_ASM_READ(U4, "4", "movl", "=r");
DECLARE_ASM_READ(__m128i, "16", "movaps", "=x");
DECLARE_ASM_REP_MOVS(U1, "movsb");
DECLARE_ASM_REP_MOVS(U2, "movsw");
DECLARE_ASM_REP_MOVS(U4, "movsl");
template<typename T> void TestAsmWrite(const char *DeathPattern) {
T *buf = new T;
EXPECT_DEATH(asm_write(&buf[1], static_cast<T>(0)), DeathPattern);
T var = 0x12;
asm_write(&var, static_cast<T>(0x21));
ASSERT_EQ(static_cast<T>(0x21), var);
delete buf;
}
template<> void TestAsmWrite<__m128i>(const char *DeathPattern) {
char *buf = new char[16];
char *p = buf + 16;
if (((uintptr_t) p % 16) != 0)
p = buf + 8;
assert(((uintptr_t) p % 16) == 0);
__m128i val = _mm_set1_epi16(0x1234);
EXPECT_DEATH(asm_write<__m128i>((__m128i*) p, val), DeathPattern);
__m128i var = _mm_set1_epi16(0x4321);
asm_write(&var, val);
ASSERT_EQ(0x1234, _mm_extract_epi16(var, 0));
delete [] buf;
}
template<typename T> void TestAsmRead(const char *DeathPattern) {
T *buf = new T;
EXPECT_DEATH(asm_read(&buf[1]), DeathPattern);
T var = 0x12;
ASSERT_EQ(static_cast<T>(0x12), asm_read(&var));
delete buf;
}
template<> void TestAsmRead<__m128i>(const char *DeathPattern) {
char *buf = new char[16];
char *p = buf + 16;
if (((uintptr_t) p % 16) != 0)
p = buf + 8;
assert(((uintptr_t) p % 16) == 0);
EXPECT_DEATH(asm_read<__m128i>((__m128i*) p), DeathPattern);
__m128i val = _mm_set1_epi16(0x1234);
ASSERT_EQ(0x1234, _mm_extract_epi16(asm_read(&val), 0));
delete [] buf;
}
U4 AsmLoad(U4 *a) {
U4 r;
__asm__("movl (%[a]), %[r] \n\t" : [r] "=r" (r) : [a] "r" (a) : "memory");
return r;
}
void AsmStore(U4 r, U4 *a) {
__asm__("movl %[r], (%[a]) \n\t" : : [a] "r" (a), [r] "r" (r) : "memory");
}
template <typename T>
void TestAsmRepMovs(const char *DeathPatternRead,
const char *DeathPatternWrite) {
T src_good[4] = { 0x0, 0x1, 0x2, 0x3 };
T dst_good[4] = {};
asm_rep_movs(dst_good, src_good, 4);
ASSERT_EQ(static_cast<T>(0x0), dst_good[0]);
ASSERT_EQ(static_cast<T>(0x1), dst_good[1]);
ASSERT_EQ(static_cast<T>(0x2), dst_good[2]);
ASSERT_EQ(static_cast<T>(0x3), dst_good[3]);
T dst_bad[3];
EXPECT_DEATH(asm_rep_movs(dst_bad, src_good, 4), DeathPatternWrite);
T src_bad[3] = { 0x0, 0x1, 0x2 };
EXPECT_DEATH(asm_rep_movs(dst_good, src_bad, 4), DeathPatternRead);
T* dp = dst_bad + 4;
T* sp = src_bad + 4;
asm_rep_movs(dp, sp, 0);
}
} // End of anonymous namespace
TEST(AddressSanitizer, asm_load_store) {
U4* buf = new U4[2];
EXPECT_DEATH(AsmLoad(&buf[3]), "READ of size 4");
EXPECT_DEATH(AsmStore(0x1234, &buf[3]), "WRITE of size 4");
delete [] buf;
}
TEST(AddressSanitizer, asm_rw) {
TestAsmWrite<U1>("WRITE of size 1");
TestAsmWrite<U2>("WRITE of size 2");
TestAsmWrite<U4>("WRITE of size 4");
#if defined(__x86_64__)
TestAsmWrite<U8>("WRITE of size 8");
#endif // defined(__x86_64__)
TestAsmWrite<__m128i>("WRITE of size 16");
TestAsmRead<U1>("READ of size 1");
TestAsmRead<U2>("READ of size 2");
TestAsmRead<U4>("READ of size 4");
#if defined(__x86_64__)
TestAsmRead<U8>("READ of size 8");
#endif // defined(__x86_64__)
TestAsmRead<__m128i>("READ of size 16");
}
TEST(AddressSanitizer, asm_flags) {
long magic = 0x1234;
long r = 0x0;
#if defined(__x86_64__) && !defined(__ILP32__)
__asm__("xorq %%rax, %%rax \n\t"
"movq (%[p]), %%rax \n\t"
"sete %%al \n\t"
"movzbq %%al, %[r] \n\t"
: [r] "=r"(r)
: [p] "r"(&magic)
: "rax", "memory");
#else
__asm__("xorl %%eax, %%eax \n\t"
"movl (%[p]), %%eax \n\t"
"sete %%al \n\t"
"movzbl %%al, %[r] \n\t"
: [r] "=r"(r)
: [p] "r"(&magic)
: "eax", "memory");
#endif // defined(__x86_64__) && !defined(__ILP32__)
ASSERT_EQ(0x1, r);
}
TEST(AddressSanitizer, asm_rep_movs) {
TestAsmRepMovs<U1>("READ of size 1", "WRITE of size 1");
TestAsmRepMovs<U2>("READ of size 2", "WRITE of size 2");
TestAsmRepMovs<U4>("READ of size 4", "WRITE of size 4");
#if defined(__x86_64__)
TestAsmRepMovs<U8>("READ of size 8", "WRITE of size 8");
#endif // defined(__x86_64__)
}
#endif // defined(__x86_64__) || (defined(__i386__) && defined(__SSE2__))
#endif // defined(__linux__)
<commit_msg>[asan] Fix test broken by r290540<commit_after>//===-- asan_asm_test.cc --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"
#if defined(__linux__)
// Assembly instrumentation is broken on x86 Android (x86 + PIC + shared runtime
// library). See https://github.com/google/sanitizers/issues/353
#if defined(__x86_64__) || \
(defined(__i386__) && defined(__SSE2__) && !defined(__ANDROID__))
#include <emmintrin.h>
namespace {
template<typename T> void asm_write(T *ptr, T val);
template<typename T> T asm_read(T *ptr);
template<typename T> void asm_rep_movs(T *dst, T *src, size_t n);
} // End of anonymous namespace
#endif // defined(__x86_64__) || (defined(__i386__) && defined(__SSE2__))
#if defined(__x86_64__)
namespace {
#define DECLARE_ASM_WRITE(Type, Size, Mov, Reg) \
template<> void asm_write<Type>(Type *ptr, Type val) { \
__asm__( \
Mov " %[val], (%[ptr]) \n\t" \
: \
: [ptr] "r" (ptr), [val] Reg (val) \
: "memory" \
); \
}
#define DECLARE_ASM_READ(Type, Size, Mov, Reg) \
template<> Type asm_read<Type>(Type *ptr) { \
Type res; \
__asm__( \
Mov " (%[ptr]), %[res] \n\t" \
: [res] Reg (res) \
: [ptr] "r" (ptr) \
: "memory" \
); \
return res; \
}
#define DECLARE_ASM_REP_MOVS(Type, Movs) \
template <> \
void asm_rep_movs<Type>(Type * dst, Type * src, size_t size) { \
__asm__("rep " Movs " \n\t" \
: "+D"(dst), "+S"(src), "+c"(size) \
: \
: "memory"); \
}
DECLARE_ASM_WRITE(U8, "8", "movq", "r");
DECLARE_ASM_READ(U8, "8", "movq", "=r");
DECLARE_ASM_REP_MOVS(U8, "movsq");
} // End of anonymous namespace
#endif // defined(__x86_64__)
#if defined(__i386__) && defined(__SSE2__) && !defined(__ANDROID__)
namespace {
#define DECLARE_ASM_WRITE(Type, Size, Mov, Reg) \
template<> void asm_write<Type>(Type *ptr, Type val) { \
__asm__( \
Mov " %[val], (%[ptr]) \n\t" \
: \
: [ptr] "r" (ptr), [val] Reg (val) \
: "memory" \
); \
}
#define DECLARE_ASM_READ(Type, Size, Mov, Reg) \
template<> Type asm_read<Type>(Type *ptr) { \
Type res; \
__asm__( \
Mov " (%[ptr]), %[res] \n\t" \
: [res] Reg (res) \
: [ptr] "r" (ptr) \
: "memory" \
); \
return res; \
}
#define DECLARE_ASM_REP_MOVS(Type, Movs) \
template <> \
void asm_rep_movs<Type>(Type * dst, Type * src, size_t size) { \
__asm__("rep " Movs " \n\t" \
: "+D"(dst), "+S"(src), "+c"(size) \
: \
: "memory"); \
}
} // End of anonymous namespace
#endif // defined(__i386__) && defined(__SSE2__)
#if defined(__x86_64__) || \
(defined(__i386__) && defined(__SSE2__) && !defined(__ANDROID__))
namespace {
DECLARE_ASM_WRITE(U1, "1", "movb", "r");
DECLARE_ASM_WRITE(U2, "2", "movw", "r");
DECLARE_ASM_WRITE(U4, "4", "movl", "r");
DECLARE_ASM_WRITE(__m128i, "16", "movaps", "x");
DECLARE_ASM_READ(U1, "1", "movb", "=r");
DECLARE_ASM_READ(U2, "2", "movw", "=r");
DECLARE_ASM_READ(U4, "4", "movl", "=r");
DECLARE_ASM_READ(__m128i, "16", "movaps", "=x");
DECLARE_ASM_REP_MOVS(U1, "movsb");
DECLARE_ASM_REP_MOVS(U2, "movsw");
DECLARE_ASM_REP_MOVS(U4, "movsl");
template<typename T> void TestAsmWrite(const char *DeathPattern) {
T *buf = new T;
EXPECT_DEATH(asm_write(&buf[1], static_cast<T>(0)), DeathPattern);
T var = 0x12;
asm_write(&var, static_cast<T>(0x21));
ASSERT_EQ(static_cast<T>(0x21), var);
delete buf;
}
template<> void TestAsmWrite<__m128i>(const char *DeathPattern) {
char *buf = new char[16];
char *p = buf + 16;
if (((uintptr_t) p % 16) != 0)
p = buf + 8;
assert(((uintptr_t) p % 16) == 0);
__m128i val = _mm_set1_epi16(0x1234);
EXPECT_DEATH(asm_write<__m128i>((__m128i*) p, val), DeathPattern);
__m128i var = _mm_set1_epi16(0x4321);
asm_write(&var, val);
ASSERT_EQ(0x1234, _mm_extract_epi16(var, 0));
delete [] buf;
}
template<typename T> void TestAsmRead(const char *DeathPattern) {
T *buf = new T;
EXPECT_DEATH(asm_read(&buf[1]), DeathPattern);
T var = 0x12;
ASSERT_EQ(static_cast<T>(0x12), asm_read(&var));
delete buf;
}
template<> void TestAsmRead<__m128i>(const char *DeathPattern) {
char *buf = new char[16];
char *p = buf + 16;
if (((uintptr_t) p % 16) != 0)
p = buf + 8;
assert(((uintptr_t) p % 16) == 0);
EXPECT_DEATH(asm_read<__m128i>((__m128i*) p), DeathPattern);
__m128i val = _mm_set1_epi16(0x1234);
ASSERT_EQ(0x1234, _mm_extract_epi16(asm_read(&val), 0));
delete [] buf;
}
U4 AsmLoad(U4 *a) {
U4 r;
__asm__("movl (%[a]), %[r] \n\t" : [r] "=r" (r) : [a] "r" (a) : "memory");
return r;
}
void AsmStore(U4 r, U4 *a) {
__asm__("movl %[r], (%[a]) \n\t" : : [a] "r" (a), [r] "r" (r) : "memory");
}
template <typename T>
void TestAsmRepMovs(const char *DeathPatternRead,
const char *DeathPatternWrite) {
T src_good[4] = { 0x0, 0x1, 0x2, 0x3 };
T dst_good[4] = {};
asm_rep_movs(dst_good, src_good, 4);
ASSERT_EQ(static_cast<T>(0x0), dst_good[0]);
ASSERT_EQ(static_cast<T>(0x1), dst_good[1]);
ASSERT_EQ(static_cast<T>(0x2), dst_good[2]);
ASSERT_EQ(static_cast<T>(0x3), dst_good[3]);
T dst_bad[3];
EXPECT_DEATH(asm_rep_movs(dst_bad, src_good, 4), DeathPatternWrite);
T src_bad[3] = { 0x0, 0x1, 0x2 };
EXPECT_DEATH(asm_rep_movs(dst_good, src_bad, 4), DeathPatternRead);
T* dp = dst_bad + 4;
T* sp = src_bad + 4;
asm_rep_movs(dp, sp, 0);
}
} // End of anonymous namespace
TEST(AddressSanitizer, asm_load_store) {
U4* buf = new U4[2];
EXPECT_DEATH(AsmLoad(&buf[3]), "READ of size 4");
EXPECT_DEATH(AsmStore(0x1234, &buf[3]), "WRITE of size 4");
delete [] buf;
}
TEST(AddressSanitizer, asm_rw) {
TestAsmWrite<U1>("WRITE of size 1");
TestAsmWrite<U2>("WRITE of size 2");
TestAsmWrite<U4>("WRITE of size 4");
#if defined(__x86_64__)
TestAsmWrite<U8>("WRITE of size 8");
#endif // defined(__x86_64__)
TestAsmWrite<__m128i>("WRITE of size 16");
TestAsmRead<U1>("READ of size 1");
TestAsmRead<U2>("READ of size 2");
TestAsmRead<U4>("READ of size 4");
#if defined(__x86_64__)
TestAsmRead<U8>("READ of size 8");
#endif // defined(__x86_64__)
TestAsmRead<__m128i>("READ of size 16");
}
TEST(AddressSanitizer, asm_flags) {
long magic = 0x1234;
long r = 0x0;
#if defined(__x86_64__) && !defined(__ILP32__)
__asm__("xorq %%rax, %%rax \n\t"
"movq (%[p]), %%rax \n\t"
"sete %%al \n\t"
"movzbq %%al, %[r] \n\t"
: [r] "=r"(r)
: [p] "r"(&magic)
: "rax", "memory");
#else
__asm__("xorl %%eax, %%eax \n\t"
"movl (%[p]), %%eax \n\t"
"sete %%al \n\t"
"movzbl %%al, %[r] \n\t"
: [r] "=r"(r)
: [p] "r"(&magic)
: "eax", "memory");
#endif // defined(__x86_64__) && !defined(__ILP32__)
ASSERT_EQ(0x1, r);
}
TEST(AddressSanitizer, asm_rep_movs) {
TestAsmRepMovs<U1>("READ of size 1", "WRITE of size 1");
TestAsmRepMovs<U2>("READ of size 2", "WRITE of size 2");
TestAsmRepMovs<U4>("READ of size 4", "WRITE of size 4");
#if defined(__x86_64__)
TestAsmRepMovs<U8>("READ of size 8", "WRITE of size 8");
#endif // defined(__x86_64__)
}
#endif // defined(__x86_64__) || (defined(__i386__) && defined(__SSE2__))
#endif // defined(__linux__)
<|endoftext|> |
<commit_before>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file AppObstacleTest.cpp
* @brief Contains the definition function main() for testing new obstacles
* @author Brian Mirletz
* $Id$
*/
// This application
#include "tgBlockField.h"
#include "tgStairs.h"
// This library
#include "core/terrain/tgBoxGround.h"
#include "core/terrain/tgEmptyGround.h"
#include "core/terrain/tgHillyGround.h"
#include "core/tgModel.h"
#include "core/tgSimViewGraphics.h"
#include "core/tgSimulation.h"
#include "core/tgWorld.h"
#include "tgcreator/tgUtil.h"
// The Bullet Physics Library
#include "LinearMath/btVector3.h"
#include "LinearMath/btQuaternion.h"
// The C++ Standard Library
#include <iostream>
/**
* The entry point.
* @param[in] argc the number of command-line arguments
* @param[in] argv argv[0] is the executable name
* @return 0
*/
int main(int argc, char** argv)
{
std::cout << "AppObstacleTest" << std::endl;
// First create the ground and world. Specify ground rotation in radians
const double yaw = 0.0;
const double pitch = 0.0;
const double roll = 0.0;
const tgBoxGround::Config groundConfig(btVector3(yaw, pitch, roll));
// the world will delete this
tgBoxGround* ground = new tgBoxGround(groundConfig);
btVector3 eulerAngles = btVector3(0.0, 0.0, 0.0);
btScalar friction = 0.5;
btScalar restitution = 0.0;
// Size doesn't affect hilly terrain
btVector3 size = btVector3(0.0, 0.1, 0.0);
btVector3 origin = btVector3(0.0, 0.0, 0.0);
size_t nx = 100;
size_t ny = 100;
double margin = 0.5;
double triangleSize = 5.0;
double waveHeight = 3.0;
double offset = 0.0;
tgHillyGround::Config hillGroundConfig(eulerAngles, friction, restitution,
size, origin, nx, ny, margin, triangleSize,
waveHeight, offset);
const tgWorld::Config config(98.1); // gravity, cm/sec^2
tgWorld world(config, ground);
// Second create the view
const double timestep_physics = 1.0/1000.0; // seconds
const double timestep_graphics = 1.f/60.f; // seconds
tgSimViewGraphics view(world, timestep_physics, timestep_graphics);
// Third create the simulation
tgSimulation simulation(view);
btVector3 position(0.0, 0.0, 0.0);
// Fourth create the models with their controllers and add the models to the
// simulation
tgBlockField* myObstacle = new tgBlockField();
// Add the model to the world
simulation.addModel(myObstacle);
tgStairs* bigStairs = new tgStairs();
// Add the stairs to the world
simulation.addModel(bigStairs);
for (int i = 0; i < 3; i++)
{
simulation.run(10);
if (i %2 == 0)
{
// World will delete prior pointer, so make a new one each time
tgHillyGround* hillGround = new tgHillyGround(hillGroundConfig);
world.reset(hillGround);
}
else
{
ground = new tgBoxGround(groundConfig);
world.reset(ground);
}
simulation.reset();
}
return 0;
}
<commit_msg>Example of obstacle use<commit_after>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file AppObstacleTest.cpp
* @brief Contains the definition function main() for testing new obstacles
* @author Brian Mirletz
* $Id$
*/
// This application
#include "tgBlockField.h"
#include "tgStairs.h"
// This library
#include "core/terrain/tgBoxGround.h"
#include "core/terrain/tgEmptyGround.h"
#include "core/terrain/tgHillyGround.h"
#include "core/tgModel.h"
#include "core/tgSimViewGraphics.h"
#include "core/tgSimulation.h"
#include "core/tgWorld.h"
#include "tgcreator/tgUtil.h"
// The Bullet Physics Library
#include "LinearMath/btVector3.h"
#include "LinearMath/btQuaternion.h"
// The C++ Standard Library
#include <iostream>
/**
* The entry point.
* @param[in] argc the number of command-line arguments
* @param[in] argv argv[0] is the executable name
* @return 0
*/
int main(int argc, char** argv)
{
std::cout << "AppObstacleTest" << std::endl;
// First create the ground and world. Specify ground rotation in radians
const double yaw = 0.0;
const double pitch = 0.0;
const double roll = 0.0;
const tgBoxGround::Config groundConfig(btVector3(yaw, pitch, roll));
// the world will delete this
tgBoxGround* ground = new tgBoxGround(groundConfig);
btVector3 eulerAngles = btVector3(0.0, 0.0, 0.0);
btScalar friction = 0.5;
btScalar restitution = 0.0;
// Size doesn't affect hilly terrain
btVector3 size = btVector3(0.0, 0.1, 0.0);
btVector3 origin = btVector3(0.0, 0.0, 0.0);
size_t nx = 100;
size_t ny = 100;
double margin = 0.5;
double triangleSize = 5.0;
double waveHeight = 3.0;
double offset = 0.0;
tgHillyGround::Config hillGroundConfig(eulerAngles, friction, restitution,
size, origin, nx, ny, margin, triangleSize,
waveHeight, offset);
const tgWorld::Config config(98.1); // gravity, cm/sec^2
tgWorld world(config, ground);
// Second create the view
const double timestep_physics = 1.0/1000.0; // seconds
const double timestep_graphics = 1.f/60.f; // seconds
tgSimViewGraphics view(world, timestep_physics, timestep_graphics);
// Third create the simulation
tgSimulation simulation(view);
btVector3 position(0.0, 0.0, 0.0);
// Fourth create the models with their controllers and add the models to the
// simulation
tgBlockField* myObstacle = new tgBlockField();
// Add the model to the world
simulation.addModel(myObstacle);
tgStairs* bigStairs = new tgStairs();
// Add the stairs to the world
simulation.addObstacle(bigStairs);
for (int i = 0; i < 3; i++)
{
simulation.run(10);
if (i %2 == 0)
{
// World will delete prior pointer, so make a new one each time
tgHillyGround* hillGround = new tgHillyGround(hillGroundConfig);
world.reset(hillGround);
}
else
{
ground = new tgBoxGround(groundConfig);
world.reset(ground);
}
simulation.reset();
}
return 0;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <popt.h>
#include "defs.hh"
#include "StringSet.hh"
#include "FactorEncoder.hh"
#include "Unigrams.hh"
#include "Bigrams.hh"
using namespace std;
int main(int argc, char* argv[]) {
float cutoff_value = 0.0;
int n_candidates_per_iter = 5000;
int removals_per_iter = 5000;
int target_vocab_size = 30000;
flt_type one_char_min_lp = -25.0;
string initial_transitions_fname;
string wordlist_fname;
string msfg_fname;
string transition_fname;
// Popt documentation:
// http://linux.die.net/man/3/popt
// http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html
poptContext pc;
struct poptOption po[] = {
{"candidates", 'c', POPT_ARG_INT, &n_candidates_per_iter, 11002, NULL, "Number of candidate subwords to try to remove per iteration"},
{"removals", 'r', POPT_ARG_INT, &removals_per_iter, 11003, NULL, "Number of removals per iteration"},
{"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"},
POPT_AUTOHELP
{NULL}
};
pc = poptGetContext(NULL, argc, (const char **)argv, po, 0);
poptSetOtherOptionHelp(pc, "[INITIAL TRANSITIONS] [WORDLIST] [MSFG_IN] [TRANSITIONS]");
int val;
while ((val = poptGetNextOpt(pc)) >= 0)
continue;
// poptGetNextOpt returns -1 when the final argument has been parsed
// otherwise an error occured
if (val != -1) {
switch (val) {
case POPT_ERROR_NOARG:
cerr << "Argument missing for an option" << endl;
exit(1);
case POPT_ERROR_BADOPT:
cerr << "Option's argument could not be parsed" << endl;
exit(1);
case POPT_ERROR_BADNUMBER:
case POPT_ERROR_OVERFLOW:
cerr << "Option could not be converted to number" << endl;
exit(1);
default:
cerr << "Unknown error in option processing" << endl;
exit(1);
}
}
// Handle ARG part of command line
if (poptPeekArg(pc) != NULL)
initial_transitions_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Initial vocabulary file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
wordlist_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Wordlist file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
msfg_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Input MSFG file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
transition_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Transition file not set" << endl;
exit(1);
}
cerr << "parameters, initial transitions: " << initial_transitions_fname << endl;
cerr << "parameters, wordlist: " << wordlist_fname << endl;
cerr << "parameters, msfg: " << msfg_fname << endl;
cerr << "parameters, transitions: " << transition_fname << endl;
cerr << "parameters, candidates per iteration: " << n_candidates_per_iter << endl;
cerr << "parameters, removals per iteration: " << removals_per_iter << endl;
cerr << "parameters, target vocab size: " << target_vocab_size << endl;
int maxlen, word_maxlen;
string start_end_symbol("*");
map<string, flt_type> all_chars;
map<string, flt_type> freqs;
map<string, flt_type> words;
MultiStringFactorGraph msfg(start_end_symbol);
transitions_t transitions;
transitions_t trans_stats;
map<string, flt_type> unigram_stats;
cerr << "Reading initial transitions " << initial_transitions_fname << endl;
int retval = Bigrams::read_transitions(transitions, initial_transitions_fname);
if (retval < 0) {
cerr << "something went wrong reading transitions" << endl;
exit(0);
}
cerr << "Reading word list " << wordlist_fname << endl;
retval = Unigrams::read_vocab(wordlist_fname, words, word_maxlen);
if (retval < 0) {
cerr << "something went wrong reading word list" << endl;
exit(0);
}
cerr << "\t" << "wordlist size: " << words.size() << endl;
cerr << "\t" << "maximum word length: " << word_maxlen << endl;
cerr << "Reading msfg " << msfg_fname << endl;
msfg.read(msfg_fname);
if (transitions.size() < msfg.factor_node_map.size()) {
vector<string> to_remove;
cerr << "Pruning " << msfg.factor_node_map.size()-transitions.size() << " unused transitions from msfg." << endl;
for (auto it = msfg.factor_node_map.begin(); it != msfg.factor_node_map.end(); ++it)
if (transitions.find(it->first) == transitions.end())
to_remove.push_back(it->first);
for (auto it = to_remove.begin(); it != to_remove.end(); ++it)
msfg.remove_arcs(*it);
}
assign_scores(transitions, msfg);
std::cerr << std::setprecision(15);
int iteration = 1;
while (true) {
cerr << "Iteration " << iteration << endl;
flt_type lp = Bigrams::collect_trans_stats(words, msfg, trans_stats, unigram_stats);
Bigrams::copy_transitions(trans_stats, transitions);
Bigrams::normalize(transitions);
cerr << "\tbigram cost: " << lp << endl;
cerr << "\tamount of transitions: " << Bigrams::transition_count(transitions) << endl;
cerr << "\tvocab size: " << transitions.size() << endl;
// Get removal candidates based on unigram stats
cerr << "\tinitializing removals .." << endl;
map<string, flt_type> candidates;
Bigrams::init_removal_candidates(n_candidates_per_iter, unigram_stats, candidates);
// Score all candidates
cerr << "\tranking removals .." << endl;
Bigrams::rank_removal_candidates(words, msfg, unigram_stats, transitions, candidates);
// Remove least significant subwords
vector<pair<string, flt_type> > sorted_scores;
Unigrams::sort_vocab(candidates, sorted_scores, true);
vector<string> to_remove;
for (auto it = sorted_scores.begin(); it != sorted_scores.end(); ++it) {
to_remove.push_back(it->first);
if (iteration == 1) {
if ((to_remove.size() >= transitions.size() % 1000) && (to_remove.size() > 0)) break;
}
else if (to_remove.size() >= removals_per_iter) break;
}
Bigrams::remove_transitions(to_remove, transitions);
for (auto it = to_remove.begin(); it != to_remove.end(); ++it)
msfg.remove_arcs(*it);
// Write temp transitions
ostringstream transitions_temp;
transitions_temp << "transitions.iter" << iteration << ".bz2";
cerr << "\twriting to: " << transitions_temp.str() << endl;
Bigrams::write_transitions(transitions, transitions_temp.str());
if (transitions.size() <= target_vocab_size) break;
iteration++;
}
// Write transitions
Bigrams::write_transitions(transitions, transition_fname);
exit(1);
}
<commit_msg>Write transitions after normalization.<commit_after>#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <popt.h>
#include "defs.hh"
#include "StringSet.hh"
#include "FactorEncoder.hh"
#include "Unigrams.hh"
#include "Bigrams.hh"
using namespace std;
int main(int argc, char* argv[]) {
float cutoff_value = 0.0;
int n_candidates_per_iter = 5000;
int removals_per_iter = 5000;
int target_vocab_size = 30000;
flt_type one_char_min_lp = -25.0;
string initial_transitions_fname;
string wordlist_fname;
string msfg_fname;
string transition_fname;
// Popt documentation:
// http://linux.die.net/man/3/popt
// http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html
poptContext pc;
struct poptOption po[] = {
{"candidates", 'c', POPT_ARG_INT, &n_candidates_per_iter, 11002, NULL, "Number of candidate subwords to try to remove per iteration"},
{"removals", 'r', POPT_ARG_INT, &removals_per_iter, 11003, NULL, "Number of removals per iteration"},
{"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"},
POPT_AUTOHELP
{NULL}
};
pc = poptGetContext(NULL, argc, (const char **)argv, po, 0);
poptSetOtherOptionHelp(pc, "[INITIAL TRANSITIONS] [WORDLIST] [MSFG_IN] [TRANSITIONS]");
int val;
while ((val = poptGetNextOpt(pc)) >= 0)
continue;
// poptGetNextOpt returns -1 when the final argument has been parsed
// otherwise an error occured
if (val != -1) {
switch (val) {
case POPT_ERROR_NOARG:
cerr << "Argument missing for an option" << endl;
exit(1);
case POPT_ERROR_BADOPT:
cerr << "Option's argument could not be parsed" << endl;
exit(1);
case POPT_ERROR_BADNUMBER:
case POPT_ERROR_OVERFLOW:
cerr << "Option could not be converted to number" << endl;
exit(1);
default:
cerr << "Unknown error in option processing" << endl;
exit(1);
}
}
// Handle ARG part of command line
if (poptPeekArg(pc) != NULL)
initial_transitions_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Initial vocabulary file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
wordlist_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Wordlist file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
msfg_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Input MSFG file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
transition_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Transition file not set" << endl;
exit(1);
}
cerr << "parameters, initial transitions: " << initial_transitions_fname << endl;
cerr << "parameters, wordlist: " << wordlist_fname << endl;
cerr << "parameters, msfg: " << msfg_fname << endl;
cerr << "parameters, transitions: " << transition_fname << endl;
cerr << "parameters, candidates per iteration: " << n_candidates_per_iter << endl;
cerr << "parameters, removals per iteration: " << removals_per_iter << endl;
cerr << "parameters, target vocab size: " << target_vocab_size << endl;
int maxlen, word_maxlen;
string start_end_symbol("*");
map<string, flt_type> all_chars;
map<string, flt_type> freqs;
map<string, flt_type> words;
MultiStringFactorGraph msfg(start_end_symbol);
transitions_t transitions;
transitions_t trans_stats;
map<string, flt_type> unigram_stats;
cerr << "Reading initial transitions " << initial_transitions_fname << endl;
int retval = Bigrams::read_transitions(transitions, initial_transitions_fname);
if (retval < 0) {
cerr << "something went wrong reading transitions" << endl;
exit(0);
}
cerr << "Reading word list " << wordlist_fname << endl;
retval = Unigrams::read_vocab(wordlist_fname, words, word_maxlen);
if (retval < 0) {
cerr << "something went wrong reading word list" << endl;
exit(0);
}
cerr << "\t" << "wordlist size: " << words.size() << endl;
cerr << "\t" << "maximum word length: " << word_maxlen << endl;
cerr << "Reading msfg " << msfg_fname << endl;
msfg.read(msfg_fname);
if (transitions.size() < msfg.factor_node_map.size()) {
vector<string> to_remove;
cerr << "Pruning " << msfg.factor_node_map.size()-transitions.size() << " unused transitions from msfg." << endl;
for (auto it = msfg.factor_node_map.begin(); it != msfg.factor_node_map.end(); ++it)
if (transitions.find(it->first) == transitions.end())
to_remove.push_back(it->first);
for (auto it = to_remove.begin(); it != to_remove.end(); ++it)
msfg.remove_arcs(*it);
}
assign_scores(transitions, msfg);
std::cerr << std::setprecision(15);
int iteration = 1;
while (true) {
cerr << "Iteration " << iteration << endl;
flt_type lp = Bigrams::collect_trans_stats(words, msfg, trans_stats, unigram_stats);
Bigrams::copy_transitions(trans_stats, transitions);
Bigrams::normalize(transitions);
cerr << "\tbigram cost: " << lp << endl;
cerr << "\tamount of transitions: " << Bigrams::transition_count(transitions) << endl;
cerr << "\tvocab size: " << transitions.size() << endl;
// Write temp transitions
ostringstream transitions_temp;
transitions_temp << "transitions.iter" << iteration << ".bz2";
cerr << "\twriting to: " << transitions_temp.str() << endl;
Bigrams::write_transitions(transitions, transitions_temp.str());
// Get removal candidates based on unigram stats
cerr << "\tinitializing removals .." << endl;
map<string, flt_type> candidates;
Bigrams::init_removal_candidates(n_candidates_per_iter, unigram_stats, candidates);
// Score all candidates
cerr << "\tranking removals .." << endl;
Bigrams::rank_removal_candidates(words, msfg, unigram_stats, transitions, candidates);
// Remove least significant subwords
vector<pair<string, flt_type> > sorted_scores;
Unigrams::sort_vocab(candidates, sorted_scores, true);
vector<string> to_remove;
for (auto it = sorted_scores.begin(); it != sorted_scores.end(); ++it) {
to_remove.push_back(it->first);
if (iteration == 1 && transitions.size() % 1000 != 0) {
if ((to_remove.size() >= transitions.size() % 1000) && (to_remove.size() > 0)) break;
}
else if (to_remove.size() >= removals_per_iter) break;
}
Bigrams::remove_transitions(to_remove, transitions);
for (auto it = to_remove.begin(); it != to_remove.end(); ++it)
msfg.remove_arcs(*it);
if (transitions.size() <= target_vocab_size) break;
iteration++;
}
// Write transitions
Bigrams::write_transitions(transitions, transition_fname);
exit(1);
}
<|endoftext|> |
<commit_before>//
// StoreJsonSerializer.cpp
// Pods
//
// Created by eps on 7/1/20.
//
#include "ee/store/private/StoreJsonSerializer.hpp"
#include <ee/nlohmann/json.hpp>
#include "ee/store/StoreProductDefinition.hpp"
#include "ee/store/StoreProductMetadata.hpp"
#include "ee/store/private/StoreProductDescription.hpp"
#include "ee/store/private/StorePurchaseFailureDescription.hpp"
#include "ee/store/private/StorePurchaseFailureReason.hpp"
namespace ee {
namespace store {
using Self = JsonSerializer;
void to_json(nlohmann::json& json,
const std::shared_ptr<ProductDefinition>& value) {
json["id"] = value->id();
json["storeSpecificId"] = value->storeSpecificId();
json["type"] = value->type();
}
void to_json(nlohmann::json& json,
const std::shared_ptr<ProductMetadata>& value) {
json["localizedPriceString"] = value->localizedPriceString();
json["localizedTitle"] = value->localizedTitle();
json["localizedDescription"] = value->localizedDescription();
json["isoCurrencyCode"] = value->isoCurrencyCode();
json["localizedPrice"] = value->localizedPrice();
}
void from_json(const nlohmann::json& json,
std::shared_ptr<ProductMetadata>& value) {
value = std::make_shared<ProductMetadata>(json["localizedPriceString"], //
json["localizedTitle"], //
json["localizedDescription"],
json["isoCurrencyCode"],
json["localizedPrice"]);
}
void to_json(nlohmann::json& json,
const std::shared_ptr<ProductDescription>& value) {
json["storeSpecificId"] = value->storeSpecificId();
json["metadata"] = value->metadata();
json["receipt"] = value->receipt();
json["transactionId"] = value->transactionId();
}
void from_json(const nlohmann::json& json,
std::shared_ptr<ProductDescription>& value) {
value = std::make_shared<ProductDescription>(
json["storeSpecificId"], //
json["metadata"], //
json.value("receipt", ""), //
json.value("transactionId", ""),
json.value("type", ProductType::NonConsumable));
}
std::string Self::serializeProductDefinition(
const std::shared_ptr<ProductDefinition>& product) {
nlohmann::json json = product;
return json.dump();
}
std::string Self::serializeProductDefinitions(
const std::vector<std::shared_ptr<ProductDefinition>>& products) {
nlohmann::json json;
for (auto&& product : products) {
json.push_back(product);
}
return json.dump();
}
std::string Self::serializeProductDescription(
const std::shared_ptr<ProductDescription>& product) {
nlohmann::json json = product;
return json.dump();
}
std::string Self::serializeProductDescriptions(
const std::vector<std::shared_ptr<ProductDescription>>& products) {
nlohmann::json json;
for (auto&& product : products) {
json.push_back(product);
}
return json.dump();
}
std::vector<std::shared_ptr<ProductDescription>>
Self::deserializeProductDescriptions(const std::string& str) {
auto json = nlohmann::json::parse(str);
return json;
}
std::map<std::string, std::string>
Self::deserializeSubscriptionDescriptions(const std::string& json) {
auto objectList = nlohmann::json::parse(json);
std::map<std::string, std::string> dictionary1;
for (auto&& dictionary2 : objectList) {
auto&& dic = dictionary2["metadata"];
auto key = dictionary2["storeSpecificId"].get<std::string>();
nlohmann::json dictionary3;
dictionary3["introductoryPrice"] = dic["introductoryPrice"];
dictionary3["introductoryPriceLocale"] = dic["introductoryPriceLocale"];
dictionary3["introductoryPriceNumberOfPeriods"] =
dic["introductoryPriceNumberOfPeriods"];
dictionary3["numberOfUnits"] = dic["numberOfUnits"];
dictionary3["unit"] = dic["unit"];
if (not dictionary3["numberOfUnits"].is_null() &&
dictionary3["unit"].is_null()) {
dictionary3["unit"] = 0;
}
dictionary1[key] = dictionary3.dump();
}
return dictionary1;
}
std::map<std::string, std::string>
Self::deserializeProductDetails(const std::string& json) {
auto objectList = nlohmann::json::parse(json);
std::map<std::string, std::string> dictionary1;
for (auto&& dictionary2 : objectList) {
auto&& dic = dictionary2["metadata"];
auto key = dictionary2["storeSpecificId"].get<std::string>();
nlohmann::json dictionary3;
dictionary3["subscriptionNumberOfUnits"] =
dic["subscriptionNumberOfUnits"];
dictionary3["subscriptionPeriodUnit"] = dic["subscriptionPeriodUnit"];
dictionary3["localizedPrice"] = dic["localizedPrice"];
dictionary3["isoCurrencyCode"] = dic["isoCurrencyCode"];
dictionary3["localizedPriceString"] = dic["localizedPriceString"];
dictionary3["localizedTitle"] = dic["localizedTitle"];
dictionary3["localizedDescription"] = dic["localizedDescription"];
dictionary3["introductoryPrice"] = dic["introductoryPrice"];
dictionary3["introductoryPriceLocale"] = dic["introductoryPriceLocale"];
dictionary3["introductoryPriceNumberOfPeriods"] =
dic["introductoryPriceNumberOfPeriods"];
dictionary3["numberOfUnits"] = dic["numberOfUnits"];
dictionary3["unit"] = dic["unit"];
if (not dictionary3["subscriptionNumberOfUnits"].is_null() &&
dictionary3["subscriptionPeriodUnit"].is_null()) {
dictionary3["subscriptionPeriodUnit"] = 0;
}
if (not dictionary3["numberOfUnits"].is_null() &&
dictionary3["unit"].is_null()) {
dictionary3["unit"] = "0";
}
dictionary1[key] = dictionary3.dump();
}
return dictionary1;
}
PurchaseFailureDescription
Self::deserializeFailureReason(const std::string& json) {
using Enum = PurchaseFailureReason;
static std::map<std::string, Enum> strToEnum{
{"PurchasingUnavailable", Enum::PurchasingUnavailable},
{"ExistingPurchasePending", Enum::ExistingPurchasePending},
{"ProductUnavailable", Enum::ProductUnavailable},
{"SignatureInvalid", Enum::SignatureInvalid},
{"UserCancelled", Enum::UserCancelled},
{"PaymentDeclined", Enum::PaymentDeclined},
{"DuplicateTransaction", Enum::DuplicateTransaction}};
auto dic = nlohmann::json::parse(json);
auto reason = PurchaseFailureReason::Unknown;
auto iter = strToEnum.find(dic["reason"]);
if (iter != strToEnum.cend()) {
reason = iter->second;
}
return PurchaseFailureDescription(dic["productId"], reason, dic["message"]);
}
} // namespace store
} // namespace ee
<commit_msg>Fix serializing enum.<commit_after>//
// StoreJsonSerializer.cpp
// Pods
//
// Created by eps on 7/1/20.
//
#include "ee/store/private/StoreJsonSerializer.hpp"
#include <ee/nlohmann/json.hpp>
#include "ee/store/StoreProductDefinition.hpp"
#include "ee/store/StoreProductMetadata.hpp"
#include "ee/store/private/StoreProductDescription.hpp"
#include "ee/store/private/StorePurchaseFailureDescription.hpp"
#include "ee/store/private/StorePurchaseFailureReason.hpp"
namespace ee {
namespace store {
using Self = JsonSerializer;
void to_json(nlohmann::json& json,
const std::shared_ptr<ProductDefinition>& value) {
json["id"] = value->id();
json["storeSpecificId"] = value->storeSpecificId();
json["type"] = value->type();
}
void to_json(nlohmann::json& json,
const std::shared_ptr<ProductMetadata>& value) {
json["localizedPriceString"] = value->localizedPriceString();
json["localizedTitle"] = value->localizedTitle();
json["localizedDescription"] = value->localizedDescription();
json["isoCurrencyCode"] = value->isoCurrencyCode();
json["localizedPrice"] = value->localizedPrice();
}
void from_json(const nlohmann::json& json,
std::shared_ptr<ProductMetadata>& value) {
value = std::make_shared<ProductMetadata>(json["localizedPriceString"], //
json["localizedTitle"], //
json["localizedDescription"],
json["isoCurrencyCode"],
json["localizedPrice"]);
}
void to_json(nlohmann::json& json,
const std::shared_ptr<ProductDescription>& value) {
json["storeSpecificId"] = value->storeSpecificId();
json["metadata"] = value->metadata();
json["receipt"] = value->receipt();
json["transactionId"] = value->transactionId();
}
void from_json(const nlohmann::json& json,
std::shared_ptr<ProductDescription>& value) {
value = std::make_shared<ProductDescription>(
json["storeSpecificId"], //
json["metadata"], //
json.value("receipt", ""), //
json.value("transactionId", ""),
json.value("type", ProductType::NonConsumable));
}
std::string Self::serializeProductDefinition(
const std::shared_ptr<ProductDefinition>& product) {
nlohmann::json json = product;
return json.dump();
}
std::string Self::serializeProductDefinitions(
const std::vector<std::shared_ptr<ProductDefinition>>& products) {
nlohmann::json json;
for (auto&& product : products) {
json.push_back(product);
}
return json.dump();
}
std::string Self::serializeProductDescription(
const std::shared_ptr<ProductDescription>& product) {
nlohmann::json json = product;
return json.dump();
}
std::string Self::serializeProductDescriptions(
const std::vector<std::shared_ptr<ProductDescription>>& products) {
nlohmann::json json;
for (auto&& product : products) {
json.push_back(product);
}
return json.dump();
}
std::vector<std::shared_ptr<ProductDescription>>
Self::deserializeProductDescriptions(const std::string& str) {
auto json = nlohmann::json::parse(str);
return json;
}
std::map<std::string, std::string>
Self::deserializeSubscriptionDescriptions(const std::string& json) {
auto objectList = nlohmann::json::parse(json);
std::map<std::string, std::string> dictionary1;
for (auto&& dictionary2 : objectList) {
auto&& dic = dictionary2["metadata"];
auto key = dictionary2["storeSpecificId"].get<std::string>();
nlohmann::json dictionary3;
dictionary3["introductoryPrice"] = dic["introductoryPrice"];
dictionary3["introductoryPriceLocale"] = dic["introductoryPriceLocale"];
dictionary3["introductoryPriceNumberOfPeriods"] =
dic["introductoryPriceNumberOfPeriods"];
dictionary3["numberOfUnits"] = dic["numberOfUnits"];
dictionary3["unit"] = dic["unit"];
if (not dictionary3["numberOfUnits"].is_null() &&
dictionary3["unit"].is_null()) {
dictionary3["unit"] = 0;
}
dictionary1[key] = dictionary3.dump();
}
return dictionary1;
}
std::map<std::string, std::string>
Self::deserializeProductDetails(const std::string& json) {
auto objectList = nlohmann::json::parse(json);
std::map<std::string, std::string> dictionary1;
for (auto&& dictionary2 : objectList) {
auto&& dic = dictionary2["metadata"];
auto key = dictionary2["storeSpecificId"].get<std::string>();
nlohmann::json dictionary3;
dictionary3["subscriptionNumberOfUnits"] =
dic["subscriptionNumberOfUnits"];
dictionary3["subscriptionPeriodUnit"] = dic["subscriptionPeriodUnit"];
dictionary3["localizedPrice"] = dic["localizedPrice"];
dictionary3["isoCurrencyCode"] = dic["isoCurrencyCode"];
dictionary3["localizedPriceString"] = dic["localizedPriceString"];
dictionary3["localizedTitle"] = dic["localizedTitle"];
dictionary3["localizedDescription"] = dic["localizedDescription"];
dictionary3["introductoryPrice"] = dic["introductoryPrice"];
dictionary3["introductoryPriceLocale"] = dic["introductoryPriceLocale"];
dictionary3["introductoryPriceNumberOfPeriods"] =
dic["introductoryPriceNumberOfPeriods"];
dictionary3["numberOfUnits"] = dic["numberOfUnits"];
dictionary3["unit"] = dic["unit"];
if (not dictionary3["subscriptionNumberOfUnits"].is_null() &&
dictionary3["subscriptionPeriodUnit"].is_null()) {
dictionary3["subscriptionPeriodUnit"] = 0;
}
if (not dictionary3["numberOfUnits"].is_null() &&
dictionary3["unit"].is_null()) {
dictionary3["unit"] = "0";
}
dictionary1[key] = dictionary3.dump();
}
return dictionary1;
}
PurchaseFailureDescription
Self::deserializeFailureReason(const std::string& json) {
using Enum = PurchaseFailureReason;
static std::map<int, Enum> intToEnum{
{0, Enum::PurchasingUnavailable},
{1, Enum::ExistingPurchasePending},
{2, Enum::ProductUnavailable},
{3, Enum::SignatureInvalid},
{4, Enum::UserCancelled},
{5, Enum::PaymentDeclined},
{6, Enum::DuplicateTransaction}};
auto dic = nlohmann::json::parse(json);
auto reason = PurchaseFailureReason::Unknown;
auto iter = intToEnum.find(dic["reason"]);
if (iter != intToEnum.cend()) {
reason = iter->second;
}
return PurchaseFailureDescription(dic["productId"], reason, dic["message"]);
}
} // namespace store
} // namespace ee
<|endoftext|> |
<commit_before>//===- DlltoolDriver.cpp - dlltool.exe-compatible driver ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Defines an interface to a dlltool.exe-compatible driver.
//
//===----------------------------------------------------------------------===//
#include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/COFFImportFile.h"
#include "llvm/Object/COFFModuleDefinition.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Path.h"
#include <vector>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::COFF;
namespace {
enum {
OPT_INVALID = 0,
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
#include "Options.inc"
#undef OPTION
};
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
static const llvm::opt::OptTable::Info InfoTable[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
class DllOptTable : public llvm::opt::OptTable {
public:
DllOptTable() : OptTable(InfoTable, false) {}
};
} // namespace
// Opens a file. Path has to be resolved already.
static std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB = MemoryBuffer::getFile(Path);
if (std::error_code EC = MB.getError()) {
llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
return nullptr;
}
return std::move(*MB);
}
static MachineTypes getEmulation(StringRef S) {
return StringSwitch<MachineTypes>(S)
.Case("i386", IMAGE_FILE_MACHINE_I386)
.Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
.Case("arm", IMAGE_FILE_MACHINE_ARMNT)
.Case("arm64", IMAGE_FILE_MACHINE_ARM64)
.Default(IMAGE_FILE_MACHINE_UNKNOWN);
}
static std::string getImplibPath(StringRef Path) {
SmallString<128> Out = StringRef("lib");
Out.append(Path);
sys::path::replace_extension(Out, ".a");
return Out.str();
}
int llvm::dlltoolDriverMain(llvm::ArrayRef<const char *> ArgsArr) {
DllOptTable Table;
unsigned MissingIndex;
unsigned MissingCount;
llvm::opt::InputArgList Args =
Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
if (MissingCount) {
llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
return 1;
}
// Handle when no input or output is specified
if (Args.hasArgNoClaim(OPT_INPUT) ||
(!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) {
Table.PrintHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool",
false);
llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64\n";
return 1;
}
if (!Args.hasArgNoClaim(OPT_m) && Args.hasArgNoClaim(OPT_d)) {
llvm::errs() << "error: no target machine specified\n"
<< "supported targets: i386, i386:x86-64, arm, arm64\n";
return 1;
}
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
<< "\n";
if (!Args.hasArg(OPT_d)) {
llvm::errs() << "no definition file specified\n";
return 1;
}
std::unique_ptr<MemoryBuffer> MB =
openFile(Args.getLastArg(OPT_d)->getValue());
if (!MB)
return 1;
if (!MB->getBufferSize()) {
llvm::errs() << "definition file empty\n";
return 1;
}
COFF::MachineTypes Machine = IMAGE_FILE_MACHINE_UNKNOWN;
if (auto *Arg = Args.getLastArg(OPT_m))
Machine = getEmulation(Arg->getValue());
if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
llvm::errs() << "unknown target\n";
return 1;
}
Expected<COFFModuleDefinition> Def =
parseCOFFModuleDefinition(*MB, Machine, true);
if (!Def) {
llvm::errs() << "error parsing definition\n"
<< errorToErrorCode(Def.takeError()).message();
return 1;
}
// Do this after the parser because parseCOFFModuleDefinition sets OutputFile.
if (auto *Arg = Args.getLastArg(OPT_D))
Def->OutputFile = Arg->getValue();
if (Def->OutputFile.empty()) {
llvm::errs() << "no DLL name specified\n";
return 1;
}
std::string Path = Args.getLastArgValue(OPT_l);
if (Path.empty())
Path = getImplibPath(Def->OutputFile);
if (Machine == IMAGE_FILE_MACHINE_I386 && Args.getLastArg(OPT_k)) {
for (COFFShortExport& E : Def->Exports) {
if (!E.AliasTarget.empty() || (!E.Name.empty() && E.Name[0] == '?'))
continue;
E.SymbolName = E.Name;
// Trim off the trailing decoration. Symbols will always have a
// starting prefix here (either _ for cdecl/stdcall, @ for fastcall
// or ? for C++ functions). Vectorcall functions won't have any
// fixed prefix, but the function base name will still be at least
// one char.
E.Name = E.Name.substr(0, E.Name.find('@', 1));
// By making sure E.SymbolName != E.Name for decorated symbols,
// writeImportLibrary writes these symbols with the type
// IMPORT_NAME_UNDECORATE.
E.ExtName = E.ExtName.substr(0, E.ExtName.find('@', 1));
}
}
if (writeImportLibrary(Def->OutputFile, Path, Def->Exports, Machine, true))
return 1;
return 0;
}
<commit_msg>[llvm-dlltool] Remove support for implying output name<commit_after>//===- DlltoolDriver.cpp - dlltool.exe-compatible driver ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Defines an interface to a dlltool.exe-compatible driver.
//
//===----------------------------------------------------------------------===//
#include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/COFFImportFile.h"
#include "llvm/Object/COFFModuleDefinition.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Path.h"
#include <vector>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::COFF;
namespace {
enum {
OPT_INVALID = 0,
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
#include "Options.inc"
#undef OPTION
};
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
static const llvm::opt::OptTable::Info InfoTable[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
class DllOptTable : public llvm::opt::OptTable {
public:
DllOptTable() : OptTable(InfoTable, false) {}
};
} // namespace
// Opens a file. Path has to be resolved already.
static std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB = MemoryBuffer::getFile(Path);
if (std::error_code EC = MB.getError()) {
llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
return nullptr;
}
return std::move(*MB);
}
static MachineTypes getEmulation(StringRef S) {
return StringSwitch<MachineTypes>(S)
.Case("i386", IMAGE_FILE_MACHINE_I386)
.Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
.Case("arm", IMAGE_FILE_MACHINE_ARMNT)
.Case("arm64", IMAGE_FILE_MACHINE_ARM64)
.Default(IMAGE_FILE_MACHINE_UNKNOWN);
}
int llvm::dlltoolDriverMain(llvm::ArrayRef<const char *> ArgsArr) {
DllOptTable Table;
unsigned MissingIndex;
unsigned MissingCount;
llvm::opt::InputArgList Args =
Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
if (MissingCount) {
llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
return 1;
}
// Handle when no input or output is specified
if (Args.hasArgNoClaim(OPT_INPUT) ||
(!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) {
Table.PrintHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool",
false);
llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64\n";
return 1;
}
if (!Args.hasArgNoClaim(OPT_m) && Args.hasArgNoClaim(OPT_d)) {
llvm::errs() << "error: no target machine specified\n"
<< "supported targets: i386, i386:x86-64, arm, arm64\n";
return 1;
}
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
<< "\n";
if (!Args.hasArg(OPT_d)) {
llvm::errs() << "no definition file specified\n";
return 1;
}
std::unique_ptr<MemoryBuffer> MB =
openFile(Args.getLastArg(OPT_d)->getValue());
if (!MB)
return 1;
if (!MB->getBufferSize()) {
llvm::errs() << "definition file empty\n";
return 1;
}
COFF::MachineTypes Machine = IMAGE_FILE_MACHINE_UNKNOWN;
if (auto *Arg = Args.getLastArg(OPT_m))
Machine = getEmulation(Arg->getValue());
if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
llvm::errs() << "unknown target\n";
return 1;
}
Expected<COFFModuleDefinition> Def =
parseCOFFModuleDefinition(*MB, Machine, true);
if (!Def) {
llvm::errs() << "error parsing definition\n"
<< errorToErrorCode(Def.takeError()).message();
return 1;
}
// Do this after the parser because parseCOFFModuleDefinition sets OutputFile.
if (auto *Arg = Args.getLastArg(OPT_D))
Def->OutputFile = Arg->getValue();
if (Def->OutputFile.empty()) {
llvm::errs() << "no DLL name specified\n";
return 1;
}
std::string Path = Args.getLastArgValue(OPT_l);
if (Machine == IMAGE_FILE_MACHINE_I386 && Args.getLastArg(OPT_k)) {
for (COFFShortExport& E : Def->Exports) {
if (!E.AliasTarget.empty() || (!E.Name.empty() && E.Name[0] == '?'))
continue;
E.SymbolName = E.Name;
// Trim off the trailing decoration. Symbols will always have a
// starting prefix here (either _ for cdecl/stdcall, @ for fastcall
// or ? for C++ functions). Vectorcall functions won't have any
// fixed prefix, but the function base name will still be at least
// one char.
E.Name = E.Name.substr(0, E.Name.find('@', 1));
// By making sure E.SymbolName != E.Name for decorated symbols,
// writeImportLibrary writes these symbols with the type
// IMPORT_NAME_UNDECORATE.
E.ExtName = E.ExtName.substr(0, E.ExtName.find('@', 1));
}
}
if (!Path.empty() &&
writeImportLibrary(Def->OutputFile, Path, Def->Exports, Machine, true))
return 1;
return 0;
}
<|endoftext|> |
<commit_before>#define CROW_ENABLE_SSL
#include <crow.h>
#include "kolmoconf.hh"
#include "comboaddress.hh"
#include <set>
#include <boost/utility/string_ref.hpp>
#include <sstream>
#include "http.hh"
/*
Welcome to the default free zone!
No single number or default can live here EVERYTHING comes from the configuration file.
The webserver serves URL of SITES which have NAMES and ALTERNATE NAMES.
URLs map to DIRECTORIES or ACTIONS (Redirects of various types)
A SITE listens on one or more IP address LISTENERS
LISTENERS can have settings too
Settings:
GLOBAL
Syslog on/off
LISTENER
Address
Port
Listen-limit
Free-bind / non-local
SITE
Domain Name
Alternate name
Make-canonical
Mapping / ->
DIRECTORY
Path /var/www/
Directory-listing: no
Mapping /new/ ->
ACTION
Target https://new.site/
Code 302
Password /data/ -> Passwords: default
PASSWORDS
Name: default
Entries: [{User: user, Password: password}]
*/
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::set;
using std::vector;
using std::string;
static int readFile(const boost::string_ref& path, std::string& content)
{
FILE* ffp=fopen(&path[0], "r");
if(!ffp) {
return -1;
}
std::shared_ptr<FILE> fp(ffp, fclose);
content.clear();
char buffer[4096];
size_t nbytes;
while((nbytes=fread(buffer,1,sizeof(buffer), fp.get()))!=0) {
content.append(buffer, nbytes);
}
return content.size();
}
string getPath(KolmoConf* kc, const crow::request& req, const std::string& rest, KolmoStruct** siteptr)
{
cout<<req.url<<endl;
auto f=req.headers.find("host");
if(f != req.headers.end()) {
string host=f->second;
auto pos = host.find(':');
if(pos != string::npos)
host.resize(pos);
cout<<"Host: "<<host<<endl;
auto sites = kc->d_main.getStruct("sites"); // XXX SHOULd BE TYPESAFE
for(const auto& m : sites->getMembers()) {
auto site = sites->getStruct(m);
if(site->getString("name")==host && site->getBool("enabled")) {
cout<<"Got it, should serve up to "<<site->getString("path")+"/"+rest<<endl;
*siteptr=site;
return site->getString("path")+"/"+rest;
}
}
}
return "";
}
void listenThread(KolmoConf* kc, ComboAddress ca)
try
{
crow::SimpleApp app;
bool tls{false};
auto func=[ca,kc,&tls](const crow::request& req, crow::response& resp, const std::string& a){
cerr<<"Request for "<<req.url<<" came in on "<<ca.toStringWithPort()<<", tls="<<tls<<endl;
KolmoStruct *site=0;
auto path=getPath(kc, req, a, &site);
if(!tls && site && site->getBool("redirect-to-https")) {
resp.code=301;
resp.set_header("Location", "https://"+site->getString("name")+req.url);
resp.body=R"(<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>ws</center>
</body>
</html>)";
resp.end();
return;
}
if(path.empty() || path.find("..") != string::npos) {
cerr<<"Can't find path for "<<req.url<<endl;
resp.code=404;
resp.body="Can't find URL";
resp.end();
return;
}
string content;
if(readFile(path, resp.body) < 0) {
resp.code=404;
resp.body="Can't find URL";
resp.end();
}
resp.set_header("Content-Type", pickContentType(path));
resp.end();
};
CROW_ROUTE(app, "/<path>")(func);
CROW_ROUTE(app, "/")([&func](const crow::request& rec, crow::response& resp) { return func(rec, resp, "/index.html");});
auto listeners=kc->d_main.getStruct("listeners");
for(const auto& m : listeners->getMembers()) {
ComboAddress pot(m);
if(pot==ca) {
cerr<<"Found a listener that applies!"<<endl;
auto listener=listeners->getStruct(m);
auto pemfile=listener->getString("pem-file");
auto certfile=listener->getString("cert-file");
auto keyfile=listener->getString("key-file");
if(!pemfile.empty()) {
cerr<<"Doing TLS on "<<ca.toStringWithPort()<<", pem-file: "<<pemfile<<endl;
tls=true;
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).ssl_file(pemfile).multithreaded().run();
cerr<<"Ended?"<<endl;
return;
}
else if(!certfile.empty()) {
tls=true;
cerr<<"Doing certfile TLS on "<<ca.toStringWithPort()<<", pem-file: "<<pemfile<<endl;
crow::ssl_context_t ctx{boost::asio::ssl::context::sslv23};
ctx.use_certificate_chain_file(certfile);
ctx.use_private_key_file(keyfile, crow::ssl_context_t::pem);
ctx.set_options(
boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::no_sslv3
);
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).ssl(std::move(ctx)).multithreaded().run();
cerr<<"Ended?"<<endl;
return;
}
}
}
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).multithreaded().run();
}
catch(std::exception& e)
{
cerr<<"Error from webserver for "<<ca.toString()<<": "<<e.what()<<endl;
}
std::atomic<bool> g_verbose;
void emitJSON(crow::response& resp, nlohmann::json& wv)
{
std::ostringstream str;
str << std::setw(4) << wv << endl;
resp.write(str.str());
resp.set_header("Content-Type","application/json");
resp.end();
}
void KolmoThread(KolmoConf* kc, ComboAddress ca)
{
crow::SimpleApp app;
CROW_ROUTE(app, "/full-config")([kc](const crow::request& rec, crow::response& resp) {
nlohmann::json wv;
KSToJson(&kc->d_main, wv);
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/minimal-config")([kc](const crow::request& rec, crow::response& resp) {
auto minimal=kc->getMinimalConfig();
nlohmann::json wv;
KSToJson(minimal.get(), wv);
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/delta-config")([kc](const crow::request& rec, crow::response& resp) {
auto minimal=kc->getRuntimeDiff();
nlohmann::json wv={};
KSToJson(minimal.get(), wv);
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/runtime/set-value")([kc](const crow::request& rec, crow::response& resp) {
cerr<<rec.url_params.get("variable")<<endl;
auto variable=rec.url_params.get("variable"), value=rec.url_params.get("value");
nlohmann::json wv;
try {
cerr<<"Setting '"<<variable<<"' to '"<<value<<"'"<<endl;
kc->d_main.setValueAt(variable, value);
wv["result"]="ok";
}catch(std::exception& e) {
wv["result"]="failure";
wv["reason"]=e.what();
}
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/ls<path>")([kc](const crow::request& rec, crow::response& resp, const std::string& path=std::string()) {
cerr<<path<<endl;
string rpath=path.substr(1);
KolmoStruct* ks=&kc->d_main;
if(!rpath.empty()) {
cerr<<"Traversing path"<<endl;
auto ptr=ks->getValueAt(rpath);
ks=dynamic_cast<KolmoStruct*>(ptr);
if(!ks) {
nlohmann::json item;
item["description"] = ptr->description;
item["runtime"] = ptr->runtime;
item["unit"] = ptr->unit;
item["mandatory"] = ptr->mandatory;
item["value"]=ptr->getValue();
item["default"]=ptr->defaultValue;
emitJSON(resp, item);
return;
}
}
nlohmann::json wv=nlohmann::json::object();
for(const auto& a : ks->getAll()) {
nlohmann::json item;
item["description"] = a.second->description;
item["runtime"] = a.second->runtime;
item["unit"] = a.second->unit;
item["mandatory"] = a.second->mandatory;
item["value"]=a.second->getValue();
item["default"]=a.second->defaultValue;
wv[a.first]=item;
}
emitJSON(resp, wv);
});
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).multithreaded().run();
}
int main(int argc, char** argv)
{
// crow::logger::setLogLevel(crow::LogLevel::Debug);
KolmoConf kc;
kc.initSchemaFromFile("ws-schema.lua");
kc.initConfigFromLua("ws.conf");
// kc.initConfigFromJSON("ws.json");
kc.declareRuntime();
kc.initConfigFromCmdline(argc, argv);
kc.d_main.tieBool("verbose", &g_verbose);
if(g_verbose) {
cerr<<"Must be verbose"<<endl;
cerr<<"Server name is "<<kc.d_main.getString("server-name")<<endl;
}
else {
cerr<<"Verbose is false"<<endl;
}
set<ComboAddress> listenAddresses;
auto sites = kc.d_main.getStruct("sites"); // XXX SHOULd BE TYPESAFE
for(const auto& m : sites->getMembers()) {
auto site = sites->getStruct(m);
cerr<<"["<<m<<"] We run a website called "<<site->getString("name")<<endl;
if(!site->getBool("enabled")) {
cerr<<"However, site is not enabled, skipping"<<endl;
}
else {
cerr<<"The site enable status: "<<site->getBool("enabled")<<endl;
cerr<<"We serve from path: "<<site->getString("path")<<endl;
cerr<<"We serve on addresses: ";
auto listeners = site->getStruct("listen");
for(const auto& i : listeners->getMembers()) {
ComboAddress ca=listeners->getIPEndpoint(i);
cerr<<ca.toStringWithPort()<<endl;
listenAddresses.insert(ca);
}
}
cerr<<endl;
}
// cout<<"Full config: "<<endl;
// cout<<kc.d_main.display();
cerr<<"Need to listen on "<<listenAddresses.size()<<" addresses"<<endl;
vector<std::thread> listeners;
auto addr=kc.d_main.getIPEndpoint("kolmo-server");
if(addr.sin4.sin_family) // this should actually be some kind of 'isSet()' thing
listeners.emplace_back(KolmoThread, &kc, addr);
for(const auto& addr : listenAddresses) {
listeners.emplace_back(listenThread, &kc, addr);
}
for(auto& t: listeners)
t.join();
}
<commit_msg>move to json<commit_after>#define CROW_ENABLE_SSL
#include <crow.h>
#include "kolmoconf.hh"
#include "comboaddress.hh"
#include <set>
#include <boost/utility/string_ref.hpp>
#include <sstream>
#include "http.hh"
/*
Welcome to the default free zone!
No single number or default can live here EVERYTHING comes from the configuration file.
The webserver serves URL of SITES which have NAMES and ALTERNATE NAMES.
URLs map to DIRECTORIES or ACTIONS (Redirects of various types)
A SITE listens on one or more IP address LISTENERS
LISTENERS can have settings too
Settings:
GLOBAL
Syslog on/off
LISTENER
Address
Port
Listen-limit
Free-bind / non-local
SITE
Domain Name
Alternate name
Make-canonical
Mapping / ->
DIRECTORY
Path /var/www/
Directory-listing: no
Mapping /new/ ->
ACTION
Target https://new.site/
Code 302
Password /data/ -> Passwords: default
PASSWORDS
Name: default
Entries: [{User: user, Password: password}]
*/
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::set;
using std::vector;
using std::string;
static int readFile(const boost::string_ref& path, std::string& content)
{
FILE* ffp=fopen(&path[0], "r");
if(!ffp) {
return -1;
}
std::shared_ptr<FILE> fp(ffp, fclose);
content.clear();
char buffer[4096];
size_t nbytes;
while((nbytes=fread(buffer,1,sizeof(buffer), fp.get()))!=0) {
content.append(buffer, nbytes);
}
return content.size();
}
string getPath(KolmoConf* kc, const crow::request& req, const std::string& rest, KolmoStruct** siteptr)
{
cout<<req.url<<endl;
auto f=req.headers.find("host");
if(f != req.headers.end()) {
string host=f->second;
auto pos = host.find(':');
if(pos != string::npos)
host.resize(pos);
cout<<"Host: "<<host<<endl;
auto sites = kc->d_main.getStruct("sites"); // XXX SHOULd BE TYPESAFE
for(const auto& m : sites->getMembers()) {
auto site = sites->getStruct(m);
if(site->getString("name")==host && site->getBool("enabled")) {
cout<<"Got it, should serve up to "<<site->getString("path")+"/"+rest<<endl;
*siteptr=site;
return site->getString("path")+"/"+rest;
}
}
}
return "";
}
void listenThread(KolmoConf* kc, ComboAddress ca)
try
{
crow::SimpleApp app;
bool tls{false};
auto func=[ca,kc,&tls](const crow::request& req, crow::response& resp, const std::string& a){
cerr<<"Request for "<<req.url<<" came in on "<<ca.toStringWithPort()<<", tls="<<tls<<endl;
KolmoStruct *site=0;
auto path=getPath(kc, req, a, &site);
if(!tls && site && site->getBool("redirect-to-https")) {
resp.code=301;
resp.set_header("Location", "https://"+site->getString("name")+req.url);
resp.body=R"(<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>ws</center>
</body>
</html>)";
resp.end();
return;
}
if(path.empty() || path.find("..") != string::npos) {
cerr<<"Can't find path for "<<req.url<<endl;
resp.code=404;
resp.body="Can't find URL";
resp.end();
return;
}
string content;
if(readFile(path, resp.body) < 0) {
resp.code=404;
resp.body="Can't find URL";
resp.end();
}
resp.set_header("Content-Type", pickContentType(path));
resp.end();
};
CROW_ROUTE(app, "/<path>")(func);
CROW_ROUTE(app, "/")([&func](const crow::request& rec, crow::response& resp) { return func(rec, resp, "/index.html");});
auto listeners=kc->d_main.getStruct("listeners");
for(const auto& m : listeners->getMembers()) {
ComboAddress pot(m);
if(pot==ca) {
cerr<<"Found a listener that applies!"<<endl;
auto listener=listeners->getStruct(m);
auto pemfile=listener->getString("pem-file");
auto certfile=listener->getString("cert-file");
auto keyfile=listener->getString("key-file");
if(!pemfile.empty()) {
cerr<<"Doing TLS on "<<ca.toStringWithPort()<<", pem-file: "<<pemfile<<endl;
tls=true;
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).ssl_file(pemfile).multithreaded().run();
cerr<<"Ended?"<<endl;
return;
}
else if(!certfile.empty()) {
tls=true;
cerr<<"Doing certfile TLS on "<<ca.toStringWithPort()<<", pem-file: "<<pemfile<<endl;
crow::ssl_context_t ctx{boost::asio::ssl::context::sslv23};
ctx.use_certificate_chain_file(certfile);
ctx.use_private_key_file(keyfile, crow::ssl_context_t::pem);
ctx.set_options(
boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::no_sslv3
);
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).ssl(std::move(ctx)).multithreaded().run();
cerr<<"Ended?"<<endl;
return;
}
}
}
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).multithreaded().run();
}
catch(std::exception& e)
{
cerr<<"Error from webserver for "<<ca.toString()<<": "<<e.what()<<endl;
}
std::atomic<bool> g_verbose;
void emitJSON(crow::response& resp, nlohmann::json& wv)
{
std::ostringstream str;
str << std::setw(4) << wv << endl;
resp.write(str.str());
resp.set_header("Content-Type","application/json");
resp.end();
}
void KolmoThread(KolmoConf* kc, ComboAddress ca)
{
crow::SimpleApp app;
CROW_ROUTE(app, "/full-config")([kc](const crow::request& rec, crow::response& resp) {
nlohmann::json wv;
KSToJson(&kc->d_main, wv);
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/minimal-config")([kc](const crow::request& rec, crow::response& resp) {
auto minimal=kc->getMinimalConfig();
nlohmann::json wv;
KSToJson(minimal.get(), wv);
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/delta-config")([kc](const crow::request& rec, crow::response& resp) {
auto minimal=kc->getRuntimeDiff();
nlohmann::json wv={};
KSToJson(minimal.get(), wv);
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/runtime/set-value")([kc](const crow::request& rec, crow::response& resp) {
cerr<<rec.url_params.get("variable")<<endl;
auto variable=rec.url_params.get("variable"), value=rec.url_params.get("value");
nlohmann::json wv;
try {
cerr<<"Setting '"<<variable<<"' to '"<<value<<"'"<<endl;
kc->d_main.setValueAt(variable, value);
wv["result"]="ok";
}catch(std::exception& e) {
wv["result"]="failure";
wv["reason"]=e.what();
}
emitJSON(resp, wv);
});
CROW_ROUTE(app, "/ls<path>")([kc](const crow::request& rec, crow::response& resp, const std::string& path=std::string()) {
cerr<<path<<endl;
string rpath=path.substr(1);
KolmoStruct* ks=&kc->d_main;
if(!rpath.empty()) {
cerr<<"Traversing path"<<endl;
auto ptr=ks->getValueAt(rpath);
ks=dynamic_cast<KolmoStruct*>(ptr);
if(!ks) {
nlohmann::json item;
item["description"] = ptr->description;
item["runtime"] = ptr->runtime;
item["unit"] = ptr->unit;
item["mandatory"] = ptr->mandatory;
item["value"]=ptr->getValue();
item["default"]=ptr->defaultValue;
emitJSON(resp, item);
return;
}
}
nlohmann::json wv=nlohmann::json::object();
for(const auto& a : ks->getAll()) {
nlohmann::json item;
item["description"] = a.second->description;
item["runtime"] = a.second->runtime;
item["unit"] = a.second->unit;
item["mandatory"] = a.second->mandatory;
item["value"]=a.second->getValue();
item["default"]=a.second->defaultValue;
wv[a.first]=item;
}
emitJSON(resp, wv);
});
app.port(ntohs(ca.sin4.sin_port)).bindaddr(ca.toString()).multithreaded().run();
}
int main(int argc, char** argv)
{
// crow::logger::setLogLevel(crow::LogLevel::Debug);
KolmoConf kc;
kc.initSchemaFromFile("ws-schema.lua");
//kc.initConfigFromLua("ws.conf");
kc.initConfigFromJSON("ws.json");
kc.declareRuntime();
kc.initConfigFromCmdline(argc, argv);
kc.d_main.tieBool("verbose", &g_verbose);
if(g_verbose) {
cerr<<"Must be verbose"<<endl;
cerr<<"Server name is "<<kc.d_main.getString("server-name")<<endl;
}
else {
cerr<<"Verbose is false"<<endl;
}
set<ComboAddress> listenAddresses;
auto sites = kc.d_main.getStruct("sites"); // XXX SHOULd BE TYPESAFE
for(const auto& m : sites->getMembers()) {
auto site = sites->getStruct(m);
cerr<<"["<<m<<"] We run a website called "<<site->getString("name")<<endl;
if(!site->getBool("enabled")) {
cerr<<"However, site is not enabled, skipping"<<endl;
}
else {
cerr<<"The site enable status: "<<site->getBool("enabled")<<endl;
cerr<<"We serve from path: "<<site->getString("path")<<endl;
cerr<<"We serve on addresses: ";
auto listeners = site->getStruct("listen");
for(const auto& i : listeners->getMembers()) {
ComboAddress ca=listeners->getIPEndpoint(i);
cerr<<ca.toStringWithPort()<<endl;
listenAddresses.insert(ca);
}
}
cerr<<endl;
}
// cout<<"Full config: "<<endl;
// cout<<kc.d_main.display();
cerr<<"Need to listen on "<<listenAddresses.size()<<" addresses"<<endl;
vector<std::thread> listeners;
auto addr=kc.d_main.getIPEndpoint("kolmo-server");
if(addr.sin4.sin_family) // this should actually be some kind of 'isSet()' thing
listeners.emplace_back(KolmoThread, &kc, addr);
for(const auto& addr : listenAddresses) {
listeners.emplace_back(listenThread, &kc, addr);
}
for(auto& t: listeners)
t.join();
}
<|endoftext|> |
<commit_before>#include <halley/core/input/input_keyboard.h>
#include "input/input_keys.h"
#include "input/text_input_capture.h"
#include "input/text_input_data.h"
using namespace Halley;
KeyboardKeyPress::KeyboardKeyPress(KeyCode key, KeyMods mod)
: key(key)
, mod(mod)
{
}
bool KeyboardKeyPress::operator==(const KeyboardKeyPress& other) const
{
return key == other.key && mod == other.mod;
}
bool KeyboardKeyPress::is(KeyCode key, KeyMods mod) const
{
return this->key == key && this->mod == mod;
}
bool KeyboardKeyPress::isPrintable() const
{
return static_cast<int>(key) >= 32 && static_cast<int>(key) < 128 && (mod == KeyMods::None || mod == KeyMods::Shift);
}
InputKeyboard::InputKeyboard(int nButtons, std::shared_ptr<IClipboard> clipboard)
: InputButtonBase(nButtons)
, clipboard(std::move(clipboard))
{
}
TextInputCapture InputKeyboard::captureText(TextInputData& textInputData, SoftwareKeyboardData data)
{
return TextInputCapture(textInputData, std::move(data), makeTextInputCapture());
}
void InputKeyboard::onKeyPressed(KeyCode code, KeyMods mods)
{
const auto key = KeyboardKeyPress(code, mods);
if (!sendKeyPress(key)) {
keyPresses.push_back(key);
}
onButtonPressed(static_cast<int>(code));
}
void InputKeyboard::onKeyReleased(KeyCode code, KeyMods mods)
{
onButtonReleased(static_cast<int>(code));
}
gsl::span<const KeyboardKeyPress> InputKeyboard::getPendingKeys() const
{
return { keyPresses };
}
void InputKeyboard::onTextEntered(const char* text)
{
const auto str = String(text).getUTF32();
for (const auto& c: captures) {
c->onTextEntered(str);
}
}
bool InputKeyboard::sendKeyPress(KeyboardKeyPress chr)
{
for (const auto& c: captures) {
const bool handled = c->onKeyPress(chr, clipboard.get());
if (handled) {
return true;
}
}
return false;
}
void InputKeyboard::onButtonsCleared()
{
keyPresses.clear();
}
std::unique_ptr<ITextInputCapture> InputKeyboard::makeTextInputCapture()
{
auto ptr = std::make_unique<StandardTextInputCapture>(*this);
captures.insert(ptr.get());
return ptr;
}
void InputKeyboard::removeCapture(ITextInputCapture* capture)
{
captures.erase(capture);
}
<commit_msg>Workaround for SDL bug reporting Ctrl+Space as a text event<commit_after>#include <halley/core/input/input_keyboard.h>
#include "input/input_keys.h"
#include "input/text_input_capture.h"
#include "input/text_input_data.h"
using namespace Halley;
KeyboardKeyPress::KeyboardKeyPress(KeyCode key, KeyMods mod)
: key(key)
, mod(mod)
{
}
bool KeyboardKeyPress::operator==(const KeyboardKeyPress& other) const
{
return key == other.key && mod == other.mod;
}
bool KeyboardKeyPress::is(KeyCode key, KeyMods mod) const
{
return this->key == key && this->mod == mod;
}
bool KeyboardKeyPress::isPrintable() const
{
return static_cast<int>(key) >= 32 && static_cast<int>(key) < 128 && (mod == KeyMods::None || mod == KeyMods::Shift);
}
InputKeyboard::InputKeyboard(int nButtons, std::shared_ptr<IClipboard> clipboard)
: InputButtonBase(nButtons)
, clipboard(std::move(clipboard))
{
}
TextInputCapture InputKeyboard::captureText(TextInputData& textInputData, SoftwareKeyboardData data)
{
return TextInputCapture(textInputData, std::move(data), makeTextInputCapture());
}
void InputKeyboard::onKeyPressed(KeyCode code, KeyMods mods)
{
const auto key = KeyboardKeyPress(code, mods);
if (!sendKeyPress(key)) {
keyPresses.push_back(key);
}
onButtonPressed(static_cast<int>(code));
}
void InputKeyboard::onKeyReleased(KeyCode code, KeyMods mods)
{
onButtonReleased(static_cast<int>(code));
}
gsl::span<const KeyboardKeyPress> InputKeyboard::getPendingKeys() const
{
return { keyPresses };
}
void InputKeyboard::onTextEntered(const char* text)
{
const auto str = String(text).getUTF32();
if (str.size() == 1 && str[0] == ' ' && (isButtonDown(KeyCode::LCtrl) || isButtonDown(KeyCode::RCtrl))) {
// Workaround SDL bug
return;
}
for (const auto& c: captures) {
c->onTextEntered(str);
}
}
bool InputKeyboard::sendKeyPress(KeyboardKeyPress chr)
{
for (const auto& c: captures) {
const bool handled = c->onKeyPress(chr, clipboard.get());
if (handled) {
return true;
}
}
return false;
}
void InputKeyboard::onButtonsCleared()
{
keyPresses.clear();
}
std::unique_ptr<ITextInputCapture> InputKeyboard::makeTextInputCapture()
{
auto ptr = std::make_unique<StandardTextInputCapture>(*this);
captures.insert(ptr.get());
return ptr;
}
void InputKeyboard::removeCapture(ITextInputCapture* capture)
{
captures.erase(capture);
}
<|endoftext|> |
<commit_before>//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass hoists instructions to enable speculative execution on
// targets where branches are expensive. This is aimed at GPUs. It
// currently works on simple if-then and if-then-else
// patterns.
//
// Removing branches is not the only motivation for this
// pass. E.g. consider this code and assume that there is no
// addressing mode for multiplying by sizeof(*a):
//
// if (b > 0)
// c = a[i + 1]
// if (d > 0)
// e = a[i + 2]
//
// turns into
//
// p = &a[i + 1];
// if (b > 0)
// c = *p;
// q = &a[i + 2];
// if (d > 0)
// e = *q;
//
// which could later be optimized to
//
// r = &a[i];
// if (b > 0)
// c = r[1];
// if (d > 0)
// e = r[2];
//
// Later passes sink back much of the speculated code that did not enable
// further optimization.
//
// This pass is more aggressive than the function SpeculativeyExecuteBB in
// SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
// it will speculate at most one instruction. It also will not speculate if
// there is a value defined in the if-block that is only used in the then-block.
// These restrictions make sense since the speculation in SimplifyCFG seems
// aimed at introducing cheap selects, while this pass is intended to do more
// aggressive speculation while counting on later passes to either capitalize on
// that or clean it up.
//
// If the pass was created by calling
// createSpeculativeExecutionIfHasBranchDivergencePass or the
// -spec-exec-only-if-divergent-target option is present, this pass only has an
// effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
// on other targets, it is a nop.
//
// This lets you include this pass unconditionally in the IR pass pipeline, but
// only enable it for relevant targets.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallSet.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "speculative-execution"
// The risk that speculation will not pay off increases with the
// number of instructions speculated, so we put a limit on that.
static cl::opt<unsigned> SpecExecMaxSpeculationCost(
"spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where "
"the cost of the instructions to speculatively execute "
"exceeds this limit."));
// Speculating just a few instructions from a larger block tends not
// to be profitable and this limit prevents that. A reason for that is
// that small basic blocks are more likely to be candidates for
// further optimization.
static cl::opt<unsigned> SpecExecMaxNotHoisted(
"spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where the "
"number of instructions that would not be speculatively executed "
"exceeds this limit."));
static cl::opt<bool> SpecExecOnlyIfDivergentTarget(
"spec-exec-only-if-divergent-target", cl::init(0), cl::Hidden,
cl::desc("Speculative execution is applied only to targets with divergent "
"branches, even if the pass was configured to apply only to all "
"targets."));
namespace {
class SpeculativeExecution : public FunctionPass {
public:
static char ID;
explicit SpeculativeExecution(bool OnlyIfDivergentTarget = false)
: FunctionPass(ID),
OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
SpecExecOnlyIfDivergentTarget) {}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
const char *getPassName() const override {
if (OnlyIfDivergentTarget)
return "Speculatively execute instructions if target has divergent "
"branches";
return "Speculatively execute instructions";
}
private:
bool runOnBasicBlock(BasicBlock &B);
bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
// If true, this pass is a nop unless the target Targetitecture has branch
// divergence.
const bool OnlyIfDivergentTarget;
const TargetTransformInfo *TTI = nullptr;
};
} // namespace
char SpeculativeExecution::ID = 0;
INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetTransformInfoWrapperPass>();
}
bool SpeculativeExecution::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence()) {
DEBUG(dbgs() << "Not running SpeculativeExecution because "
"TTI->hasBranchDivergence() is false.\n");
return false;
}
bool Changed = false;
for (auto& B : F) {
Changed |= runOnBasicBlock(B);
}
return Changed;
}
bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
if (BI == nullptr)
return false;
if (BI->getNumSuccessors() != 2)
return false;
BasicBlock &Succ0 = *BI->getSuccessor(0);
BasicBlock &Succ1 = *BI->getSuccessor(1);
if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
return false;
}
// Hoist from if-then (triangle).
if (Succ0.getSinglePredecessor() != nullptr &&
Succ0.getSingleSuccessor() == &Succ1) {
return considerHoistingFromTo(Succ0, B);
}
// Hoist from if-else (triangle).
if (Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() == &Succ0) {
return considerHoistingFromTo(Succ1, B);
}
// Hoist from if-then-else (diamond), but only if it is equivalent to
// an if-else or if-then due to one of the branches doing nothing.
if (Succ0.getSinglePredecessor() != nullptr &&
Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() != nullptr &&
Succ1.getSingleSuccessor() != &B &&
Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
// If a block has only one instruction, then that is a terminator
// instruction so that the block does nothing. This does happen.
if (Succ1.size() == 1) // equivalent to if-then
return considerHoistingFromTo(Succ0, B);
if (Succ0.size() == 1) // equivalent to if-else
return considerHoistingFromTo(Succ1, B);
}
return false;
}
static unsigned ComputeSpeculationCost(const Instruction *I,
const TargetTransformInfo &TTI) {
switch (Operator::getOpcode(I)) {
case Instruction::GetElementPtr:
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Select:
case Instruction::Shl:
case Instruction::Sub:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Xor:
case Instruction::ZExt:
case Instruction::SExt:
return TTI.getUserCost(I);
default:
return UINT_MAX; // Disallow anything not whitelisted.
}
}
bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
BasicBlock &ToBlock) {
SmallSet<const Instruction *, 8> NotHoisted;
const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
for (Value* V : U->operand_values()) {
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (NotHoisted.count(I) > 0)
return false;
}
}
return true;
};
unsigned TotalSpeculationCost = 0;
for (auto& I : FromBlock) {
const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
AllPrecedingUsesFromBlockHoisted(&I)) {
TotalSpeculationCost += Cost;
if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
return false; // too much to hoist
} else {
NotHoisted.insert(&I);
if (NotHoisted.size() > SpecExecMaxNotHoisted)
return false; // too much left behind
}
}
if (TotalSpeculationCost == 0)
return false; // nothing to hoist
for (auto I = FromBlock.begin(); I != FromBlock.end();) {
// We have to increment I before moving Current as moving Current
// changes the list that I is iterating through.
auto Current = I;
++I;
if (!NotHoisted.count(&*Current)) {
Current->moveBefore(ToBlock.getTerminator());
}
}
return true;
}
namespace llvm {
FunctionPass *createSpeculativeExecutionPass() {
return new SpeculativeExecution();
}
FunctionPass *createSpeculativeExecutionIfHasBranchDivergencePass() {
return new SpeculativeExecution(/* OnlyIfDivergentTarget = */ true);
}
} // namespace llvm
<commit_msg>Use false rather than 0 for a boolean value. NFC.<commit_after>//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass hoists instructions to enable speculative execution on
// targets where branches are expensive. This is aimed at GPUs. It
// currently works on simple if-then and if-then-else
// patterns.
//
// Removing branches is not the only motivation for this
// pass. E.g. consider this code and assume that there is no
// addressing mode for multiplying by sizeof(*a):
//
// if (b > 0)
// c = a[i + 1]
// if (d > 0)
// e = a[i + 2]
//
// turns into
//
// p = &a[i + 1];
// if (b > 0)
// c = *p;
// q = &a[i + 2];
// if (d > 0)
// e = *q;
//
// which could later be optimized to
//
// r = &a[i];
// if (b > 0)
// c = r[1];
// if (d > 0)
// e = r[2];
//
// Later passes sink back much of the speculated code that did not enable
// further optimization.
//
// This pass is more aggressive than the function SpeculativeyExecuteBB in
// SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
// it will speculate at most one instruction. It also will not speculate if
// there is a value defined in the if-block that is only used in the then-block.
// These restrictions make sense since the speculation in SimplifyCFG seems
// aimed at introducing cheap selects, while this pass is intended to do more
// aggressive speculation while counting on later passes to either capitalize on
// that or clean it up.
//
// If the pass was created by calling
// createSpeculativeExecutionIfHasBranchDivergencePass or the
// -spec-exec-only-if-divergent-target option is present, this pass only has an
// effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
// on other targets, it is a nop.
//
// This lets you include this pass unconditionally in the IR pass pipeline, but
// only enable it for relevant targets.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallSet.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "speculative-execution"
// The risk that speculation will not pay off increases with the
// number of instructions speculated, so we put a limit on that.
static cl::opt<unsigned> SpecExecMaxSpeculationCost(
"spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where "
"the cost of the instructions to speculatively execute "
"exceeds this limit."));
// Speculating just a few instructions from a larger block tends not
// to be profitable and this limit prevents that. A reason for that is
// that small basic blocks are more likely to be candidates for
// further optimization.
static cl::opt<unsigned> SpecExecMaxNotHoisted(
"spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where the "
"number of instructions that would not be speculatively executed "
"exceeds this limit."));
static cl::opt<bool> SpecExecOnlyIfDivergentTarget(
"spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden,
cl::desc("Speculative execution is applied only to targets with divergent "
"branches, even if the pass was configured to apply only to all "
"targets."));
namespace {
class SpeculativeExecution : public FunctionPass {
public:
static char ID;
explicit SpeculativeExecution(bool OnlyIfDivergentTarget = false)
: FunctionPass(ID),
OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
SpecExecOnlyIfDivergentTarget) {}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
const char *getPassName() const override {
if (OnlyIfDivergentTarget)
return "Speculatively execute instructions if target has divergent "
"branches";
return "Speculatively execute instructions";
}
private:
bool runOnBasicBlock(BasicBlock &B);
bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
// If true, this pass is a nop unless the target Targetitecture has branch
// divergence.
const bool OnlyIfDivergentTarget;
const TargetTransformInfo *TTI = nullptr;
};
} // namespace
char SpeculativeExecution::ID = 0;
INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetTransformInfoWrapperPass>();
}
bool SpeculativeExecution::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence()) {
DEBUG(dbgs() << "Not running SpeculativeExecution because "
"TTI->hasBranchDivergence() is false.\n");
return false;
}
bool Changed = false;
for (auto& B : F) {
Changed |= runOnBasicBlock(B);
}
return Changed;
}
bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
if (BI == nullptr)
return false;
if (BI->getNumSuccessors() != 2)
return false;
BasicBlock &Succ0 = *BI->getSuccessor(0);
BasicBlock &Succ1 = *BI->getSuccessor(1);
if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
return false;
}
// Hoist from if-then (triangle).
if (Succ0.getSinglePredecessor() != nullptr &&
Succ0.getSingleSuccessor() == &Succ1) {
return considerHoistingFromTo(Succ0, B);
}
// Hoist from if-else (triangle).
if (Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() == &Succ0) {
return considerHoistingFromTo(Succ1, B);
}
// Hoist from if-then-else (diamond), but only if it is equivalent to
// an if-else or if-then due to one of the branches doing nothing.
if (Succ0.getSinglePredecessor() != nullptr &&
Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() != nullptr &&
Succ1.getSingleSuccessor() != &B &&
Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
// If a block has only one instruction, then that is a terminator
// instruction so that the block does nothing. This does happen.
if (Succ1.size() == 1) // equivalent to if-then
return considerHoistingFromTo(Succ0, B);
if (Succ0.size() == 1) // equivalent to if-else
return considerHoistingFromTo(Succ1, B);
}
return false;
}
static unsigned ComputeSpeculationCost(const Instruction *I,
const TargetTransformInfo &TTI) {
switch (Operator::getOpcode(I)) {
case Instruction::GetElementPtr:
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Select:
case Instruction::Shl:
case Instruction::Sub:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Xor:
case Instruction::ZExt:
case Instruction::SExt:
return TTI.getUserCost(I);
default:
return UINT_MAX; // Disallow anything not whitelisted.
}
}
bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
BasicBlock &ToBlock) {
SmallSet<const Instruction *, 8> NotHoisted;
const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
for (Value* V : U->operand_values()) {
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (NotHoisted.count(I) > 0)
return false;
}
}
return true;
};
unsigned TotalSpeculationCost = 0;
for (auto& I : FromBlock) {
const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
AllPrecedingUsesFromBlockHoisted(&I)) {
TotalSpeculationCost += Cost;
if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
return false; // too much to hoist
} else {
NotHoisted.insert(&I);
if (NotHoisted.size() > SpecExecMaxNotHoisted)
return false; // too much left behind
}
}
if (TotalSpeculationCost == 0)
return false; // nothing to hoist
for (auto I = FromBlock.begin(); I != FromBlock.end();) {
// We have to increment I before moving Current as moving Current
// changes the list that I is iterating through.
auto Current = I;
++I;
if (!NotHoisted.count(&*Current)) {
Current->moveBefore(ToBlock.getTerminator());
}
}
return true;
}
namespace llvm {
FunctionPass *createSpeculativeExecutionPass() {
return new SpeculativeExecution();
}
FunctionPass *createSpeculativeExecutionIfHasBranchDivergencePass() {
return new SpeculativeExecution(/* OnlyIfDivergentTarget = */ true);
}
} // namespace llvm
<|endoftext|> |
<commit_before>#include "lexer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * copy_str (char * from)
{
int str_length;
char * to;
str_length = strlen(from);
to = (char *)malloc(str_length);
strcpy(to, from);
return to;
}
char * append_to_buffer(char * buffer, char chr)
{
int buffer_length;
buffer_length = 0;
if (buffer == NULL)
buffer = (char *)malloc(1);
else {
buffer_length = strlen(buffer);
buffer = (char *)realloc(buffer, buffer_length + 1);
}
buffer[buffer_length] = chr;
buffer[buffer_length + 1] = '\0';
return buffer;
}
struct Token * append(struct Token * tok_arr, int ntokens, int type, char quote,
char * val)
{
int new_size;
new_size = (ntokens + 1) * sizeof(token);
if (tok_arr == NULL && ntokens == 0)
tok_arr = (struct Token *)malloc(sizeof(token));
else if (tok_arr != NULL && ntokens > 0)
tok_arr = (struct Token *)realloc(tok_arr, new_size);
else {
fprintf(stderr, "Fatal Error: Illegal arguments passed to Token append()\n");
exit(1);
}
tok_arr[ntokens].type = type;
tok_arr[ntokens].quote = quote;
if (val != NULL)
tok_arr[ntokens].value = copy_str(val);
else
tok_arr[ntokens].value = val;
return tok_arr;
}
void print_token_array(struct Token * token_array, int size)
{
int i;
printf("Tokens in array: %d\n", size);
for(i = 0; i < size; ++i) {
printf("--------------------------------\n");
printf("Token: %d\n", i);
printf("Type: %d\n", token_array[i].type);
printf("Quote: %d\n", token_array[i].quote);
printf("Value: %s\n", token_array[i].value);
printf("---------------------------------\n\n");
}
}
void free_token_array(struct Token * token_array, int size)
{
int i;
for(i = 0; i < size; ++i)
free(token_array[i].value);
free(token_array);
token_array = NULL;
}
<commit_msg>Prefer explicit NULL assignment<commit_after>#include "lexer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * copy_str (char * from)
{
int str_length;
char * to;
str_length = strlen(from);
to = (char *)malloc(str_length);
strcpy(to, from);
return to;
}
char * append_to_buffer(char * buffer, char chr)
{
int buffer_length;
buffer_length = 0;
if (buffer == NULL)
buffer = (char *)malloc(1);
else {
buffer_length = strlen(buffer);
buffer = (char *)realloc(buffer, buffer_length + 1);
}
buffer[buffer_length] = chr;
buffer[buffer_length + 1] = '\0';
return buffer;
}
struct Token * append(struct Token * tok_arr, int ntokens, int type, char quote,
char * val)
{
int new_size;
new_size = (ntokens + 1) * sizeof(token);
if (tok_arr == NULL && ntokens == 0)
tok_arr = (struct Token *)malloc(sizeof(token));
else if (tok_arr != NULL && ntokens > 0)
tok_arr = (struct Token *)realloc(tok_arr, new_size);
else {
fprintf(stderr, "Fatal Error: Illegal arguments passed to Token append()\n");
exit(1);
}
tok_arr[ntokens].type = type;
tok_arr[ntokens].quote = quote;
if (val != NULL)
tok_arr[ntokens].value = copy_str(val);
else
tok_arr[ntokens].value = NULL;
return tok_arr;
}
void print_token_array(struct Token * token_array, int size)
{
int i;
printf("Tokens in array: %d\n", size);
for(i = 0; i < size; ++i) {
printf("--------------------------------\n");
printf("Token: %d\n", i);
printf("Type: %d\n", token_array[i].type);
printf("Quote: %d\n", token_array[i].quote);
printf("Value: %s\n", token_array[i].value);
printf("---------------------------------\n\n");
}
}
void free_token_array(struct Token * token_array, int size)
{
int i;
for(i = 0; i < size; ++i)
free(token_array[i].value);
free(token_array);
token_array = NULL;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include "appupappsmodel.h"
#include <QHash>
#include <QDir>
#include <QDebug>
#include <QStringList>
#include <QFileSystemWatcher>
#include <QtDeclarative/qdeclarative.h>
#include <mdesktopentry.h>
AppUpAppsModel::AppUpAppsModel(AppUpType type, QObject *parent) :
QAbstractListModel(parent),
mLimit(6),
mType(type)
{
QHash<int, QByteArray> roles;
roles.insert(AppUpAppsModel::Type, "type");
roles.insert(AppUpAppsModel::Title, "title");
roles.insert(AppUpAppsModel::Comment, "comment");
roles.insert(AppUpAppsModel::Icon, "icon");
roles.insert(AppUpAppsModel::Exec, "exec");
roles.insert(AppUpAppsModel::Filename, "filename");
setRoleNames(roles);
mWatcher = new QFileSystemWatcher(this);
qDebug() << "Type: " << type << "Adding path: " << APPUP_DESKTOP_PATH.arg(APPUP_DIRECTORIES.at(mType));
mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType)));
connect(mWatcher,
SIGNAL(directoryChanged(QString)),
this,
SLOT(loadDesktops()));
loadDesktops();
}
AppUpAppsModel::~AppUpAppsModel()
{
}
int AppUpAppsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
if (mLimit == 0)
return mDesktops.count();
else
return std::min(mDesktops.count(), mLimit);
}
QVariant AppUpAppsModel::data(const QModelIndex &index, int role) const
{
int row;
if (!index.isValid() || index.row() >= mDesktops.count())
return QVariant();
row = index.row();
switch (role) {
case AppUpAppsModel::Type:
return mDesktops[row]->type();
break;
case AppUpAppsModel::Title:
return mDesktops[row]->name();
break;
case AppUpAppsModel::Comment:
return mDesktops[row]->comment();
break;
case AppUpAppsModel::Exec:
return mDesktops[row]->exec();
break;
case AppUpAppsModel::Icon:
return mDesktops[row]->icon();
break;
case AppUpAppsModel::Filename:
return mDesktops[row]->fileName();
break;
default:
qDebug("Unhandled data role requested in AppUpAppsModel::data(): %i", role);
return QVariant();
break;
}
}
//Private slots:
void AppUpAppsModel::loadDesktops()
{
// qDebug("**** Beginning loadDesktops");
if (mDesktops.count()) {
this->beginRemoveRows(QModelIndex(), 0, mDesktops.count()-1);
mDesktops.clear();
this->endRemoveRows();
}
qDebug() << mWatcher->directories();
if (mWatcher->directories().count() < 1) {
qDebug("No directories loaded into mWatcher!");
return;
}
QString curDir = mWatcher->directories().at(0);
QDir dir(curDir);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
QStringList filters;
filters << "*.desktop";
foreach (QFileInfo fileInfo, dir.entryInfoList(filters))
{
// qDebug("Inside foreach loop");
MDesktopEntry *newDesktop = new MDesktopEntry(fileInfo.absoluteFilePath());
// qDebug("After MDesktopEntry creation");
if (newDesktop->isValid()) {
// qDebug("MDesktopEntry valid!");
this->beginInsertRows(QModelIndex(), mDesktops.count(), mDesktops.count());
mDesktops.append(new MDesktopEntry(fileInfo.absoluteFilePath()));
this->endInsertRows();
// qDebug("After endInsertRows");
}
}
// qDebug("End of loadDesktops");
}
//Private functions
void AppUpAppsModel::setType(AppUpType type)
{
mType = type;
emit this->typeChanged();
mWatcher->removePath(mWatcher->directories()[0]);
mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType)));
loadDesktops();
}
QML_DECLARE_TYPE(AppUpAppsModel);
<commit_msg>Fix BMC#18642 - Mytablet panel failed to auto detect the app-up's update<commit_after>/*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include "appupappsmodel.h"
#include <QHash>
#include <QDir>
#include <QDebug>
#include <QStringList>
#include <QFileSystemWatcher>
#include <QtDeclarative/qdeclarative.h>
#include <mdesktopentry.h>
AppUpAppsModel::AppUpAppsModel(AppUpType type, QObject *parent) :
QAbstractListModel(parent),
mLimit(6),
mType(type)
{
QHash<int, QByteArray> roles;
roles.insert(AppUpAppsModel::Type, "type");
roles.insert(AppUpAppsModel::Title, "title");
roles.insert(AppUpAppsModel::Comment, "comment");
roles.insert(AppUpAppsModel::Icon, "icon");
roles.insert(AppUpAppsModel::Exec, "exec");
roles.insert(AppUpAppsModel::Filename, "filename");
setRoleNames(roles);
mWatcher = new QFileSystemWatcher(this);
qDebug() << "Type: " << type << "Adding path: " << APPUP_DESKTOP_PATH.arg(APPUP_DIRECTORIES.at(mType));
mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType)));
connect(mWatcher,
SIGNAL(directoryChanged(QString)),
this,
SLOT(loadDesktops()));
loadDesktops();
}
AppUpAppsModel::~AppUpAppsModel()
{
}
int AppUpAppsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
if (mLimit == 0)
return mDesktops.count();
else
return std::min(mDesktops.count(), mLimit);
}
QVariant AppUpAppsModel::data(const QModelIndex &index, int role) const
{
int row;
if (!index.isValid() || index.row() >= mDesktops.count())
return QVariant();
row = index.row();
switch (role) {
case AppUpAppsModel::Type:
return mDesktops[row]->type();
break;
case AppUpAppsModel::Title:
return mDesktops[row]->name();
break;
case AppUpAppsModel::Comment:
return mDesktops[row]->comment();
break;
case AppUpAppsModel::Exec:
return mDesktops[row]->exec();
break;
case AppUpAppsModel::Icon:
return mDesktops[row]->icon();
break;
case AppUpAppsModel::Filename:
return mDesktops[row]->fileName();
break;
default:
qDebug("Unhandled data role requested in AppUpAppsModel::data(): %i", role);
return QVariant();
break;
}
}
//Private slots:
void AppUpAppsModel::loadDesktops()
{
// qDebug("**** Beginning loadDesktops");
if (mDesktops.count()) {
this->beginRemoveRows(QModelIndex(), 0, mDesktops.count()-1);
mDesktops.clear();
this->endRemoveRows();
}
qDebug() << mWatcher->directories();
if (mWatcher->directories().count() < 1) {
qDebug("No directories loaded into mWatcher!");
return;
}
QString curDir = mWatcher->directories().at(0);
QDir dir(curDir);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
QStringList filters;
filters << "*.desktop";
foreach (QFileInfo fileInfo, dir.entryInfoList(filters))
{
qDebug() << fileInfo.absoluteFilePath();
MDesktopEntry *newDesktop = new MDesktopEntry(fileInfo.absoluteFilePath());
if (newDesktop->isValid()) {
this->beginInsertRows(QModelIndex(), mDesktops.count(), mDesktops.count());
mDesktops.append(new MDesktopEntry(fileInfo.absoluteFilePath()));
this->endInsertRows();
} else {
qDebug() << "Invalid desktop: " << fileInfo.absoluteFilePath();
}
}
emit countChanged();
}
//Private functions
void AppUpAppsModel::setType(AppUpType type)
{
mType = type;
emit this->typeChanged();
mWatcher->removePath(mWatcher->directories()[0]);
mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType)));
loadDesktops();
}
QML_DECLARE_TYPE(AppUpAppsModel);
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_DDS_INTERNAL_GATEWAY_DDS_TO_IOX_INL
#define IOX_DDS_INTERNAL_GATEWAY_DDS_TO_IOX_INL
#include "iceoryx_dds/internal/log/logging.hpp"
#include "iceoryx_posh/capro/service_description.hpp"
#include "iceoryx_utils/cxx/string.hpp"
#include "iceoryx_dds/gateway/dds_to_iox.hpp"
namespace iox
{
namespace dds
{
template <typename channel_t, typename gateway_t>
inline DDS2IceoryxGateway<channel_t, gateway_t>::DDS2IceoryxGateway() noexcept
: gateway_t()
{
}
template <typename channel_t, typename gateway_t>
inline void DDS2IceoryxGateway<channel_t, gateway_t>::loadConfiguration(const GatewayConfig& config) noexcept
{
iox::LogDebug() << "[DDS2IceoryxGateway] Configuring gateway.";
for (const auto& service : config.m_configuredServices)
{
if (!this->findChannel(service.m_serviceDescription).has_value())
{
setupChannel(service.m_serviceDescription);
}
}
}
template <typename channel_t, typename gateway_t>
inline void
DDS2IceoryxGateway<channel_t, gateway_t>::discover([[gnu::unused]] const iox::capro::CaproMessage& msg) noexcept
{
/// @note not implemented - requires dds discovery which is currently not implemented in the used dds stack.
}
template <typename channel_t, typename gateway_t>
inline void DDS2IceoryxGateway<channel_t, gateway_t>::forward(const channel_t& channel) noexcept
{
auto publisher = channel.getIceoryxTerminal();
auto reader = channel.getDDSTerminal();
auto peekResult = reader->peekNextSize();
if (peekResult.has_value())
{
// reserve a chunk for the sample
auto size = peekResult.value();
m_reservedChunk = publisher->allocateChunk(static_cast<uint32_t>(size));
// read sample into reserved chunk
auto buffer = static_cast<uint8_t*>(m_reservedChunk);
auto takeResult = reader->takeNext(buffer, size);
if (takeResult.has_error())
{
LogWarn() << "[DDS2IceoryxGateway] Encountered error reading from DDS network: "
<< iox::dds::DataReaderErrorString[static_cast<uint8_t>(takeResult.get_error())];
}
else
{
// publish the sample
publisher->sendChunk(buffer);
}
}
}
// ======================================== Private ======================================== //
template <typename channel_t, typename gateway_t>
iox::cxx::expected<channel_t, iox::dds::GatewayError>
DDS2IceoryxGateway<channel_t, gateway_t>::setupChannel(const iox::capro::ServiceDescription& service) noexcept
{
return this->addChannel(service).on_success(
[&service](iox::cxx::expected<channel_t, iox::dds::GatewayError> result) {
auto channel = result.get_value();
auto publisher = channel.getIceoryxTerminal();
auto reader = channel.getDDSTerminal();
publisher->offer();
reader->connect();
iox::LogDebug() << "[DDS2IceoryxGateway] Setup channel for service: {" << service.getServiceIDString()
<< ", " << service.getInstanceIDString() << ", " << service.getEventIDString() << "}";
});
}
} // namespace dds
} // namespace iox
#endif
<commit_msg>iox-#65 Remove header includion from inl file.<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_DDS_INTERNAL_GATEWAY_DDS_TO_IOX_INL
#define IOX_DDS_INTERNAL_GATEWAY_DDS_TO_IOX_INL
#include "iceoryx_dds/internal/log/logging.hpp"
#include "iceoryx_posh/capro/service_description.hpp"
#include "iceoryx_utils/cxx/string.hpp"
namespace iox
{
namespace dds
{
template <typename channel_t, typename gateway_t>
inline DDS2IceoryxGateway<channel_t, gateway_t>::DDS2IceoryxGateway() noexcept
: gateway_t()
{
}
template <typename channel_t, typename gateway_t>
inline void DDS2IceoryxGateway<channel_t, gateway_t>::loadConfiguration(const GatewayConfig& config) noexcept
{
iox::LogDebug() << "[DDS2IceoryxGateway] Configuring gateway.";
for (const auto& service : config.m_configuredServices)
{
if (!this->findChannel(service.m_serviceDescription).has_value())
{
setupChannel(service.m_serviceDescription);
}
}
}
template <typename channel_t, typename gateway_t>
inline void
DDS2IceoryxGateway<channel_t, gateway_t>::discover([[gnu::unused]] const iox::capro::CaproMessage& msg) noexcept
{
/// @note not implemented - requires dds discovery which is currently not implemented in the used dds stack.
}
template <typename channel_t, typename gateway_t>
inline void DDS2IceoryxGateway<channel_t, gateway_t>::forward(const channel_t& channel) noexcept
{
auto publisher = channel.getIceoryxTerminal();
auto reader = channel.getDDSTerminal();
auto peekResult = reader->peekNextSize();
if (peekResult.has_value())
{
// reserve a chunk for the sample
auto size = peekResult.value();
m_reservedChunk = publisher->allocateChunk(static_cast<uint32_t>(size));
// read sample into reserved chunk
auto buffer = static_cast<uint8_t*>(m_reservedChunk);
auto takeResult = reader->takeNext(buffer, size);
if (takeResult.has_error())
{
LogWarn() << "[DDS2IceoryxGateway] Encountered error reading from DDS network: "
<< iox::dds::DataReaderErrorString[static_cast<uint8_t>(takeResult.get_error())];
}
else
{
// publish the sample
publisher->sendChunk(buffer);
}
}
}
// ======================================== Private ======================================== //
template <typename channel_t, typename gateway_t>
iox::cxx::expected<channel_t, iox::dds::GatewayError>
DDS2IceoryxGateway<channel_t, gateway_t>::setupChannel(const iox::capro::ServiceDescription& service) noexcept
{
return this->addChannel(service).on_success(
[&service](iox::cxx::expected<channel_t, iox::dds::GatewayError> result) {
auto channel = result.get_value();
auto publisher = channel.getIceoryxTerminal();
auto reader = channel.getDDSTerminal();
publisher->offer();
reader->connect();
iox::LogDebug() << "[DDS2IceoryxGateway] Setup channel for service: {" << service.getServiceIDString()
<< ", " << service.getInstanceIDString() << ", " << service.getEventIDString() << "}";
});
}
} // namespace dds
} // namespace iox
#endif
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <cstring>
#include <fcntl.h>
#define sizeLim 10
using namespace std;
struct arguments
{
int argc;
char **argv;
};
arguments* readPrompt();
arguments* writePrompt();
void testArgs(arguments*);
void testSuite(arguments, string);
bool isValid(arguments*);
int redirectLeft(arguments*);
int redirectRight(arguments*);
bool run;
int main()
{
run = true;
while (run) {
arguments * temp = writePrompt();
//testArgs(temp);
int in = redirectRight(temp);
int out = redirectLeft(temp);
if(in>-1){
dup2(in, 0);
}
if(out>-1){
dup2(out,1);
}
if (isValid(temp)) {
int status;
long head = (long)*temp->argv;
long mHead = (long) temp->argv;
if (fork() != 0) {
//parent
*temp->argv =(char*) head;
waitpid(-1, &status, 0);
if(in>-1){
close(in);
}
if(out>-1){
close(out);
}
}
else {
//child
*temp->argv = (char*)head;
execvp(temp->argv[0], temp->argv);
cout<<"process failed, likley due to unknown command\n";
return 0;
}
}
}
return 0;
}
arguments* readPrompt() {
arguments* temp = new arguments;
string rawInput;
int aryLen =10;
getline(std::cin,rawInput);
temp->argc = 1;
char** ptr = new char*[aryLen];
temp->argv=ptr;
int start = 0;
int end=0;
for (int i=0; start < rawInput.length();start=(end+=1), ++i){//we set start to begining of next segment
if(i==aryLen){
aryLen+=10;
char** tempPtr= new char*[aryLen];
for(int j=0;j<i;++j){
tempPtr[j]=ptr[j];
}
ptr=tempPtr;
}
end = rawInput.find(' ', start);//get the end of the next segment
if(end==-1){
end=rawInput.length();//were finished fall out naturally
}
rawInput[end]='\0';//change whitespace to NULL
ptr[i]=&rawInput[start]; //set a new charpointer to our new segment
}
ptr[rawInput.length()+1] = NULL;
//testSuite(temp, rawInput); commented out for production
return temp;
}
bool isValid(arguments* args) {
char* comp = (*args->argv);
bool tf = true;
if (strcmp("cd", comp)==0){
chdir(&comp[3]);
tf = false;
}
else if(strcmp("pwd", comp)==0) {
char* WD = get_current_dir_name();
cout<<*WD<<endl;
delete WD;
tf = false;
}
else if(strcmp("quit", comp)==0){
run = false;
tf = false;
}
*args->argv=comp;
return tf;
}
arguments* writePrompt() {
cout << ">";
return readPrompt();
}
void testArgs(arguments* args) { //just tests using our args class
char * head = *args->argv;
char* ptr = (*args->argv);
cout << "there are " << (args->argc) << " arguments" << endl;
while(ptr!= NULL){
cout<<*ptr<<endl;
++ptr;
}
*args->argv = head;
}
void testSuite(arguments* args, string input) {
char* ptr = (*args->argv);
for (int i = 0; i < args->argc; ++i, ++ptr) {
if (!input.find(ptr, strlen(ptr)-1)) {
cout << "failed test at: " << i << endl;
}
}
}
int redirectLeft(arguments* args){
char* comp;
for(int i=0;i<args->argc;i++){
comp=args->argv[i];
if(strcmp("<", comp)==0){
return open(args->argv[i+1], O_RDONLY);
}
else if(strcmp("<<", comp)==0){
return open(args->argv[i+1], O_RDONLY);
}
}
return -1;
}
int redirectRight(arguments* args){
char* comp;
for(int i=0;i<args->argc;i++){
comp=args->argv[i];
if(strcmp(">", comp)==0){
return open(args->argv[i+1], O_WRONLY |O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
}
else if(strcmp(">>", comp)==0){
int temp;
return open(args->argv[i+1], O_WRONLY |O_APPEND | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
return temp;
}
}
return -1;
}
<commit_msg>forgot to set argc<commit_after>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <iostream>
#include <cstring>
#include <fcntl.h>
#define sizeLim 10
using namespace std;
struct arguments
{
int argc;
char **argv;
};
arguments* readPrompt();
arguments* writePrompt();
void testArgs(arguments*);
void testSuite(arguments, string);
bool isValid(arguments*);
int redirectLeft(arguments*);
int redirectRight(arguments*);
bool run;
int main()
{
run = true;
while (run) {
arguments * temp = writePrompt();
int in = redirectRight(temp);
int out = redirectLeft(temp);
if(in>-1){
dup2(in, 0);
}
if(out>-1){
dup2(out,1);
}
if (isValid(temp)) {
int status;
long head = (long)*temp->argv;
long mHead = (long) temp->argv;
if (fork() != 0) {
//parent
*temp->argv =(char*) head;
waitpid(-1, &status, 0);
if(in>-1){
close(in);
}
if(out>-1){
close(out);
}
}
else {
//child
*temp->argv = (char*)head;
execvp(temp->argv[0], temp->argv);
cout<<"process failed, likley due to unknown command\n";
return 0;
}
}
}
return 0;
}
arguments* readPrompt() {
arguments* temp = new arguments;
string rawInput;
int aryLen =10;
getline(std::cin,rawInput);
char** ptr = new char*[aryLen];
temp->argv=ptr;
int start = 0;
int end=0;
int i=0;
for (; start < rawInput.length();start=(end+=1), ++i){//we set start to begining of next segment
if(i==aryLen){
aryLen+=10;
char** tempPtr= new char*[aryLen];
for(int j=0;j<i;++j){
tempPtr[j]=ptr[j];
}
delete ptr;
ptr=tempPtr;
}
end = rawInput.find(' ', start);//get the end of the next segment
if(end==-1){
end=rawInput.length();//were finished fall out naturally
}
rawInput[end]='\0';//change whitespace to NULL
ptr[i]=&rawInput[start]; //set a new charpointer to our new segment
}
temp->argc=++i;
temp->argv[i]=NULL;
return temp;
}
bool isValid(arguments* args) {
char* comp = (*args->argv);
bool tf = true;
if (strcmp("cd", comp)==0){
chdir(&comp[3]);
tf = false;
}
else if(strcmp("pwd", comp)==0) {
char* WD = get_current_dir_name();
cout<<*WD<<endl;
delete WD;
tf = false;
}
else if(strcmp("quit", comp)==0){
run = false;
tf = false;
}
*args->argv=comp;
return tf;
}
arguments* writePrompt() {
cout << ">";
return readPrompt();
}
void testArgs(arguments* args) { //just tests using our args class
char * head = *args->argv;
char* ptr = (*args->argv);
cout << "there are " << (args->argc) << " arguments" << endl;
while(ptr!= NULL){
cout<<*ptr<<endl;
++ptr;
}
*args->argv = head;
}
void testSuite(arguments* args, string input) {
char* ptr = (*args->argv);
for (int i = 0; i < args->argc; ++i, ++ptr) {
if (!input.find(ptr, strlen(ptr)-1)) {
cout << "failed test at: " << i << endl;
}
}
}
int redirectLeft(arguments* args){
char* comp;
for(int i=0;i<args->argc-1;i++){
comp=args->argv[i];
if(strcmp("<", comp)==0){
return open(args->argv[i+1], O_RDONLY);
}
else if(strcmp("<<", comp)==0){
return open(args->argv[i+1], O_RDONLY);
}
}
return -1;
}
int redirectRight(arguments* args){
char* comp;
for(int i=0;i<args->argc-1;i++){
comp=args->argv[i];
if(strcmp(">", comp)==0){
return open(args->argv[i+1], O_WRONLY |O_TRUNC | O_CREAT);
}
else if(strcmp(">>", comp)==0){
int temp;
return open(args->argv[i+1], O_WRONLY |O_APPEND | O_CREAT);
return temp;
}
}
return -1;
}
<|endoftext|> |
<commit_before>/*
grabber.cpp
Screen grabber
*/
/* Revision: 1.01 13.07.2000 $ */
/*
Modify:
13.07.2000 SVS
! ४樨 ᯮ짮 new/delete/realloc
25.06.2000 SVS
! ⮢ Master Copy
! 뤥 ⢥ ᠬ⥫쭮
*/
#include "headers.hpp"
#pragma hdrstop
/* $ 30.06.2000 IS
⠭
*/
#include "internalheaders.hpp"
/* IS $ */
Grabber::Grabber()
{
SaveScr=new SaveScreen;
PrevMacroMode=CtrlObject->Macro.GetMode();
CtrlObject->Macro.SetMode(MACRO_OTHER);
int Visible,Size;
GetCursorType(Visible,Size);
if (Visible)
GetCursorPos(GArea.CurX,GArea.CurY);
else
{
GArea.CurX=0;
GArea.CurY=0;
}
GArea.X1=-1;
SetCursorType(TRUE,60);
PrevArea=GArea;
ResetArea=TRUE;
Process();
delete SaveScr;
}
Grabber::~Grabber()
{
CtrlObject->Macro.SetMode(PrevMacroMode);
}
void Grabber::CopyGrabbedArea(int Append)
{
if (GArea.X1==-1)
return;
int X1,Y1,X2,Y2;
X1=Min(GArea.X1,GArea.X2);
X2=Max(GArea.X1,GArea.X2);
Y1=Min(GArea.Y1,GArea.Y2);
Y2=Max(GArea.Y1,GArea.Y2);
int BufSize=(X2-X1+3)*(Y2-Y1+1);
CHAR_INFO *CharBuf=new CHAR_INFO[BufSize];
char *CopyBuf=new char[BufSize];
GetText(X1,Y1,X2,Y2,CharBuf);
*CopyBuf=0;
for (int I=0;I<Y2-Y1+1;I++)
{
if (I>0)
strcat(CopyBuf,"\r\n");
for (int J=0;J<X2-X1+1;J++)
strncat(CopyBuf,&CharBuf[I*(X2-X1+1)+J].Char.AsciiChar,1);
for (int K=strlen(CopyBuf)-1;K>=0 && CopyBuf[K]==' ';K--)
CopyBuf[K]=0;
}
if (Append)
{
char *AppendBuf=PasteFromClipboard();
if (AppendBuf!=NULL)
{
int DataSize=strlen(AppendBuf);
AppendBuf=(char *)realloc(AppendBuf,DataSize+BufSize);
memcpy(AppendBuf+DataSize,CopyBuf,BufSize);
/* $ 13.07.2000 SVS
ࠧ 뢠 new[], 㦭 뢠 delete[]
*/
delete[] CopyBuf;
/* SVS $ */
CopyBuf=AppendBuf;
}
}
CopyToClipboard(CopyBuf);
/* $ 13.07.2000 SVS
ࠧ 뢠 new[], 㦭 뢠 delete[]
*/
delete[] CopyBuf;
delete[] CharBuf;
/* SVS $ */
}
void Grabber::DisplayObject()
{
MoveCursor(GArea.CurX,GArea.CurY);
if (PrevArea.X1!=GArea.X1 || PrevArea.X2!=GArea.X2 ||
PrevArea.Y1!=GArea.Y1 || PrevArea.Y2!=GArea.Y2)
{
int X1,Y1,X2,Y2;
X1=Min(GArea.X1,GArea.X2);
X2=Max(GArea.X1,GArea.X2);
Y1=Min(GArea.Y1,GArea.Y2);
Y2=Max(GArea.Y1,GArea.Y2);
if (X1>Min(PrevArea.X1,PrevArea.X2) || X2<Max(PrevArea.X1,PrevArea.X2) ||
Y1>Min(PrevArea.Y1,PrevArea.Y2) || Y2<Max(PrevArea.Y1,PrevArea.Y2))
SaveScr->RestoreArea(FALSE);
if (GArea.X1!=-1)
{
CHAR_INFO *CharBuf=new CHAR_INFO[(X2-X1+1)*(Y2-Y1+1)];
CHAR_INFO *PrevBuf=SaveScr->GetBufferAddress();
GetText(X1,Y1,X2,Y2,CharBuf);
for (int X=X1;X<=X2;X++)
for (int Y=Y1;Y<=Y2;Y++)
{
int NewColor;
if ((PrevBuf[X+Y*(ScrX+1)].Attributes & B_LIGHTGRAY)==B_LIGHTGRAY)
NewColor=B_BLACK|F_LIGHTGRAY;
else
NewColor=B_LIGHTGRAY|F_BLACK;
int Pos=(X-X1)+(Y-Y1)*(X2-X1+1);
CharBuf[Pos].Attributes=(CharBuf[Pos].Attributes & ~0xff) | NewColor;
}
PutText(X1,Y1,X2,Y2,CharBuf);
/* $ 13.07.2000 SVS
ࠧ 뢠 new[], 㦭 뢠 delete[]
*/
delete[] CharBuf;
/* SVS $ */
}
PrevArea=GArea;
}
}
int Grabber::ProcessKey(int Key)
{
if (ShiftPressed && Key!=KEY_NONE && ResetArea)
{
GArea.X1=GArea.X2=GArea.CurX;
GArea.Y1=GArea.Y2=GArea.CurY;
ResetArea=FALSE;
}
else
if (Key!=KEY_NONE && Key!=KEY_SHIFT && !ShiftPressed)
ResetArea=TRUE;
switch(Key)
{
case KEY_ESC:
SetExitCode(0);
break;
case KEY_ENTER:
case KEY_CTRLINS:
case KEY_CTRLADD:
CopyGrabbedArea(Key==KEY_CTRLADD);
SetExitCode(1);
break;
case KEY_LEFT:
if (GArea.CurX>0)
GArea.CurX--;
break;
case KEY_RIGHT:
if (GArea.CurX<ScrX)
GArea.CurX++;
break;
case KEY_UP:
if (GArea.CurY>0)
GArea.CurY--;
break;
case KEY_DOWN:
if (GArea.CurY<ScrY)
GArea.CurY++;
break;
case KEY_HOME:
GArea.CurX=0;
break;
case KEY_END:
GArea.CurX=ScrX;
break;
case KEY_PGUP:
GArea.CurY=0;
break;
case KEY_PGDN:
GArea.CurY=ScrY;
break;
case KEY_CTRLHOME:
GArea.CurX=GArea.CurY=0;
break;
case KEY_CTRLEND:
GArea.CurX=ScrX;
GArea.CurY=ScrY;
break;
case KEY_CTRLLEFT:
if ((GArea.CurX-=10)<0)
GArea.CurX=0;
break;
case KEY_CTRLRIGHT:
if ((GArea.CurX+=10)>ScrX)
GArea.CurX=ScrX;
break;
case KEY_CTRLUP:
if ((GArea.CurY-=5)<0)
GArea.CurY=0;
break;
case KEY_CTRLDOWN:
if ((GArea.CurY+=5)>ScrY)
GArea.CurY=ScrY;
break;
case KEY_SHIFTLEFT:
if (GArea.X1>0)
GArea.X1--;
GArea.CurX=GArea.X1;
break;
case KEY_SHIFTRIGHT:
if (GArea.X1<ScrX)
GArea.X1++;
GArea.CurX=GArea.X1;
break;
case KEY_SHIFTUP:
if (GArea.Y1>0)
GArea.Y1--;
GArea.CurY=GArea.Y1;
break;
case KEY_SHIFTDOWN:
if (GArea.Y1<ScrY)
GArea.Y1++;
GArea.CurY=GArea.Y1;
break;
case KEY_SHIFTHOME:
GArea.CurX=GArea.X1=0;
break;
case KEY_SHIFTEND:
GArea.CurX=GArea.X1=ScrX;
break;
case KEY_SHIFTPGUP:
GArea.CurY=GArea.Y1=0;
break;
case KEY_SHIFTPGDN:
GArea.CurY=GArea.Y1=ScrY;
break;
}
DisplayObject();
return(TRUE);
}
int Grabber::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
if (MouseEvent->dwEventFlags==DOUBLE_CLICK ||
MouseEvent->dwEventFlags==0 && (MouseEvent->dwButtonState & RIGHTMOST_BUTTON_PRESSED))
{
ProcessKey(KEY_ENTER);
return(TRUE);
}
if (!LButtonPressed)
return(FALSE);
GArea.CurX=MouseX;
GArea.CurY=MouseY;
if (MouseEvent->dwEventFlags==0)
ResetArea=TRUE;
else
if (MouseEvent->dwEventFlags==MOUSE_MOVED)
{
if (ResetArea)
{
GArea.X2=GArea.CurX;
GArea.Y2=GArea.CurY;
ResetArea=FALSE;
}
GArea.X1=GArea.CurX;
GArea.Y1=GArea.CurY;
}
DisplayObject();
return(TRUE);
}
<commit_msg>FAR patch 00127.grabber.cpp Дата : 14.08.2000 Сделал : andrey tretjakov Описание : убирает трап при проигрывании макроса c ShiftEnd Измененные файлы : grabber.cpp Состав : grabber.cpp.txt grabber.cpp.diff Основан на патче : 124 Дополнение :<commit_after>/*
grabber.cpp
Screen grabber
*/
/* Revision: 1.02 14.08.2000 $ */
/*
Modify:
14.08.2000 tran
- trap ந뢠 蠬 ⨯ Shift...
13.07.2000 SVS
! ४樨 ᯮ짮 new/delete/realloc
25.06.2000 SVS
! ⮢ Master Copy
! 뤥 ⢥ ᠬ⥫쭮
*/
#include "headers.hpp"
#pragma hdrstop
/* $ 30.06.2000 IS
⠭
*/
#include "internalheaders.hpp"
/* IS $ */
Grabber::Grabber()
{
SaveScr=new SaveScreen;
PrevMacroMode=CtrlObject->Macro.GetMode();
CtrlObject->Macro.SetMode(MACRO_OTHER);
/* $ 14.08.2000 tran
蠥 , 㦥 */
memset(&GArea,0,sizeof(GArea));
memset(&PrevArea,0,sizeof(PrevArea));
/* tran 14.08.2000 $ */
int Visible,Size;
GetCursorType(Visible,Size);
if (Visible)
GetCursorPos(GArea.CurX,GArea.CurY);
else
{
GArea.CurX=0;
GArea.CurY=0;
}
GArea.X1=-1;
SetCursorType(TRUE,60);
PrevArea=GArea;
ResetArea=TRUE;
Process();
delete SaveScr;
}
Grabber::~Grabber()
{
CtrlObject->Macro.SetMode(PrevMacroMode);
}
void Grabber::CopyGrabbedArea(int Append)
{
if (GArea.X1==-1)
return;
int X1,Y1,X2,Y2;
X1=Min(GArea.X1,GArea.X2);
X2=Max(GArea.X1,GArea.X2);
Y1=Min(GArea.Y1,GArea.Y2);
Y2=Max(GArea.Y1,GArea.Y2);
int BufSize=(X2-X1+3)*(Y2-Y1+1);
CHAR_INFO *CharBuf=new CHAR_INFO[BufSize];
char *CopyBuf=new char[BufSize];
GetText(X1,Y1,X2,Y2,CharBuf);
*CopyBuf=0;
for (int I=0;I<Y2-Y1+1;I++)
{
if (I>0)
strcat(CopyBuf,"\r\n");
for (int J=0;J<X2-X1+1;J++)
strncat(CopyBuf,&CharBuf[I*(X2-X1+1)+J].Char.AsciiChar,1);
for (int K=strlen(CopyBuf)-1;K>=0 && CopyBuf[K]==' ';K--)
CopyBuf[K]=0;
}
if (Append)
{
char *AppendBuf=PasteFromClipboard();
if (AppendBuf!=NULL)
{
int DataSize=strlen(AppendBuf);
AppendBuf=(char *)realloc(AppendBuf,DataSize+BufSize);
memcpy(AppendBuf+DataSize,CopyBuf,BufSize);
/* $ 13.07.2000 SVS
ࠧ 뢠 new[], 㦭 뢠 delete[]
*/
delete[] CopyBuf;
/* SVS $ */
CopyBuf=AppendBuf;
}
}
CopyToClipboard(CopyBuf);
/* $ 13.07.2000 SVS
ࠧ 뢠 new[], 㦭 뢠 delete[]
*/
delete[] CopyBuf;
delete[] CharBuf;
/* SVS $ */
}
void Grabber::DisplayObject()
{
MoveCursor(GArea.CurX,GArea.CurY);
if (PrevArea.X1!=GArea.X1 || PrevArea.X2!=GArea.X2 ||
PrevArea.Y1!=GArea.Y1 || PrevArea.Y2!=GArea.Y2)
{
int X1,Y1,X2,Y2;
X1=Min(GArea.X1,GArea.X2);
X2=Max(GArea.X1,GArea.X2);
Y1=Min(GArea.Y1,GArea.Y2);
Y2=Max(GArea.Y1,GArea.Y2);
if (X1>Min(PrevArea.X1,PrevArea.X2) || X2<Max(PrevArea.X1,PrevArea.X2) ||
Y1>Min(PrevArea.Y1,PrevArea.Y2) || Y2<Max(PrevArea.Y1,PrevArea.Y2))
SaveScr->RestoreArea(FALSE);
if (GArea.X1!=-1)
{
CHAR_INFO *CharBuf=new CHAR_INFO[(X2-X1+1)*(Y2-Y1+1)];
CHAR_INFO *PrevBuf=SaveScr->GetBufferAddress();
GetText(X1,Y1,X2,Y2,CharBuf);
for (int X=X1;X<=X2;X++)
for (int Y=Y1;Y<=Y2;Y++)
{
int NewColor;
if ((PrevBuf[X+Y*(ScrX+1)].Attributes & B_LIGHTGRAY)==B_LIGHTGRAY)
NewColor=B_BLACK|F_LIGHTGRAY;
else
NewColor=B_LIGHTGRAY|F_BLACK;
int Pos=(X-X1)+(Y-Y1)*(X2-X1+1);
CharBuf[Pos].Attributes=(CharBuf[Pos].Attributes & ~0xff) | NewColor;
}
PutText(X1,Y1,X2,Y2,CharBuf);
/* $ 13.07.2000 SVS
ࠧ 뢠 new[], 㦭 뢠 delete[]
*/
delete[] CharBuf;
/* SVS $ */
}
PrevArea=GArea;
}
}
int Grabber::ProcessKey(int Key)
{
if (ShiftPressed && Key!=KEY_NONE && ResetArea)
{
GArea.X1=GArea.X2=GArea.CurX;
GArea.Y1=GArea.Y2=GArea.CurY;
ResetArea=FALSE;
}
else
if (Key!=KEY_NONE && Key!=KEY_SHIFT && !ShiftPressed)
ResetArea=TRUE;
switch(Key)
{
case KEY_ESC:
SetExitCode(0);
break;
case KEY_ENTER:
case KEY_CTRLINS:
case KEY_CTRLADD:
CopyGrabbedArea(Key==KEY_CTRLADD);
SetExitCode(1);
break;
case KEY_LEFT:
if (GArea.CurX>0)
GArea.CurX--;
break;
case KEY_RIGHT:
if (GArea.CurX<ScrX)
GArea.CurX++;
break;
case KEY_UP:
if (GArea.CurY>0)
GArea.CurY--;
break;
case KEY_DOWN:
if (GArea.CurY<ScrY)
GArea.CurY++;
break;
case KEY_HOME:
GArea.CurX=0;
break;
case KEY_END:
GArea.CurX=ScrX;
break;
case KEY_PGUP:
GArea.CurY=0;
break;
case KEY_PGDN:
GArea.CurY=ScrY;
break;
case KEY_CTRLHOME:
GArea.CurX=GArea.CurY=0;
break;
case KEY_CTRLEND:
GArea.CurX=ScrX;
GArea.CurY=ScrY;
break;
case KEY_CTRLLEFT:
if ((GArea.CurX-=10)<0)
GArea.CurX=0;
break;
case KEY_CTRLRIGHT:
if ((GArea.CurX+=10)>ScrX)
GArea.CurX=ScrX;
break;
case KEY_CTRLUP:
if ((GArea.CurY-=5)<0)
GArea.CurY=0;
break;
case KEY_CTRLDOWN:
if ((GArea.CurY+=5)>ScrY)
GArea.CurY=ScrY;
break;
case KEY_SHIFTLEFT:
if (GArea.X1>0)
GArea.X1--;
GArea.CurX=GArea.X1;
break;
case KEY_SHIFTRIGHT:
if (GArea.X1<ScrX)
GArea.X1++;
GArea.CurX=GArea.X1;
break;
case KEY_SHIFTUP:
if (GArea.Y1>0)
GArea.Y1--;
GArea.CurY=GArea.Y1;
break;
case KEY_SHIFTDOWN:
if (GArea.Y1<ScrY)
GArea.Y1++;
GArea.CurY=GArea.Y1;
break;
case KEY_SHIFTHOME:
GArea.CurX=GArea.X1=0;
break;
case KEY_SHIFTEND:
GArea.CurX=GArea.X1=ScrX;
break;
case KEY_SHIFTPGUP:
GArea.CurY=GArea.Y1=0;
break;
case KEY_SHIFTPGDN:
GArea.CurY=GArea.Y1=ScrY;
break;
}
DisplayObject();
return(TRUE);
}
int Grabber::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
if (MouseEvent->dwEventFlags==DOUBLE_CLICK ||
MouseEvent->dwEventFlags==0 && (MouseEvent->dwButtonState & RIGHTMOST_BUTTON_PRESSED))
{
ProcessKey(KEY_ENTER);
return(TRUE);
}
if (!LButtonPressed)
return(FALSE);
GArea.CurX=MouseX;
GArea.CurY=MouseY;
if (MouseEvent->dwEventFlags==0)
ResetArea=TRUE;
else
if (MouseEvent->dwEventFlags==MOUSE_MOVED)
{
if (ResetArea)
{
GArea.X2=GArea.CurX;
GArea.Y2=GArea.CurY;
ResetArea=FALSE;
}
GArea.X1=GArea.CurX;
GArea.Y1=GArea.CurY;
}
DisplayObject();
return(TRUE);
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "QOSPRayWindow.h"
QOSPRayWindow::QOSPRayWindow(QMainWindow *parent,
OSPRenderer renderer,
bool showFrameRate,
std::string writeFramesFilename)
: parent(parent),
showFrameRate(showFrameRate),
frameCount(0),
renderingEnabled(false),
rotationRate(0.f),
benchmarkWarmUpFrames(0),
benchmarkFrames(0),
frameBuffer(NULL),
renderer(NULL),
camera(NULL),
writeFramesFilename(writeFramesFilename)
{
// assign renderer
if(!renderer)
throw std::runtime_error("QOSPRayWindow: must be constructed with an existing renderer");
this->renderer = renderer;
// setup camera
camera = ospNewCamera("perspective");
if(!camera)
throw std::runtime_error("QOSPRayWindow: could not create camera type 'perspective'");
ospCommit(camera);
ospSetObject(renderer, "camera", camera);
// connect signals and slots
connect(&renderTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
}
QOSPRayWindow::~QOSPRayWindow()
{
// free the frame buffer and camera
// we don't own the renderer!
if(frameBuffer)
ospFreeFrameBuffer(frameBuffer);
if(camera)
ospRelease(camera);
}
void QOSPRayWindow::setRenderingEnabled(bool renderingEnabled)
{
this->renderingEnabled = renderingEnabled;
// trigger render if true
if(renderingEnabled == true)
renderTimer.start();
else
renderTimer.stop();
}
void QOSPRayWindow::setRotationRate(float rotationRate)
{
this->rotationRate = rotationRate;
}
void QOSPRayWindow::setBenchmarkParameters(int benchmarkWarmUpFrames, int benchmarkFrames)
{
this->benchmarkWarmUpFrames = benchmarkWarmUpFrames;
this->benchmarkFrames = benchmarkFrames;
}
void QOSPRayWindow::setWorldBounds(const osp::box3f &worldBounds)
{
this->worldBounds = worldBounds;
// set viewport look at point to center of world bounds
viewport.at = center(worldBounds);
// set viewport from point relative to center of world bounds
viewport.from = viewport.at - 1.5f * viewport.frame.l.vy;
updateGL();
}
void QOSPRayWindow::paintGL()
{
if(!renderingEnabled || !frameBuffer || !renderer)
return;
// if we're benchmarking and we've completed the required number of warm-up frames, start the timer
if(benchmarkFrames > 0 && frameCount == benchmarkWarmUpFrames) {
std::cout << "starting benchmark timer" << std::endl;
benchmarkTimer.start();
}
// update OSPRay camera if viewport has been modified
if(viewport.modified) {
ospSetVec3f(camera,"pos" ,viewport.from);
ospSetVec3f(camera,"dir" ,viewport.at - viewport.from);
ospSetVec3f(camera,"up", viewport.up);
ospSetf(camera,"aspect", viewport.aspect);
ospSetf(camera,"fovy", viewport.fovY);
ospCommit(camera);
viewport.modified = false;
}
renderFrameTimer.start();
ospRenderFrame(frameBuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);
double framesPerSecond = 1000.0 / renderFrameTimer.elapsed();
char title[1024]; sprintf(title, "OSPRay Volume Viewer (%.4f fps)", framesPerSecond);
if (showFrameRate == true) parent->setWindowTitle(title);
uint32 *mappedFrameBuffer = (unsigned int *) ospMapFrameBuffer(frameBuffer);
glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, mappedFrameBuffer);
if (writeFramesFilename.length()) writeFrameBufferToFile(mappedFrameBuffer);
ospUnmapFrameBuffer(mappedFrameBuffer, frameBuffer);
// automatic rotation
if(rotationRate != 0.f) {
resetAccumulationBuffer();
rotateCenter(rotationRate, 0.f);
}
// increment frame counter
frameCount++;
// quit if we're benchmarking and have exceeded the needed number of frames
if(benchmarkFrames > 0 && frameCount >= benchmarkWarmUpFrames + benchmarkFrames) {
float elapsedSeconds = float(benchmarkTimer.elapsed()) / 1000.f;
std::cout << "benchmark: " << elapsedSeconds << " elapsed seconds ==> " << float(benchmarkFrames) / elapsedSeconds << " fps" << std::endl;
QCoreApplication::quit();
}
}
void QOSPRayWindow::resizeGL(int width, int height)
{
windowSize = osp::vec2i(width, height);
// reallocate OSPRay framebuffer for new size
if(frameBuffer)
ospFreeFrameBuffer(frameBuffer);
frameBuffer = ospNewFrameBuffer(windowSize, OSP_RGBA_I8, OSP_FB_COLOR | OSP_FB_ACCUM);
// update viewport aspect ratio
viewport.aspect = float(width) / float(height);
viewport.modified = true;
// update OpenGL viewport and force redraw
glViewport(0, 0, width, height);
updateGL();
}
void QOSPRayWindow::mousePressEvent(QMouseEvent * event)
{
lastMousePosition = event->pos();
}
void QOSPRayWindow::mouseReleaseEvent(QMouseEvent * event)
{
lastMousePosition = event->pos();
}
void QOSPRayWindow::mouseMoveEvent(QMouseEvent * event)
{
resetAccumulationBuffer();
int dx = event->x() - lastMousePosition.x();
int dy = event->y() - lastMousePosition.y();
if(event->buttons() & Qt::LeftButton) {
// camera rotation about center point
const float rotationSpeed = 0.003f;
float du = dx * rotationSpeed;
float dv = dy * rotationSpeed;
rotateCenter(du, dv);
}
else if(event->buttons() & Qt::RightButton) {
// camera distance from center point
const float motionSpeed = 0.012f;
float forward = dy * motionSpeed;
float oldDistance = length(viewport.at - viewport.from);
float newDistance = oldDistance - forward;
if(newDistance < 1e-3f)
return;
viewport.from = viewport.at - newDistance * viewport.frame.l.vy;
viewport.frame.p = viewport.from;
viewport.modified = true;
}
lastMousePosition = event->pos();
updateGL();
}
void QOSPRayWindow::rotateCenter(float du, float dv)
{
const osp::vec3f pivot = center(worldBounds);
osp::affine3f xfm = osp::affine3f::translate(pivot)
* osp::affine3f::rotate(viewport.frame.l.vx, -dv)
* osp::affine3f::rotate(viewport.frame.l.vz, -du)
* osp::affine3f::translate(-pivot);
viewport.frame = xfm * viewport.frame;
viewport.from = xfmPoint(xfm, viewport.from);
viewport.at = xfmPoint(xfm, viewport.at);
viewport.snapUp();
viewport.modified = true;
}
void QOSPRayWindow::writeFrameBufferToFile(const uint32 *pixelData)
{
static uint32 frameNumber = 0;
char filename[1024];
sprintf(filename, "%s_%05u.ppm", writeFramesFilename.c_str(), frameNumber++);
FILE *file = fopen(filename, "wb"); if (!file) { std::cerr << "unable to write to file '" << filename << "'" << std::endl; return; }
fprintf(file, "P6\n%i %i\n255\n", windowSize.x, windowSize.y);
unsigned char out[3 * windowSize.x];
for (int y=0 ; y < windowSize.y ; y++) {
const unsigned char *in = (const unsigned char *) &pixelData[(windowSize.y - 1 - y) * windowSize.x];
for (int x=0 ; x < windowSize.x ; x++) {
out[3 * x + 0] = in[4 * x + 0];
out[3 * x + 1] = in[4 * x + 1];
out[3 * x + 2] = in[4 * x + 2];
}
fwrite(&out, 3 * windowSize.x, sizeof(char), file);
}
fprintf(file, "\n");
fclose(file);
}
<commit_msg>volume viewer resets accumulation on window resize.<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "QOSPRayWindow.h"
QOSPRayWindow::QOSPRayWindow(QMainWindow *parent,
OSPRenderer renderer,
bool showFrameRate,
std::string writeFramesFilename)
: parent(parent),
showFrameRate(showFrameRate),
frameCount(0),
renderingEnabled(false),
rotationRate(0.f),
benchmarkWarmUpFrames(0),
benchmarkFrames(0),
frameBuffer(NULL),
renderer(NULL),
camera(NULL),
writeFramesFilename(writeFramesFilename)
{
// assign renderer
if(!renderer)
throw std::runtime_error("QOSPRayWindow: must be constructed with an existing renderer");
this->renderer = renderer;
// setup camera
camera = ospNewCamera("perspective");
if(!camera)
throw std::runtime_error("QOSPRayWindow: could not create camera type 'perspective'");
ospCommit(camera);
ospSetObject(renderer, "camera", camera);
// connect signals and slots
connect(&renderTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
}
QOSPRayWindow::~QOSPRayWindow()
{
// free the frame buffer and camera
// we don't own the renderer!
if(frameBuffer)
ospFreeFrameBuffer(frameBuffer);
if(camera)
ospRelease(camera);
}
void QOSPRayWindow::setRenderingEnabled(bool renderingEnabled)
{
this->renderingEnabled = renderingEnabled;
// trigger render if true
if(renderingEnabled == true)
renderTimer.start();
else
renderTimer.stop();
}
void QOSPRayWindow::setRotationRate(float rotationRate)
{
this->rotationRate = rotationRate;
}
void QOSPRayWindow::setBenchmarkParameters(int benchmarkWarmUpFrames, int benchmarkFrames)
{
this->benchmarkWarmUpFrames = benchmarkWarmUpFrames;
this->benchmarkFrames = benchmarkFrames;
}
void QOSPRayWindow::setWorldBounds(const osp::box3f &worldBounds)
{
this->worldBounds = worldBounds;
// set viewport look at point to center of world bounds
viewport.at = center(worldBounds);
// set viewport from point relative to center of world bounds
viewport.from = viewport.at - 1.5f * viewport.frame.l.vy;
updateGL();
}
void QOSPRayWindow::paintGL()
{
if(!renderingEnabled || !frameBuffer || !renderer)
return;
// if we're benchmarking and we've completed the required number of warm-up frames, start the timer
if(benchmarkFrames > 0 && frameCount == benchmarkWarmUpFrames) {
std::cout << "starting benchmark timer" << std::endl;
benchmarkTimer.start();
}
// update OSPRay camera if viewport has been modified
if(viewport.modified) {
ospSetVec3f(camera,"pos" ,viewport.from);
ospSetVec3f(camera,"dir" ,viewport.at - viewport.from);
ospSetVec3f(camera,"up", viewport.up);
ospSetf(camera,"aspect", viewport.aspect);
ospSetf(camera,"fovy", viewport.fovY);
ospCommit(camera);
viewport.modified = false;
}
renderFrameTimer.start();
ospRenderFrame(frameBuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);
double framesPerSecond = 1000.0 / renderFrameTimer.elapsed();
char title[1024]; sprintf(title, "OSPRay Volume Viewer (%.4f fps)", framesPerSecond);
if (showFrameRate == true) parent->setWindowTitle(title);
uint32 *mappedFrameBuffer = (unsigned int *) ospMapFrameBuffer(frameBuffer);
glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, mappedFrameBuffer);
if (writeFramesFilename.length()) writeFrameBufferToFile(mappedFrameBuffer);
ospUnmapFrameBuffer(mappedFrameBuffer, frameBuffer);
// automatic rotation
if(rotationRate != 0.f) {
resetAccumulationBuffer();
rotateCenter(rotationRate, 0.f);
}
// increment frame counter
frameCount++;
// quit if we're benchmarking and have exceeded the needed number of frames
if(benchmarkFrames > 0 && frameCount >= benchmarkWarmUpFrames + benchmarkFrames) {
float elapsedSeconds = float(benchmarkTimer.elapsed()) / 1000.f;
std::cout << "benchmark: " << elapsedSeconds << " elapsed seconds ==> " << float(benchmarkFrames) / elapsedSeconds << " fps" << std::endl;
QCoreApplication::quit();
}
}
void QOSPRayWindow::resizeGL(int width, int height)
{
windowSize = osp::vec2i(width, height);
// reallocate OSPRay framebuffer for new size
if(frameBuffer)
ospFreeFrameBuffer(frameBuffer);
frameBuffer = ospNewFrameBuffer(windowSize, OSP_RGBA_I8, OSP_FB_COLOR | OSP_FB_ACCUM);
resetAccumulationBuffer();
// update viewport aspect ratio
viewport.aspect = float(width) / float(height);
viewport.modified = true;
// update OpenGL viewport and force redraw
glViewport(0, 0, width, height);
updateGL();
}
void QOSPRayWindow::mousePressEvent(QMouseEvent * event)
{
lastMousePosition = event->pos();
}
void QOSPRayWindow::mouseReleaseEvent(QMouseEvent * event)
{
lastMousePosition = event->pos();
}
void QOSPRayWindow::mouseMoveEvent(QMouseEvent * event)
{
resetAccumulationBuffer();
int dx = event->x() - lastMousePosition.x();
int dy = event->y() - lastMousePosition.y();
if(event->buttons() & Qt::LeftButton) {
// camera rotation about center point
const float rotationSpeed = 0.003f;
float du = dx * rotationSpeed;
float dv = dy * rotationSpeed;
rotateCenter(du, dv);
}
else if(event->buttons() & Qt::RightButton) {
// camera distance from center point
const float motionSpeed = 0.012f;
float forward = dy * motionSpeed;
float oldDistance = length(viewport.at - viewport.from);
float newDistance = oldDistance - forward;
if(newDistance < 1e-3f)
return;
viewport.from = viewport.at - newDistance * viewport.frame.l.vy;
viewport.frame.p = viewport.from;
viewport.modified = true;
}
lastMousePosition = event->pos();
updateGL();
}
void QOSPRayWindow::rotateCenter(float du, float dv)
{
const osp::vec3f pivot = center(worldBounds);
osp::affine3f xfm = osp::affine3f::translate(pivot)
* osp::affine3f::rotate(viewport.frame.l.vx, -dv)
* osp::affine3f::rotate(viewport.frame.l.vz, -du)
* osp::affine3f::translate(-pivot);
viewport.frame = xfm * viewport.frame;
viewport.from = xfmPoint(xfm, viewport.from);
viewport.at = xfmPoint(xfm, viewport.at);
viewport.snapUp();
viewport.modified = true;
}
void QOSPRayWindow::writeFrameBufferToFile(const uint32 *pixelData)
{
static uint32 frameNumber = 0;
char filename[1024];
sprintf(filename, "%s_%05u.ppm", writeFramesFilename.c_str(), frameNumber++);
FILE *file = fopen(filename, "wb"); if (!file) { std::cerr << "unable to write to file '" << filename << "'" << std::endl; return; }
fprintf(file, "P6\n%i %i\n255\n", windowSize.x, windowSize.y);
unsigned char out[3 * windowSize.x];
for (int y=0 ; y < windowSize.y ; y++) {
const unsigned char *in = (const unsigned char *) &pixelData[(windowSize.y - 1 - y) * windowSize.x];
for (int x=0 ; x < windowSize.x ; x++) {
out[3 * x + 0] = in[4 * x + 0];
out[3 * x + 1] = in[4 * x + 1];
out[3 * x + 2] = in[4 * x + 2];
}
fwrite(&out, 3 * windowSize.x, sizeof(char), file);
}
fprintf(file, "\n");
fclose(file);
}
<|endoftext|> |
<commit_before>#include <nan.h>
#include <v8-profiler.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <time.h>
#define snprintf _snprintf
#else
#include <sys/time.h>
#endif
using namespace v8;
char filename[256];
bool addTimestamp;
class FileOutputStream: public OutputStream {
public:
FileOutputStream(FILE* stream): stream_(stream) { }
virtual int GetChunkSize() {
return 65536;
}
virtual void EndOfStream() { }
virtual WriteResult WriteAsciiChunk(char* data, int size) {
const size_t len = static_cast<size_t>(size);
size_t off = 0;
while (off < len && !feof(stream_) && !ferror(stream_))
off += fwrite(data + off, 1, len - off, stream_);
return off == len ? kContinue : kAbort;
}
private:
FILE* stream_;
};
void OnOOMError(const char *location, bool is_heap_oom) {
if (addTimestamp) {
// Add timestamp to filename
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char * pch;
pch = strstr (filename,".heapsnapshot");
strncpy (pch,"",1);
strcat (filename, "-%Y%m%dT%H%M%S.heapsnapshot");
char newFilename[256];
strftime(newFilename, sizeof(filename), filename, timeinfo);
strcpy(filename, newFilename);
}
fprintf(stderr, "Generating Heapdump to '%s' now...\n", filename);
FILE* fp = fopen(filename, "w");
if (fp == NULL) abort();
// Create heapdump, depending on which Node.js version this can differ
// for now, just support Node.js 7 and higher
const HeapSnapshot* snap = v8::Isolate::GetCurrent()->GetHeapProfiler()->TakeHeapSnapshot();
FileOutputStream stream(fp);
snap->Serialize(&stream, HeapSnapshot::kJSON);
fclose(fp);
fprintf(stderr, "Done! Exiting process now.\n");
exit(1);
}
void ParseArgumentsAndSetErrorHandler(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
isolate->SetOOMErrorHandler(OnOOMError);
// parse JS arguments
// 1: filename
// 2: addTimestamp boolean
#if NODE_VERSION_AT_LEAST(9, 0, 0)
String::Utf8Value fArg(isolate, args[0]->ToString());
#else
String::Utf8Value fArg(args[0]->ToString());
#endif
strncpy(filename, (const char*)(*fArg), sizeof(filename) - 1);
addTimestamp = args[1]->BooleanValue();
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "call", ParseArgumentsAndSetErrorHandler);
}
NODE_MODULE(NODE_OOM_HEAPDUMP_NATIVE, init)<commit_msg>Initial try-out for making it Node 12 compatible. Still we should look into using "Maybe" version of v8 API: https://github.com/joyeecheung/node/blob/v8-maybe-doc/CPP_STYLE_GUIDE.md#use-maybe-version-of-v8-apis<commit_after>#include <nan.h>
#include <v8-profiler.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <time.h>
#define snprintf _snprintf
#else
#include <sys/time.h>
#endif
using namespace v8;
char filename[256];
bool addTimestamp;
class FileOutputStream: public OutputStream {
public:
FileOutputStream(FILE* stream): stream_(stream) { }
virtual int GetChunkSize() {
return 65536;
}
virtual void EndOfStream() { }
virtual WriteResult WriteAsciiChunk(char* data, int size) {
const size_t len = static_cast<size_t>(size);
size_t off = 0;
while (off < len && !feof(stream_) && !ferror(stream_))
off += fwrite(data + off, 1, len - off, stream_);
return off == len ? kContinue : kAbort;
}
private:
FILE* stream_;
};
void OnOOMError(const char *location, bool is_heap_oom) {
if (addTimestamp) {
// Add timestamp to filename
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char * pch;
pch = strstr (filename,".heapsnapshot");
strncpy (pch,"",1);
strcat (filename, "-%Y%m%dT%H%M%S.heapsnapshot");
char newFilename[256];
strftime(newFilename, sizeof(filename), filename, timeinfo);
strcpy(filename, newFilename);
}
fprintf(stderr, "Generating Heapdump to '%s' now...\n", filename);
FILE* fp = fopen(filename, "w");
if (fp == NULL) abort();
// Create heapdump, depending on which Node.js version this can differ
// for now, just support Node.js 7 and higher
const HeapSnapshot* snap = v8::Isolate::GetCurrent()->GetHeapProfiler()->TakeHeapSnapshot();
FileOutputStream stream(fp);
snap->Serialize(&stream, HeapSnapshot::kJSON);
fclose(fp);
fprintf(stderr, "Done! Exiting process now.\n");
exit(1);
}
void ParseArgumentsAndSetErrorHandler(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
isolate->SetOOMErrorHandler(OnOOMError);
// parse JS arguments
// 1: filename
// 2: addTimestamp boolean
#if NODE_VERSION_AT_LEAST(12, 0, 0)
String::Utf8Value fArg(isolate, args[0]->ToString(isolate));
#elif NODE_VERSION_AT_LEAST(9, 0, 0)
String::Utf8Value fArg(isolate, args[0]->ToString());
#else
String::Utf8Value fArg(args[0]->ToString());
#endif
strncpy(filename, (const char*)(*fArg), sizeof(filename) - 1);
#if NODE_VERSION_AT_LEAST(12, 0, 0)
addTimestamp = args[1]->BooleanValue(isolate);
#else
addTimestamp = args[1]->BooleanValue();
#endif
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "call", ParseArgumentsAndSetErrorHandler);
}
NODE_MODULE(NODE_OOM_HEAPDUMP_NATIVE, init)<|endoftext|> |
<commit_before>#include "chi/GraphStruct.hpp"
#include "chi/Context.hpp"
#include "chi/GraphModule.hpp"
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/DerivedTypes.h>
namespace chi {
GraphStruct::GraphStruct(GraphModule& mod, std::string name)
: mModule{&mod}, mContext{&mod.context()}, mName{std::move(name)} {}
void GraphStruct::addType(DataType ty, std::string name, size_t addBefore) {
Expects(addBefore <= types().size() && ty.valid() && !name.empty());
mTypes.emplace_back(name, ty);
// invalidate the current DataType
mDataType = {};
}
void GraphStruct::modifyType(size_t id, DataType newTy, std::string newName) {
Expects(id < types().size() && newTy.valid() && !newName.empty());
mTypes[id] = {std::move(newName), std::move(newTy)};
// invalidate the current DataType
mDataType = {};
}
void GraphStruct::removeType(size_t id) {
Expects(id < types().size());
mTypes.erase(mTypes.begin() + id);
// invalidate the current DataType
mDataType = {};
}
DataType GraphStruct::dataType() {
// if we have already calculated this, use that
if (mDataType.valid()) { return mDataType; }
if (types().empty()) { return {}; }
// create llvm::Type
std::vector<llvm::Type*> llTypes;
llTypes.reserve(types().size());
std::vector<llvm::Metadata*> diTypes;
diTypes.reserve(types().size());
size_t currentOffset = 0;
for (const auto& type : types()) {
auto debugType = type.type.debugType();
llTypes.push_back(type.type.llvmType());
#if LLVM_VERSION_MAJOR <= 3 && LLVM_VERSION_MINOR <= 6
// make a temp module so we can make a DIBuilder
auto tmpMod = std::make_unique<llvm::Module>("tmp", context().llvmContext());
auto diBuilder = std::make_unique<llvm::DIBuilder>(*tmpMod);
auto member = diBuilder->createMemberType(nullptr, type.name, nullptr, 0, debugType->getSizeInBits(), 8, currentOffset, 0, nullptr);
#else
auto member =
llvm::DIDerivedType::get(context().llvmContext(), llvm::dwarf::DW_TAG_member,
#if LLVM_VERSION_MAJOR <= 3 && LLVM_VERSION_MINOR <= 8
llvm::MDString::get(context().llvmContext(), type.name),
#else
type.name,
#endif
nullptr, 0, nullptr, debugType, debugType->getSizeInBits(), 8,
currentOffset, llvm::DINode::DIFlags{}, nullptr);
#endif
diTypes.push_back(member);
currentOffset += debugType->getSizeInBits();
}
auto llType = llvm::StructType::create(llTypes, name());
auto diStructType = llvm::DICompositeType::get(
context().llvmContext(), llvm::dwarf::DW_TAG_structure_type, name(), nullptr, 0, nullptr,
nullptr, currentOffset, 8, 0, llvm::DINode::DIFlags{},
llvm::MDTuple::get(context().llvmContext(), diTypes), 0, nullptr, {}, "");
mDataType = DataType(&module(), name(), llType, diStructType);
return mDataType;
}
} // namespace chi
<commit_msg>Fix call to createMemberType<commit_after>#include "chi/GraphStruct.hpp"
#include "chi/Context.hpp"
#include "chi/GraphModule.hpp"
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/DerivedTypes.h>
namespace chi {
GraphStruct::GraphStruct(GraphModule& mod, std::string name)
: mModule{&mod}, mContext{&mod.context()}, mName{std::move(name)} {}
void GraphStruct::addType(DataType ty, std::string name, size_t addBefore) {
Expects(addBefore <= types().size() && ty.valid() && !name.empty());
mTypes.emplace_back(name, ty);
// invalidate the current DataType
mDataType = {};
}
void GraphStruct::modifyType(size_t id, DataType newTy, std::string newName) {
Expects(id < types().size() && newTy.valid() && !newName.empty());
mTypes[id] = {std::move(newName), std::move(newTy)};
// invalidate the current DataType
mDataType = {};
}
void GraphStruct::removeType(size_t id) {
Expects(id < types().size());
mTypes.erase(mTypes.begin() + id);
// invalidate the current DataType
mDataType = {};
}
DataType GraphStruct::dataType() {
// if we have already calculated this, use that
if (mDataType.valid()) { return mDataType; }
if (types().empty()) { return {}; }
// create llvm::Type
std::vector<llvm::Type*> llTypes;
llTypes.reserve(types().size());
std::vector<llvm::Metadata*> diTypes;
diTypes.reserve(types().size());
size_t currentOffset = 0;
for (const auto& type : types()) {
auto debugType = type.type.debugType();
llTypes.push_back(type.type.llvmType());
#if LLVM_VERSION_MAJOR <= 3 && LLVM_VERSION_MINOR <= 6
// make a temp module so we can make a DIBuilder
auto tmpMod = std::make_unique<llvm::Module>("tmp", context().llvmContext());
auto diBuilder = std::make_unique<llvm::DIBuilder>(*tmpMod);
auto member = diBuilder->createMemberType(llvm::DIDescriptor(), type.name, llvm::DIFile(), 0, debugType->getSizeInBits(), 8, currentOffset, 0, *debugType);
#else
auto member =
llvm::DIDerivedType::get(context().llvmContext(), llvm::dwarf::DW_TAG_member,
#if LLVM_VERSION_MAJOR <= 3 && LLVM_VERSION_MINOR <= 8
llvm::MDString::get(context().llvmContext(), type.name),
#else
type.name,
#endif
nullptr, 0, nullptr, debugType, debugType->getSizeInBits(), 8,
currentOffset, llvm::DINode::DIFlags{}, nullptr);
#endif
diTypes.push_back(member);
currentOffset += debugType->getSizeInBits();
}
auto llType = llvm::StructType::create(llTypes, name());
auto diStructType = llvm::DICompositeType::get(
context().llvmContext(), llvm::dwarf::DW_TAG_structure_type, name(), nullptr, 0, nullptr,
nullptr, currentOffset, 8, 0, llvm::DINode::DIFlags{},
llvm::MDTuple::get(context().llvmContext(), diTypes), 0, nullptr, {}, "");
mDataType = DataType(&module(), name(), llType, diStructType);
return mDataType;
}
} // namespace chi
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include "franka/vacuum_gripper_state.h"
#include <cstring>
namespace franka {
std::ostream& operator<<(std::ostream& ostream,
const franka::VacuumGripperState& vacuum_gripper_state) {
std::string device_status;
switch (vacuum_gripper_state.device_status) {
case VacuumGripperDeviceStatus::kGreen:
device_status = "Green";
break;
case VacuumGripperDeviceStatus::kYellow:
device_status = "Yellow";
break;
case VacuumGripperDeviceStatus::kOrange:
device_status = "Orange";
break;
case VacuumGripperDeviceStatus::kRed:
device_status = "Red";
break;
}
ostream << "{\"in_control_range\": " << vacuum_gripper_state.in_control_range
<< ", \"part_detached\": " << vacuum_gripper_state.part_detached
<< ", \"part_present\": " << vacuum_gripper_state.part_present
<< ", \"device_status\": " << device_status
<< ", \"actual_power\": " << vacuum_gripper_state.actual_power
<< ", \"vacuum\": " << vacuum_gripper_state.vacuum
<< ", \"time\": " << vacuum_gripper_state.time.toSec() << "}";
return ostream;
}
} // namespace franka
<commit_msg>Fix JSON serializing of VacuumGripperState.<commit_after>// Copyright (c) 2019 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include "franka/vacuum_gripper_state.h"
#include <cstring>
namespace franka {
std::ostream& operator<<(std::ostream& ostream,
const franka::VacuumGripperState& vacuum_gripper_state) {
std::string device_status;
switch (vacuum_gripper_state.device_status) {
case VacuumGripperDeviceStatus::kGreen:
device_status = "Green";
break;
case VacuumGripperDeviceStatus::kYellow:
device_status = "Yellow";
break;
case VacuumGripperDeviceStatus::kOrange:
device_status = "Orange";
break;
case VacuumGripperDeviceStatus::kRed:
device_status = "Red";
break;
}
ostream << "{\"in_control_range\": " << vacuum_gripper_state.in_control_range
<< ", \"part_detached\": " << vacuum_gripper_state.part_detached
<< ", \"part_present\": " << vacuum_gripper_state.part_present << ", \"device_status\": "
<< "\"" << device_status << "\""
<< ", \"actual_power\": " << vacuum_gripper_state.actual_power
<< ", \"vacuum\": " << vacuum_gripper_state.vacuum
<< ", \"time\": " << vacuum_gripper_state.time.toSec() << "}";
return ostream;
}
} // namespace franka
<|endoftext|> |
<commit_before>/**
* This file is part of the Marble Virtual Globe.
*
* Copyright 2005-2007 Torsten Rahn <tackat@kde.org>
* Copyright 2007 Inge Wallin <ingwa@kde.org>
* Copyright 2008, 2009, 2010 Jens-Michael Hoffmann <jensmh@gmx.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "StackedTileLoader.h"
#include "GeoSceneDocument.h"
#include "GeoSceneGroup.h"
#include "GeoSceneHead.h"
#include "GeoSceneLayer.h"
#include "GeoSceneMap.h"
#include "GeoSceneSettings.h"
#include "GeoSceneTexture.h"
#include "HttpDownloadManager.h"
#include "MapThemeManager.h"
#include "MarbleDebug.h"
#include "MarbleDirs.h"
#include "MergedLayerDecorator.h"
#include "StackedTile.h"
#include "TextureTile.h"
#include "TileLoader.h"
#include "TileLoaderHelper.h"
#include "global.h"
#include <QtCore/QCache>
#include <QtCore/QDateTime>
#include <QtCore/QHash>
#include <QtGui/QImage>
#ifdef Q_CC_MSVC
# ifndef KDEWIN_MATH_H
long double log(int i) { return log((long double)i); }
# endif
#endif
namespace Marble
{
class StackedTileLoaderPrivate
{
public:
StackedTileLoaderPrivate( TileLoader *tileLoader, SunLocator *sunLocator )
: m_layerDecorator( tileLoader, sunLocator ),
m_tileLoader( tileLoader ),
m_maxTileLevel( 0 )
{
m_tileCache.setMaxCost( 20000 * 1024 ); // Cache size measured in bytes
}
void detectMaxTileLevel();
QVector<GeoSceneTexture const *>
findRelevantTextureLayers( TileId const & stackedTileId ) const;
MergedLayerDecorator m_layerDecorator;
TileLoader *m_tileLoader;
int m_maxTileLevel;
QVector<GeoSceneTexture const *> m_textureLayers;
QHash <TileId, StackedTile*> m_tilesOnDisplay;
QCache <TileId, StackedTile> m_tileCache;
};
StackedTileLoader::StackedTileLoader( TileLoader * const tileLoader,
SunLocator * const sunLocator )
: d( new StackedTileLoaderPrivate( tileLoader, sunLocator ) )
{
connect( d->m_tileLoader, SIGNAL( tileCompleted( TileId )),
SLOT( updateTile( TileId )));
}
StackedTileLoader::~StackedTileLoader()
{
flush();
d->m_tileCache.clear();
delete d;
}
void StackedTileLoader::setTextureLayers( QVector<GeoSceneTexture const *> & textureLayers )
{
mDebug() << "StackedTileLoader::setTextureLayers";
d->m_textureLayers = textureLayers;
d->m_tilesOnDisplay.clear();
d->m_tileCache.clear();
d->detectMaxTileLevel();
}
void StackedTileLoader::setShowTileId( bool show )
{
d->m_layerDecorator.setShowTileId( show );
}
int StackedTileLoader::tileColumnCount( int level ) const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
const int levelZeroColumns = d->m_textureLayers.at( 0 )->levelZeroColumns();
return TileLoaderHelper::levelToColumn( levelZeroColumns, level );
}
int StackedTileLoader::tileRowCount( int level ) const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
const int levelZeroRows = d->m_textureLayers.at( 0 )->levelZeroRows();
return TileLoaderHelper::levelToRow( levelZeroRows, level );
}
GeoSceneTexture::Projection StackedTileLoader::tileProjection() const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
return d->m_textureLayers.at( 0 )->projection();
}
QSize StackedTileLoader::tileSize() const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
return d->m_textureLayers.at( 0 )->tileSize();
}
void StackedTileLoader::resetTilehash()
{
QHash<TileId, StackedTile*>::const_iterator it = d->m_tilesOnDisplay.constBegin();
QHash<TileId, StackedTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; it != end; ++it ) {
it.value()->setUsed( false );
}
}
void StackedTileLoader::cleanupTilehash()
{
// Make sure that tiles which haven't been used during the last
// rendering of the map at all get removed from the tile hash.
QHashIterator<TileId, StackedTile*> it( d->m_tilesOnDisplay );
while ( it.hasNext() ) {
it.next();
if ( !it.value()->used() ) {
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
d->m_tilesOnDisplay.remove( it.key() );
}
}
}
void StackedTileLoader::flush()
{
// move all tiles from m_tilesOnDisplay into tile cache
QHash<TileId, StackedTile*>::const_iterator it = d->m_tilesOnDisplay.constBegin();
QHash<TileId, StackedTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; it != end; ++it ) {
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
}
d->m_tilesOnDisplay.clear();
}
StackedTile* StackedTileLoader::loadTile( TileId const & stackedTileId )
{
// check if the tile is in the hash
StackedTile * stackedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 );
if ( stackedTile ) {
return stackedTile;
}
// here ends the performance critical section of this method
mDebug() << "StackedTileLoader::loadTile" << stackedTileId.toString();
// the tile was not in the hash or has been removed because of expiration
// so check if it is in the cache
stackedTile = d->m_tileCache.take( stackedTileId );
if ( stackedTile ) {
// the tile was in the cache, but is it up to date?
d->m_tilesOnDisplay[ stackedTileId ] = stackedTile;
return stackedTile;
}
// tile (valid) has not been found in hash or cache, so load it from disk
// and place it in the hash from where it will get transferred to the cache
// mDebug() << "load Tile from Disk: " << stackedTileId.toString();
QVector<QSharedPointer<TextureTile> > tiles;
QVector<GeoSceneTexture const *> const textureLayers = d->findRelevantTextureLayers( stackedTileId );
QVector<GeoSceneTexture const *>::const_iterator pos = textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const textureLayer = *pos;
TileId const tileId( textureLayer->sourceDir(), stackedTileId.zoomLevel(),
stackedTileId.x(), stackedTileId.y() );
mDebug() << "StackedTileLoader::loadTile: tile" << textureLayer->sourceDir()
<< tileId.toString() << textureLayer->tileSize();
QSharedPointer<TextureTile> const tile = d->m_tileLoader->loadTile( tileId, DownloadBrowse );
if ( tile ) {
tiles.append( tile );
}
}
Q_ASSERT( !tiles.isEmpty() );
stackedTile = new StackedTile( stackedTileId, tiles );
d->m_tilesOnDisplay[ stackedTileId ] = stackedTile;
mergeDecorations( stackedTile );
return stackedTile;
}
void StackedTileLoader::downloadTile( TileId const & stackedTileId )
{
QVector<GeoSceneTexture const *> const textureLayers = d->findRelevantTextureLayers( stackedTileId );
QVector<GeoSceneTexture const *>::const_iterator pos = textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const textureLayer = *pos;
TileId const tileId( textureLayer->sourceDir(), stackedTileId.zoomLevel(),
stackedTileId.x(), stackedTileId.y() );
d->m_tileLoader->downloadTile( tileId );
}
}
quint64 StackedTileLoader::volatileCacheLimit() const
{
return d->m_tileCache.maxCost() / 1024;
}
void StackedTileLoader::reloadVisibleTiles()
{
foreach ( StackedTile * const displayedTile, d->m_tilesOnDisplay.values() ) {
Q_ASSERT( displayedTile != 0 );
foreach ( QSharedPointer<TextureTile> const & tile, *displayedTile->tiles() ) {
// it's debatable here, whether DownloadBulk or DownloadBrowse should be used
// but since "reload" or "refresh" seems to be a common action of a browser and it
// allows for more connections (in our model), use "DownloadBrowse"
d->m_tileLoader->reloadTile( tile, DownloadBrowse );
}
mergeDecorations( displayedTile );
}
emit tileUpdatesAvailable();
}
int StackedTileLoader::maximumTileLevel() const
{
return d->m_maxTileLevel;
}
void StackedTileLoaderPrivate::detectMaxTileLevel()
{
if ( m_textureLayers.isEmpty() ) {
m_maxTileLevel = -1;
return;
}
GeoSceneTexture const * const texture = m_textureLayers.at( 0 );
// if maximum tile level is configured in the DGML files,
// then use it, otherwise use old detection code.
if ( texture->maximumTileLevel() >= 0 ) {
m_maxTileLevel = texture->maximumTileLevel();
return;
}
int maximumTileLevel = -1;
QString tilepath = MarbleDirs::path( texture->themeStr() );
// mDebug() << "StackedTileLoader::maxPartialTileLevel tilepath" << tilepath;
QStringList leveldirs = QDir( tilepath ).entryList( QDir::AllDirs | QDir::NoSymLinks
| QDir::NoDotAndDotDot );
QStringList::const_iterator it = leveldirs.constBegin();
QStringList::const_iterator const end = leveldirs.constEnd();
for (; it != end; ++it ) {
bool ok = true;
const int value = (*it).toInt( &ok, 10 );
if ( ok && value > maximumTileLevel )
maximumTileLevel = value;
}
// mDebug() << "Detected maximum tile level that contains data: "
// << maxtilelevel;
m_maxTileLevel = maximumTileLevel + 1;
}
bool StackedTileLoader::baseTilesAvailable( GeoSceneLayer * layer )
{
if ( !layer ) return false;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );
const int levelZeroColumns = texture->levelZeroColumns();
const int levelZeroRows = texture->levelZeroRows();
bool noerr = true;
// Check whether the tiles from the lowest texture level are available
//
for ( int column = 0; noerr && column < levelZeroColumns; ++column ) {
for ( int row = 0; noerr && row < levelZeroRows; ++row ) {
const QString tilepath = MarbleDirs::path( texture->relativeTileFileName(
TileId( texture->sourceDir(), 0, column, row )));
noerr = QFile::exists( tilepath );
}
}
return noerr;
}
void StackedTileLoader::setVolatileCacheLimit( quint64 kiloBytes )
{
mDebug() << QString("Setting tile cache to %1 kilobytes.").arg( kiloBytes );
d->m_tileCache.setMaxCost( kiloBytes * 1024 );
}
void StackedTileLoader::updateTile( TileId const & stackedTileId )
{
d->detectMaxTileLevel();
StackedTile * const displayedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 );
if ( displayedTile ) {
mergeDecorations( displayedTile );
emit tileUpdateAvailable( stackedTileId );
}
else {
StackedTile * const cachedTile = d->m_tileCache.object( stackedTileId );
if ( cachedTile ) {
mergeDecorations( cachedTile );
emit tileUpdateAvailable( stackedTileId );
}
}
}
void StackedTileLoader::update()
{
mDebug() << "StackedTileLoader::update()";
flush(); // trigger a reload of all tiles that are currently in use
d->m_tileCache.clear(); // clear the tile cache in physical memory
emit tileUpdatesAvailable();
}
//
QVector<GeoSceneTexture const *>
StackedTileLoaderPrivate::findRelevantTextureLayers( TileId const & stackedTileId ) const
{
QVector<GeoSceneTexture const *> result;
QVector<GeoSceneTexture const *>::const_iterator pos = m_textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = m_textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const candidate = dynamic_cast<GeoSceneTexture const *>( *pos );
// check if layer is enabled. A layer is considered to be enabled if one of the
// following conditions is true:
// 1) it is the first layer
// 2) there are no settings available (group "Texture Layers" not defined in DGML)
// 3) the layer is configured and enabled in the settings
// also check, if layer provides tiles for the current level
if ( candidate
&& ( !candidate->hasMaximumTileLevel()
|| stackedTileId.zoomLevel() <= candidate->maximumTileLevel() ))
result.append( candidate );
}
return result;
}
void StackedTileLoader::mergeDecorations( StackedTile * const tile ) const
{
Q_ASSERT( tile != 0 );
Q_ASSERT( !tile->tiles()->isEmpty() );
Q_ASSERT( !d->m_textureLayers.isEmpty() );
// mDebug() << "MarbleModel::paintTile: " << "x: " << x << "y:" << y << "level: " << level
// << "requestTileUpdate" << requestTileUpdate;
tile->initResultTile();
d->m_layerDecorator.setInfo( tile->id() );
d->m_layerDecorator.setTile( tile->resultTile() );
d->m_layerDecorator.paint( "maps/" + d->m_textureLayers.at( 0 )->sourceDir() );
}
}
#include "StackedTileLoader.moc"
<commit_msg>only update displayed tiles<commit_after>/**
* This file is part of the Marble Virtual Globe.
*
* Copyright 2005-2007 Torsten Rahn <tackat@kde.org>
* Copyright 2007 Inge Wallin <ingwa@kde.org>
* Copyright 2008, 2009, 2010 Jens-Michael Hoffmann <jensmh@gmx.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "StackedTileLoader.h"
#include "GeoSceneDocument.h"
#include "GeoSceneGroup.h"
#include "GeoSceneHead.h"
#include "GeoSceneLayer.h"
#include "GeoSceneMap.h"
#include "GeoSceneSettings.h"
#include "GeoSceneTexture.h"
#include "HttpDownloadManager.h"
#include "MapThemeManager.h"
#include "MarbleDebug.h"
#include "MarbleDirs.h"
#include "MergedLayerDecorator.h"
#include "StackedTile.h"
#include "TextureTile.h"
#include "TileLoader.h"
#include "TileLoaderHelper.h"
#include "global.h"
#include <QtCore/QCache>
#include <QtCore/QDateTime>
#include <QtCore/QHash>
#include <QtGui/QImage>
#ifdef Q_CC_MSVC
# ifndef KDEWIN_MATH_H
long double log(int i) { return log((long double)i); }
# endif
#endif
namespace Marble
{
class StackedTileLoaderPrivate
{
public:
StackedTileLoaderPrivate( TileLoader *tileLoader, SunLocator *sunLocator )
: m_layerDecorator( tileLoader, sunLocator ),
m_tileLoader( tileLoader ),
m_maxTileLevel( 0 )
{
m_tileCache.setMaxCost( 20000 * 1024 ); // Cache size measured in bytes
}
void detectMaxTileLevel();
QVector<GeoSceneTexture const *>
findRelevantTextureLayers( TileId const & stackedTileId ) const;
MergedLayerDecorator m_layerDecorator;
TileLoader *m_tileLoader;
int m_maxTileLevel;
QVector<GeoSceneTexture const *> m_textureLayers;
QHash <TileId, StackedTile*> m_tilesOnDisplay;
QCache <TileId, StackedTile> m_tileCache;
};
StackedTileLoader::StackedTileLoader( TileLoader * const tileLoader,
SunLocator * const sunLocator )
: d( new StackedTileLoaderPrivate( tileLoader, sunLocator ) )
{
connect( d->m_tileLoader, SIGNAL( tileCompleted( TileId )),
SLOT( updateTile( TileId )));
}
StackedTileLoader::~StackedTileLoader()
{
flush();
d->m_tileCache.clear();
delete d;
}
void StackedTileLoader::setTextureLayers( QVector<GeoSceneTexture const *> & textureLayers )
{
mDebug() << "StackedTileLoader::setTextureLayers";
d->m_textureLayers = textureLayers;
d->m_tilesOnDisplay.clear();
d->m_tileCache.clear();
d->detectMaxTileLevel();
}
void StackedTileLoader::setShowTileId( bool show )
{
d->m_layerDecorator.setShowTileId( show );
}
int StackedTileLoader::tileColumnCount( int level ) const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
const int levelZeroColumns = d->m_textureLayers.at( 0 )->levelZeroColumns();
return TileLoaderHelper::levelToColumn( levelZeroColumns, level );
}
int StackedTileLoader::tileRowCount( int level ) const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
const int levelZeroRows = d->m_textureLayers.at( 0 )->levelZeroRows();
return TileLoaderHelper::levelToRow( levelZeroRows, level );
}
GeoSceneTexture::Projection StackedTileLoader::tileProjection() const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
return d->m_textureLayers.at( 0 )->projection();
}
QSize StackedTileLoader::tileSize() const
{
Q_ASSERT( !d->m_textureLayers.isEmpty() );
return d->m_textureLayers.at( 0 )->tileSize();
}
void StackedTileLoader::resetTilehash()
{
QHash<TileId, StackedTile*>::const_iterator it = d->m_tilesOnDisplay.constBegin();
QHash<TileId, StackedTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; it != end; ++it ) {
it.value()->setUsed( false );
}
}
void StackedTileLoader::cleanupTilehash()
{
// Make sure that tiles which haven't been used during the last
// rendering of the map at all get removed from the tile hash.
QHashIterator<TileId, StackedTile*> it( d->m_tilesOnDisplay );
while ( it.hasNext() ) {
it.next();
if ( !it.value()->used() ) {
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
d->m_tilesOnDisplay.remove( it.key() );
}
}
}
void StackedTileLoader::flush()
{
// move all tiles from m_tilesOnDisplay into tile cache
QHash<TileId, StackedTile*>::const_iterator it = d->m_tilesOnDisplay.constBegin();
QHash<TileId, StackedTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; it != end; ++it ) {
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
}
d->m_tilesOnDisplay.clear();
}
StackedTile* StackedTileLoader::loadTile( TileId const & stackedTileId )
{
// check if the tile is in the hash
StackedTile * stackedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 );
if ( stackedTile ) {
return stackedTile;
}
// here ends the performance critical section of this method
mDebug() << "StackedTileLoader::loadTile" << stackedTileId.toString();
// the tile was not in the hash or has been removed because of expiration
// so check if it is in the cache
stackedTile = d->m_tileCache.take( stackedTileId );
if ( stackedTile ) {
// the tile was in the cache, but is it up to date?
d->m_tilesOnDisplay[ stackedTileId ] = stackedTile;
return stackedTile;
}
// tile (valid) has not been found in hash or cache, so load it from disk
// and place it in the hash from where it will get transferred to the cache
// mDebug() << "load Tile from Disk: " << stackedTileId.toString();
QVector<QSharedPointer<TextureTile> > tiles;
QVector<GeoSceneTexture const *> const textureLayers = d->findRelevantTextureLayers( stackedTileId );
QVector<GeoSceneTexture const *>::const_iterator pos = textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const textureLayer = *pos;
TileId const tileId( textureLayer->sourceDir(), stackedTileId.zoomLevel(),
stackedTileId.x(), stackedTileId.y() );
mDebug() << "StackedTileLoader::loadTile: tile" << textureLayer->sourceDir()
<< tileId.toString() << textureLayer->tileSize();
QSharedPointer<TextureTile> const tile = d->m_tileLoader->loadTile( tileId, DownloadBrowse );
if ( tile ) {
tiles.append( tile );
}
}
Q_ASSERT( !tiles.isEmpty() );
stackedTile = new StackedTile( stackedTileId, tiles );
d->m_tilesOnDisplay[ stackedTileId ] = stackedTile;
mergeDecorations( stackedTile );
return stackedTile;
}
void StackedTileLoader::downloadTile( TileId const & stackedTileId )
{
QVector<GeoSceneTexture const *> const textureLayers = d->findRelevantTextureLayers( stackedTileId );
QVector<GeoSceneTexture const *>::const_iterator pos = textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const textureLayer = *pos;
TileId const tileId( textureLayer->sourceDir(), stackedTileId.zoomLevel(),
stackedTileId.x(), stackedTileId.y() );
d->m_tileLoader->downloadTile( tileId );
}
}
quint64 StackedTileLoader::volatileCacheLimit() const
{
return d->m_tileCache.maxCost() / 1024;
}
void StackedTileLoader::reloadVisibleTiles()
{
foreach ( StackedTile * const displayedTile, d->m_tilesOnDisplay.values() ) {
Q_ASSERT( displayedTile != 0 );
foreach ( QSharedPointer<TextureTile> const & tile, *displayedTile->tiles() ) {
// it's debatable here, whether DownloadBulk or DownloadBrowse should be used
// but since "reload" or "refresh" seems to be a common action of a browser and it
// allows for more connections (in our model), use "DownloadBrowse"
d->m_tileLoader->reloadTile( tile, DownloadBrowse );
}
mergeDecorations( displayedTile );
}
emit tileUpdatesAvailable();
}
int StackedTileLoader::maximumTileLevel() const
{
return d->m_maxTileLevel;
}
void StackedTileLoaderPrivate::detectMaxTileLevel()
{
if ( m_textureLayers.isEmpty() ) {
m_maxTileLevel = -1;
return;
}
GeoSceneTexture const * const texture = m_textureLayers.at( 0 );
// if maximum tile level is configured in the DGML files,
// then use it, otherwise use old detection code.
if ( texture->maximumTileLevel() >= 0 ) {
m_maxTileLevel = texture->maximumTileLevel();
return;
}
int maximumTileLevel = -1;
QString tilepath = MarbleDirs::path( texture->themeStr() );
// mDebug() << "StackedTileLoader::maxPartialTileLevel tilepath" << tilepath;
QStringList leveldirs = QDir( tilepath ).entryList( QDir::AllDirs | QDir::NoSymLinks
| QDir::NoDotAndDotDot );
QStringList::const_iterator it = leveldirs.constBegin();
QStringList::const_iterator const end = leveldirs.constEnd();
for (; it != end; ++it ) {
bool ok = true;
const int value = (*it).toInt( &ok, 10 );
if ( ok && value > maximumTileLevel )
maximumTileLevel = value;
}
// mDebug() << "Detected maximum tile level that contains data: "
// << maxtilelevel;
m_maxTileLevel = maximumTileLevel + 1;
}
bool StackedTileLoader::baseTilesAvailable( GeoSceneLayer * layer )
{
if ( !layer ) return false;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );
const int levelZeroColumns = texture->levelZeroColumns();
const int levelZeroRows = texture->levelZeroRows();
bool noerr = true;
// Check whether the tiles from the lowest texture level are available
//
for ( int column = 0; noerr && column < levelZeroColumns; ++column ) {
for ( int row = 0; noerr && row < levelZeroRows; ++row ) {
const QString tilepath = MarbleDirs::path( texture->relativeTileFileName(
TileId( texture->sourceDir(), 0, column, row )));
noerr = QFile::exists( tilepath );
}
}
return noerr;
}
void StackedTileLoader::setVolatileCacheLimit( quint64 kiloBytes )
{
mDebug() << QString("Setting tile cache to %1 kilobytes.").arg( kiloBytes );
d->m_tileCache.setMaxCost( kiloBytes * 1024 );
}
void StackedTileLoader::updateTile( TileId const & stackedTileId )
{
d->detectMaxTileLevel();
StackedTile * const displayedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 );
if ( displayedTile ) {
mergeDecorations( displayedTile );
emit tileUpdateAvailable( stackedTileId );
return;
}
d->m_tileCache.remove( stackedTileId );
}
void StackedTileLoader::update()
{
mDebug() << "StackedTileLoader::update()";
flush(); // trigger a reload of all tiles that are currently in use
d->m_tileCache.clear(); // clear the tile cache in physical memory
emit tileUpdatesAvailable();
}
//
QVector<GeoSceneTexture const *>
StackedTileLoaderPrivate::findRelevantTextureLayers( TileId const & stackedTileId ) const
{
QVector<GeoSceneTexture const *> result;
QVector<GeoSceneTexture const *>::const_iterator pos = m_textureLayers.constBegin();
QVector<GeoSceneTexture const *>::const_iterator const end = m_textureLayers.constEnd();
for (; pos != end; ++pos ) {
GeoSceneTexture const * const candidate = dynamic_cast<GeoSceneTexture const *>( *pos );
// check if layer is enabled. A layer is considered to be enabled if one of the
// following conditions is true:
// 1) it is the first layer
// 2) there are no settings available (group "Texture Layers" not defined in DGML)
// 3) the layer is configured and enabled in the settings
// also check, if layer provides tiles for the current level
if ( candidate
&& ( !candidate->hasMaximumTileLevel()
|| stackedTileId.zoomLevel() <= candidate->maximumTileLevel() ))
result.append( candidate );
}
return result;
}
void StackedTileLoader::mergeDecorations( StackedTile * const tile ) const
{
Q_ASSERT( tile != 0 );
Q_ASSERT( !tile->tiles()->isEmpty() );
Q_ASSERT( !d->m_textureLayers.isEmpty() );
// mDebug() << "MarbleModel::paintTile: " << "x: " << x << "y:" << y << "level: " << level
// << "requestTileUpdate" << requestTileUpdate;
tile->initResultTile();
d->m_layerDecorator.setInfo( tile->id() );
d->m_layerDecorator.setTile( tile->resultTile() );
d->m_layerDecorator.paint( "maps/" + d->m_textureLayers.at( 0 )->sourceDir() );
}
}
#include "StackedTileLoader.moc"
<|endoftext|> |
<commit_before>/* libwpd
* Copyright (C) 2002 William Lachance (wrlach@gmail.com)
* Copyright (C) 2002 Marc Maurer (uwog@uwog.net)
* Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include "WP6ParagraphGroup.h"
#include "libwpd_internal.h"
#include "WPXFileStructure.h"
WP6ParagraphGroup::WP6ParagraphGroup(WPXInputStream *input) :
WP6VariableLengthGroup(),
m_subGroupData(NULL)
{
_read(input);
}
WP6ParagraphGroup::~WP6ParagraphGroup()
{
if (m_subGroupData)
delete(m_subGroupData);
}
void WP6ParagraphGroup::_readContents(WPXInputStream *input)
{
switch (getSubGroup())
{
case WP6_PARAGRAPH_GROUP_LINE_SPACING:
m_subGroupData = new WP6ParagraphGroup_LineSpacingSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_TAB_SET:
m_subGroupData = new WP6ParagraphGroup_TabSetSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_JUSTIFICATION:
m_subGroupData = new WP6ParagraphGroup_JustificationModeSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_SPACING_AFTER_PARAGRAPH:
m_subGroupData = new WP6ParagraphGroup_SpacingAfterParagraphSubGroup(input, getSizeNonDeletable());
break;
case WP6_PARAGRAPH_GROUP_INDENT_FIRST_LINE_OF_PARAGRAPH:
m_subGroupData = new WP6ParagraphGroup_IndentFirstLineSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_LEFT_MARGIN_ADJUSTMENT:
m_subGroupData = new WP6ParagraphGroup_LeftMarginAdjustmentSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_RIGHT_MARGIN_ADJUSTMENT:
m_subGroupData = new WP6ParagraphGroup_RightMarginAdjustmentSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_OUTLINE_DEFINE:
m_subGroupData = new WP6ParagraphGroup_OutlineDefineSubGroup(input);
break;
}
}
void WP6ParagraphGroup::parse(WP6Listener *listener)
{
WPD_DEBUG_MSG(("WordPerfect: handling a Paragraph group\n"));
if (m_subGroupData)
m_subGroupData->parse(listener, getNumPrefixIDs(), getPrefixIDs());
}
WP6ParagraphGroup_LineSpacingSubGroup::WP6ParagraphGroup_LineSpacingSubGroup(WPXInputStream *input)
{
uint32_t lineSpacing = readU32(input);
int16_t lineSpacingIntegerPart = (int16_t)((lineSpacing & 0xFFFF0000) >> 16);
float lineSpacingFractionalPart = (float)(lineSpacing & 0xFFFF)/(float)0xFFFF;
WPD_DEBUG_MSG(("WordPerfect: line spacing integer part: %i fractional part: %f (original value: %i)\n",
lineSpacingIntegerPart, lineSpacingFractionalPart, lineSpacing));
m_lineSpacing = lineSpacingIntegerPart + lineSpacingFractionalPart;
}
void WP6ParagraphGroup_LineSpacingSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing a line spacing change of: %f\n", m_lineSpacing));
listener->lineSpacingChange(m_lineSpacing);
}
WP6ParagraphGroup_TabSetSubGroup::WP6ParagraphGroup_TabSetSubGroup(WPXInputStream *input) :
m_isRelative(false),
m_tabAdjustValue(0.0f)
{
uint8_t tmp_definition = readU8(input);
uint16_t tmp_tabAdjustValue = readU16(input);
if (tmp_definition == 0)
{
m_isRelative = false;
m_tabAdjustValue = 0.0f;
}
else
{
m_isRelative = true;
m_tabAdjustValue = (float)((double)tmp_tabAdjustValue/(double)WPX_NUM_WPUS_PER_INCH);
}
uint8_t tmp_repetitionCount = 0;
WPXTabStop tmp_tabStop;
uint8_t tmp_numTabStops = readU8(input);
bool tmp_usePreWP9LeaderMethod;
uint8_t tmp_tabType;
int i;
for (i = 0; i < tmp_numTabStops; i++)
{
tmp_tabType = readU8(input);
if ((tmp_tabType & 0x80) != 0)
{
tmp_repetitionCount = (tmp_tabType & 0x7F);
}
else
{
switch (tmp_tabType & 0x0F) //alignment bits
{
case 0x00:
tmp_tabStop.m_alignment = LEFT;
break;
case 0x01:
tmp_tabStop.m_alignment = CENTER;
break;
case 0x02:
tmp_tabStop.m_alignment = RIGHT;
break;
case 0x03:
tmp_tabStop.m_alignment = DECIMAL;
break;
case 0x04:
tmp_tabStop.m_alignment = BAR;
break;
default: // should not happen, maybe corruption
tmp_tabStop.m_alignment = LEFT;
break;
}
tmp_tabStop.m_leaderNumSpaces = 0;
if ((tmp_tabType & 0x10) == 0) // no leader character
{
tmp_tabStop.m_leaderCharacter = '\0';
tmp_usePreWP9LeaderMethod = false;
}
else
{
switch ((tmp_tabType & 0x60) >> 5) // leader character type
{
case 0: // pre-WP9 leader method
tmp_tabStop.m_leaderCharacter = '.';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = true;
break;
case 1: // dot leader
tmp_tabStop.m_leaderCharacter = '.';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = false;
break;
case 2: // hyphen leader
tmp_tabStop.m_leaderCharacter = '-';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = false;
break;
case 3: // underscore leader
tmp_tabStop.m_leaderCharacter = '_';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = false;
break;
}
}
}
uint16_t tmp_tabPosition = readU16(input);
if (tmp_repetitionCount == 0)
{
if (tmp_tabPosition != 0xFFFF)
{
tmp_tabStop.m_position = (float)((double)tmp_tabPosition/(double)WPX_NUM_WPUS_PER_INCH) -
m_tabAdjustValue;
m_tabStops.push_back(tmp_tabStop);
m_usePreWP9LeaderMethods.push_back(tmp_usePreWP9LeaderMethod);
}
}
else
{
for (int k=0; k<tmp_repetitionCount; k++)
{
tmp_tabStop.m_position += (float)((double)tmp_tabPosition/(double)WPX_NUM_WPUS_PER_INCH);
m_tabStops.push_back(tmp_tabStop);
m_usePreWP9LeaderMethods.push_back(tmp_usePreWP9LeaderMethod);
}
tmp_repetitionCount = 0;
}
}
}
WP6ParagraphGroup_TabSetSubGroup::~WP6ParagraphGroup_TabSetSubGroup()
{
}
void WP6ParagraphGroup_TabSetSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
#ifdef DEBUG
WPD_DEBUG_MSG(("Parsing Tab Set (isRelative: %s, positions: ", (m_isRelative?"true":"false")));
for(std::vector<WPXTabStop>::const_iterator i = m_tabStops.begin(); i != m_tabStops.end(); i++)
{
WPD_DEBUG_MSG((" %.4f", (*i).m_position));
}
WPD_DEBUG_MSG((")\n"));
#endif
listener->defineTabStops(m_isRelative, m_tabStops, m_usePreWP9LeaderMethods);
}
WP6ParagraphGroup_IndentFirstLineSubGroup::WP6ParagraphGroup_IndentFirstLineSubGroup(WPXInputStream *input)
{
m_firstLineOffset = (int16_t)readU16(input);
WPD_DEBUG_MSG(("WordPerfect: indent first line: %i\n", m_firstLineOffset));
}
void WP6ParagraphGroup_IndentFirstLineSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing first line indent change of: %i\n", m_firstLineOffset));
listener->indentFirstLineChange(m_firstLineOffset);
}
WP6ParagraphGroup_LeftMarginAdjustmentSubGroup::WP6ParagraphGroup_LeftMarginAdjustmentSubGroup(WPXInputStream *input)
{
m_leftMargin = (int16_t)readU16(input);
WPD_DEBUG_MSG(("WordPerfect: left margin adjustment: %i\n", m_leftMargin));
}
void WP6ParagraphGroup_LeftMarginAdjustmentSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing left margin adjustment change of: %i\n", m_leftMargin));
listener->paragraphMarginChange(WPX_LEFT, m_leftMargin);
}
WP6ParagraphGroup_RightMarginAdjustmentSubGroup::WP6ParagraphGroup_RightMarginAdjustmentSubGroup(WPXInputStream *input)
{
m_rightMargin = (int16_t)readU16(input);
WPD_DEBUG_MSG(("WordPerfect: right margin adjustment: %i\n", m_rightMargin));
}
void WP6ParagraphGroup_RightMarginAdjustmentSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const */* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing right margin adjustment change of: %i\n", m_rightMargin));
listener->paragraphMarginChange(WPX_RIGHT, m_rightMargin);
}
WP6ParagraphGroup_JustificationModeSubGroup::WP6ParagraphGroup_JustificationModeSubGroup(WPXInputStream *input)
{
m_justification = readU8(input);
}
void WP6ParagraphGroup_JustificationModeSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
listener->justificationChange(m_justification);
}
WP6ParagraphGroup_SpacingAfterParagraphSubGroup::WP6ParagraphGroup_SpacingAfterParagraphSubGroup(WPXInputStream *input, const uint16_t sizeNonDeletable)
{
m_sizeNonDeletable = sizeNonDeletable;
m_spacingAfterParagraphAbsolute = 0.0f;
m_spacingAfterParagraphRelative = 1.0f;
uint32_t spacingAfterRelative = readU32(input);
int16_t spacingAfterIntegerPart = (int16_t)((spacingAfterRelative & 0xFFFF0000) >> 16);
float spacingAfterFractionalPart = (float)(spacingAfterRelative & 0xFFFF)/(float)0xFFFF;
WPD_DEBUG_MSG(("WordPerfect: spacing after paragraph relative integer part: %i fractional part: %f (original value: %i)\n",
spacingAfterIntegerPart, spacingAfterFractionalPart, spacingAfterRelative));
m_spacingAfterParagraphRelative = spacingAfterIntegerPart + spacingAfterFractionalPart;
if (m_sizeNonDeletable == (uint16_t)0x06) // Let us use the optional information that is in WPUs
{
uint16_t spacingAfterAbsolute = readU16(input);
m_spacingAfterParagraphAbsolute = (float)((double)spacingAfterAbsolute / (double)WPX_NUM_WPUS_PER_INCH);
WPD_DEBUG_MSG(("WordPerfect: spacing after paragraph absolute: %i\n", spacingAfterAbsolute));
}
}
void WP6ParagraphGroup_SpacingAfterParagraphSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing a change of spacing after paragraph: relative %f, absolute %f\n",
m_spacingAfterParagraphRelative, m_spacingAfterParagraphAbsolute));
listener->spacingAfterParagraphChange(m_spacingAfterParagraphRelative, m_spacingAfterParagraphAbsolute);
}
WP6ParagraphGroup_OutlineDefineSubGroup::WP6ParagraphGroup_OutlineDefineSubGroup(WPXInputStream *input)
{
// NB: this is identical to WP6OutlineStylePacket::_readContents!!
m_outlineHash = readU16(input);
for (unsigned int i=0; i<WP6_NUM_LIST_LEVELS; i++)
m_numberingMethods[i] = readU8(input);
m_tabBehaviourFlag = readU8(input);
WPD_DEBUG_MSG(("WordPerfect: Read Outline Style Packet (, outlineHash: %i, tab behaviour flag: %i)\n", (int) m_outlineHash, (int) m_tabBehaviourFlag));
WPD_DEBUG_MSG(("WordPerfect: Read Outline Style Packet (m_numberingMethods: %i %i %i %i %i %i %i %i)\n",
m_numberingMethods[0], m_numberingMethods[1], m_numberingMethods[2], m_numberingMethods[3],
m_numberingMethods[4], m_numberingMethods[5], m_numberingMethods[6], m_numberingMethods[7]));
}
void WP6ParagraphGroup_OutlineDefineSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
uint16_t const * /* prefixIDs */) const
{
listener->updateOutlineDefinition(paragraphGroup, m_outlineHash, m_numberingMethods, m_tabBehaviourFlag);
}
<commit_msg>question of personal preference<commit_after>/* libwpd
* Copyright (C) 2002 William Lachance (wrlach@gmail.com)
* Copyright (C) 2002 Marc Maurer (uwog@uwog.net)
* Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include "WP6ParagraphGroup.h"
#include "libwpd_internal.h"
#include "WPXFileStructure.h"
WP6ParagraphGroup::WP6ParagraphGroup(WPXInputStream *input) :
WP6VariableLengthGroup(),
m_subGroupData(NULL)
{
_read(input);
}
WP6ParagraphGroup::~WP6ParagraphGroup()
{
if (m_subGroupData)
delete(m_subGroupData);
}
void WP6ParagraphGroup::_readContents(WPXInputStream *input)
{
switch (getSubGroup())
{
case WP6_PARAGRAPH_GROUP_LINE_SPACING:
m_subGroupData = new WP6ParagraphGroup_LineSpacingSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_TAB_SET:
m_subGroupData = new WP6ParagraphGroup_TabSetSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_JUSTIFICATION:
m_subGroupData = new WP6ParagraphGroup_JustificationModeSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_SPACING_AFTER_PARAGRAPH:
m_subGroupData = new WP6ParagraphGroup_SpacingAfterParagraphSubGroup(input, getSizeNonDeletable());
break;
case WP6_PARAGRAPH_GROUP_INDENT_FIRST_LINE_OF_PARAGRAPH:
m_subGroupData = new WP6ParagraphGroup_IndentFirstLineSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_LEFT_MARGIN_ADJUSTMENT:
m_subGroupData = new WP6ParagraphGroup_LeftMarginAdjustmentSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_RIGHT_MARGIN_ADJUSTMENT:
m_subGroupData = new WP6ParagraphGroup_RightMarginAdjustmentSubGroup(input);
break;
case WP6_PARAGRAPH_GROUP_OUTLINE_DEFINE:
m_subGroupData = new WP6ParagraphGroup_OutlineDefineSubGroup(input);
break;
}
}
void WP6ParagraphGroup::parse(WP6Listener *listener)
{
WPD_DEBUG_MSG(("WordPerfect: handling a Paragraph group\n"));
if (m_subGroupData)
m_subGroupData->parse(listener, getNumPrefixIDs(), getPrefixIDs());
}
WP6ParagraphGroup_LineSpacingSubGroup::WP6ParagraphGroup_LineSpacingSubGroup(WPXInputStream *input)
{
uint32_t lineSpacing = readU32(input);
int16_t lineSpacingIntegerPart = (int16_t)((lineSpacing & 0xFFFF0000) >> 16);
float lineSpacingFractionalPart = (float)(lineSpacing & 0xFFFF)/(float)0xFFFF;
WPD_DEBUG_MSG(("WordPerfect: line spacing integer part: %i fractional part: %f (original value: %i)\n",
lineSpacingIntegerPart, lineSpacingFractionalPart, lineSpacing));
m_lineSpacing = lineSpacingIntegerPart + lineSpacingFractionalPart;
}
void WP6ParagraphGroup_LineSpacingSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing a line spacing change of: %f\n", m_lineSpacing));
listener->lineSpacingChange(m_lineSpacing);
}
WP6ParagraphGroup_TabSetSubGroup::WP6ParagraphGroup_TabSetSubGroup(WPXInputStream *input) :
m_isRelative(false),
m_tabAdjustValue(0.0f)
{
uint8_t tmp_definition = readU8(input);
uint16_t tmp_tabAdjustValue = readU16(input);
if (tmp_definition == 0)
{
m_isRelative = false;
m_tabAdjustValue = 0.0f;
}
else
{
m_isRelative = true;
m_tabAdjustValue = (float)((double)tmp_tabAdjustValue/(double)WPX_NUM_WPUS_PER_INCH);
}
uint8_t tmp_repetitionCount = 0;
WPXTabStop tmp_tabStop;
uint8_t tmp_numTabStops = readU8(input);
bool tmp_usePreWP9LeaderMethod;
uint8_t tmp_tabType;
int i;
for (i = 0; i < tmp_numTabStops; i++)
{
tmp_tabType = readU8(input);
if ((tmp_tabType & 0x80) != 0)
{
tmp_repetitionCount = (tmp_tabType & 0x7F);
}
else
{
switch (tmp_tabType & 0x0F) //alignment bits
{
case 0x00:
tmp_tabStop.m_alignment = LEFT;
break;
case 0x01:
tmp_tabStop.m_alignment = CENTER;
break;
case 0x02:
tmp_tabStop.m_alignment = RIGHT;
break;
case 0x03:
tmp_tabStop.m_alignment = DECIMAL;
break;
case 0x04:
tmp_tabStop.m_alignment = BAR;
break;
default: // should not happen, maybe corruption
tmp_tabStop.m_alignment = LEFT;
break;
}
tmp_tabStop.m_leaderNumSpaces = 0;
if ((tmp_tabType & 0x10) == 0) // no leader character
{
tmp_tabStop.m_leaderCharacter = '\0';
tmp_usePreWP9LeaderMethod = false;
}
else
{
switch ((tmp_tabType & 0x60) >> 5) // leader character type
{
case 0: // pre-WP9 leader method
tmp_tabStop.m_leaderCharacter = '.';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = true;
break;
case 1: // dot leader
tmp_tabStop.m_leaderCharacter = '.';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = false;
break;
case 2: // hyphen leader
tmp_tabStop.m_leaderCharacter = '-';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = false;
break;
case 3: // underscore leader
tmp_tabStop.m_leaderCharacter = '_';
tmp_tabStop.m_leaderNumSpaces = 0;
tmp_usePreWP9LeaderMethod = false;
break;
}
}
}
uint16_t tmp_tabPosition = readU16(input);
if (tmp_repetitionCount == 0)
{
if (tmp_tabPosition != 0xFFFF)
{
tmp_tabStop.m_position = (float)((double)tmp_tabPosition/(double)WPX_NUM_WPUS_PER_INCH) -
m_tabAdjustValue;
m_tabStops.push_back(tmp_tabStop);
m_usePreWP9LeaderMethods.push_back(tmp_usePreWP9LeaderMethod);
}
}
else
{
for (int k=0; k<tmp_repetitionCount; k++)
{
tmp_tabStop.m_position += (float)((double)tmp_tabPosition/(double)WPX_NUM_WPUS_PER_INCH);
m_tabStops.push_back(tmp_tabStop);
m_usePreWP9LeaderMethods.push_back(tmp_usePreWP9LeaderMethod);
}
tmp_repetitionCount = 0;
}
}
}
WP6ParagraphGroup_TabSetSubGroup::~WP6ParagraphGroup_TabSetSubGroup()
{
}
void WP6ParagraphGroup_TabSetSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
#ifdef DEBUG
WPD_DEBUG_MSG(("Parsing Tab Set (isRelative: %s, positions: ", (m_isRelative?"true":"false")));
for(std::vector<WPXTabStop>::const_iterator i = m_tabStops.begin(); i != m_tabStops.end(); i++)
{
WPD_DEBUG_MSG((" %.4f", (*i).m_position));
}
WPD_DEBUG_MSG((")\n"));
#endif
listener->defineTabStops(m_isRelative, m_tabStops, m_usePreWP9LeaderMethods);
}
WP6ParagraphGroup_IndentFirstLineSubGroup::WP6ParagraphGroup_IndentFirstLineSubGroup(WPXInputStream *input)
{
m_firstLineOffset = (int16_t)readU16(input);
WPD_DEBUG_MSG(("WordPerfect: indent first line: %i\n", m_firstLineOffset));
}
void WP6ParagraphGroup_IndentFirstLineSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing first line indent change of: %i\n", m_firstLineOffset));
listener->indentFirstLineChange(m_firstLineOffset);
}
WP6ParagraphGroup_LeftMarginAdjustmentSubGroup::WP6ParagraphGroup_LeftMarginAdjustmentSubGroup(WPXInputStream *input)
{
m_leftMargin = (int16_t)readU16(input);
WPD_DEBUG_MSG(("WordPerfect: left margin adjustment: %i\n", m_leftMargin));
}
void WP6ParagraphGroup_LeftMarginAdjustmentSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing left margin adjustment change of: %i\n", m_leftMargin));
listener->paragraphMarginChange(WPX_LEFT, m_leftMargin);
}
WP6ParagraphGroup_RightMarginAdjustmentSubGroup::WP6ParagraphGroup_RightMarginAdjustmentSubGroup(WPXInputStream *input)
{
m_rightMargin = (int16_t)readU16(input);
WPD_DEBUG_MSG(("WordPerfect: right margin adjustment: %i\n", m_rightMargin));
}
void WP6ParagraphGroup_RightMarginAdjustmentSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing right margin adjustment change of: %i\n", m_rightMargin));
listener->paragraphMarginChange(WPX_RIGHT, m_rightMargin);
}
WP6ParagraphGroup_JustificationModeSubGroup::WP6ParagraphGroup_JustificationModeSubGroup(WPXInputStream *input)
{
m_justification = readU8(input);
}
void WP6ParagraphGroup_JustificationModeSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
listener->justificationChange(m_justification);
}
WP6ParagraphGroup_SpacingAfterParagraphSubGroup::WP6ParagraphGroup_SpacingAfterParagraphSubGroup(WPXInputStream *input, const uint16_t sizeNonDeletable)
{
m_sizeNonDeletable = sizeNonDeletable;
m_spacingAfterParagraphAbsolute = 0.0f;
m_spacingAfterParagraphRelative = 1.0f;
uint32_t spacingAfterRelative = readU32(input);
int16_t spacingAfterIntegerPart = (int16_t)((spacingAfterRelative & 0xFFFF0000) >> 16);
float spacingAfterFractionalPart = (float)(spacingAfterRelative & 0xFFFF)/(float)0xFFFF;
WPD_DEBUG_MSG(("WordPerfect: spacing after paragraph relative integer part: %i fractional part: %f (original value: %i)\n",
spacingAfterIntegerPart, spacingAfterFractionalPart, spacingAfterRelative));
m_spacingAfterParagraphRelative = spacingAfterIntegerPart + spacingAfterFractionalPart;
if (m_sizeNonDeletable == (uint16_t)0x06) // Let us use the optional information that is in WPUs
{
uint16_t spacingAfterAbsolute = readU16(input);
m_spacingAfterParagraphAbsolute = (float)((double)spacingAfterAbsolute / (double)WPX_NUM_WPUS_PER_INCH);
WPD_DEBUG_MSG(("WordPerfect: spacing after paragraph absolute: %i\n", spacingAfterAbsolute));
}
}
void WP6ParagraphGroup_SpacingAfterParagraphSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
WPD_DEBUG_MSG(("WordPerfect: parsing a change of spacing after paragraph: relative %f, absolute %f\n",
m_spacingAfterParagraphRelative, m_spacingAfterParagraphAbsolute));
listener->spacingAfterParagraphChange(m_spacingAfterParagraphRelative, m_spacingAfterParagraphAbsolute);
}
WP6ParagraphGroup_OutlineDefineSubGroup::WP6ParagraphGroup_OutlineDefineSubGroup(WPXInputStream *input)
{
// NB: this is identical to WP6OutlineStylePacket::_readContents!!
m_outlineHash = readU16(input);
for (unsigned int i=0; i<WP6_NUM_LIST_LEVELS; i++)
m_numberingMethods[i] = readU8(input);
m_tabBehaviourFlag = readU8(input);
WPD_DEBUG_MSG(("WordPerfect: Read Outline Style Packet (, outlineHash: %i, tab behaviour flag: %i)\n", (int) m_outlineHash, (int) m_tabBehaviourFlag));
WPD_DEBUG_MSG(("WordPerfect: Read Outline Style Packet (m_numberingMethods: %i %i %i %i %i %i %i %i)\n",
m_numberingMethods[0], m_numberingMethods[1], m_numberingMethods[2], m_numberingMethods[3],
m_numberingMethods[4], m_numberingMethods[5], m_numberingMethods[6], m_numberingMethods[7]));
}
void WP6ParagraphGroup_OutlineDefineSubGroup::parse(WP6Listener *listener, const uint8_t /* numPrefixIDs */,
const uint16_t * /* prefixIDs */) const
{
listener->updateOutlineDefinition(paragraphGroup, m_outlineHash, m_numberingMethods, m_tabBehaviourFlag);
}
<|endoftext|> |
<commit_before>#include "CategoryClassifyMiningTask.h"
#include "CategoryClassifyTable.h"
#include <document-manager/DocumentManager.h>
#include <la-manager/KNlpWrapper.h>
#include <knlp/doc_naive_bayes.h>
#include <util/ustring/UString.h>
#include <glog/logging.h>
#include <boost/filesystem/path.hpp>
using namespace sf1r;
namespace bfs = boost::filesystem;
namespace
{
const std::string kOriginalCategoryPropName("OriginalCategory");
const std::string kSourcePropName("Source");
const std::string kClassifyCategoryValueBook("R>文娱>书籍杂志");
void getDocPropValue(
const Document& doc,
const std::string& propName,
std::string& propValue)
{
izenelib::util::UString ustr;
doc.getProperty(propName, ustr);
ustr.convertString(propValue, izenelib::util::UString::UTF_8);
}
}
CategoryClassifyMiningTask::CategoryClassifyMiningTask(
DocumentManager& documentManager,
CategoryClassifyTable& classifyTable,
const std::string& targetCategoryPropName)
: documentManager_(documentManager)
, classifyTable_(classifyTable)
, targetCategoryPropName_(targetCategoryPropName)
, startDocId_(0)
{
}
bool CategoryClassifyMiningTask::buildDocument(docid_t docID, const Document& doc)
{
std::string title;
getDocPropValue(doc, classifyTable_.propName(), title);
if (title.empty())
return true;
std::string classifyCategory;
std::string targetCategory;
bool isRule = true;
if (ruleByTargetCategory_(doc, targetCategory, classifyCategory) ||
ruleByOriginalCategory_(doc, classifyCategory) ||
ruleBySource_(doc, targetCategory, classifyCategory) ||
classifyByTitle_(title, classifyCategory, isRule))
{
classifyTable_.setCategory(docID, classifyCategory, isRule);
}
return true;
}
bool CategoryClassifyMiningTask::ruleByTargetCategory_(
const Document& doc,
std::string& targetCategory,
std::string& classifyCategory)
{
if (!targetCategoryPropName_.empty())
{
getDocPropValue(doc, targetCategoryPropName_, targetCategory);
if (targetCategory.find("图书音像") != std::string::npos)
{
classifyCategory = kClassifyCategoryValueBook;
return true;
}
}
return false;
}
bool CategoryClassifyMiningTask::ruleByOriginalCategory_(
const Document& doc,
std::string& classifyCategory)
{
std::string originalCategory;
getDocPropValue(doc, kOriginalCategoryPropName, originalCategory);
if (!originalCategory.empty())
{
KNlpWrapper* knlpWrapper = KNlpWrapper::get();
classifyCategory = knlpWrapper->mapFromOriginalCategory(originalCategory);
}
return !classifyCategory.empty();
}
bool CategoryClassifyMiningTask::ruleBySource_(
const Document& doc,
const std::string& targetCategory,
std::string& classifyCategory)
{
if (!targetCategory.empty())
return false;
std::string source;
getDocPropValue(doc, kSourcePropName, source);
if (source == "文轩网官网")
{
classifyCategory = kClassifyCategoryValueBook;
return true;
}
return false;
}
bool CategoryClassifyMiningTask::classifyByTitle_(
const std::string& title,
std::string& classifyCategory,
bool& isRule)
{
try
{
KNlpWrapper* knlpWrapper = KNlpWrapper::get();
std::string cleanTitle = knlpWrapper->cleanGarbage(title);
KNlpWrapper::string_t titleKStr(cleanTitle);
KNlpWrapper::token_score_list_t tokenScores;
knlpWrapper->fmmTokenize(titleKStr, tokenScores);
KNlpWrapper::string_t classifyKStr = knlpWrapper->classifyToBestCategory(tokenScores);
classifyCategory = classifyKStr.get_bytes("utf-8");
isRule = false;
return true;
}
catch(std::exception& ex)
{
LOG(ERROR) << "exception: " << ex.what()
<< ", title: " << title;
return false;
}
}
bool CategoryClassifyMiningTask::preProcess()
{
startDocId_ = classifyTable_.docIdNum();
const docid_t endDocId = documentManager_.getMaxDocId();
LOG(INFO) << "category classify mining task"
<< ", start docid: " << startDocId_
<< ", end docid: " << endDocId;
if (startDocId_ > endDocId)
return false;
classifyTable_.resize(endDocId + 1);
return true;
}
bool CategoryClassifyMiningTask::postProcess()
{
if (!classifyTable_.flush())
{
LOG(ERROR) << "failed in CategoryClassifyTable::flush()";
return false;
}
return true;
}
<commit_msg>In CategoryClassifyMiningTask get doc property value, change from UString to string.<commit_after>#include "CategoryClassifyMiningTask.h"
#include "CategoryClassifyTable.h"
#include <document-manager/DocumentManager.h>
#include <la-manager/KNlpWrapper.h>
#include <knlp/doc_naive_bayes.h>
#include <glog/logging.h>
#include <boost/filesystem/path.hpp>
using namespace sf1r;
namespace bfs = boost::filesystem;
namespace
{
const std::string kOriginalCategoryPropName("Category");
const std::string kSourcePropName("Source");
const std::string kClassifyCategoryValueBook("R>文娱>书籍杂志");
void getDocPropValue(
const Document& doc,
const std::string& propName,
std::string& propValue)
{
doc.getProperty(propName, propValue);
}
}
CategoryClassifyMiningTask::CategoryClassifyMiningTask(
DocumentManager& documentManager,
CategoryClassifyTable& classifyTable,
const std::string& targetCategoryPropName)
: documentManager_(documentManager)
, classifyTable_(classifyTable)
, targetCategoryPropName_(targetCategoryPropName)
, startDocId_(0)
{
}
bool CategoryClassifyMiningTask::buildDocument(docid_t docID, const Document& doc)
{
std::string title;
getDocPropValue(doc, classifyTable_.propName(), title);
if (title.empty())
return true;
std::string classifyCategory;
std::string targetCategory;
bool isRule = true;
if (ruleByTargetCategory_(doc, targetCategory, classifyCategory) ||
ruleByOriginalCategory_(doc, classifyCategory) ||
ruleBySource_(doc, targetCategory, classifyCategory) ||
classifyByTitle_(title, classifyCategory, isRule))
{
classifyTable_.setCategory(docID, classifyCategory, isRule);
}
return true;
}
bool CategoryClassifyMiningTask::ruleByTargetCategory_(
const Document& doc,
std::string& targetCategory,
std::string& classifyCategory)
{
if (!targetCategoryPropName_.empty())
{
getDocPropValue(doc, targetCategoryPropName_, targetCategory);
if (targetCategory.find("图书音像") != std::string::npos)
{
classifyCategory = kClassifyCategoryValueBook;
return true;
}
}
return false;
}
bool CategoryClassifyMiningTask::ruleByOriginalCategory_(
const Document& doc,
std::string& classifyCategory)
{
std::string originalCategory;
getDocPropValue(doc, kOriginalCategoryPropName, originalCategory);
if (!originalCategory.empty())
{
KNlpWrapper* knlpWrapper = KNlpWrapper::get();
classifyCategory = knlpWrapper->mapFromOriginalCategory(originalCategory);
}
return !classifyCategory.empty();
}
bool CategoryClassifyMiningTask::ruleBySource_(
const Document& doc,
const std::string& targetCategory,
std::string& classifyCategory)
{
if (!targetCategory.empty())
return false;
std::string source;
getDocPropValue(doc, kSourcePropName, source);
if (source == "文轩网官网")
{
classifyCategory = kClassifyCategoryValueBook;
return true;
}
return false;
}
bool CategoryClassifyMiningTask::classifyByTitle_(
const std::string& title,
std::string& classifyCategory,
bool& isRule)
{
try
{
KNlpWrapper* knlpWrapper = KNlpWrapper::get();
std::string cleanTitle = knlpWrapper->cleanGarbage(title);
KNlpWrapper::string_t titleKStr(cleanTitle);
KNlpWrapper::token_score_list_t tokenScores;
knlpWrapper->fmmTokenize(titleKStr, tokenScores);
KNlpWrapper::string_t classifyKStr = knlpWrapper->classifyToBestCategory(tokenScores);
classifyCategory = classifyKStr.get_bytes("utf-8");
isRule = false;
return true;
}
catch(std::exception& ex)
{
LOG(ERROR) << "exception: " << ex.what()
<< ", title: " << title;
return false;
}
}
bool CategoryClassifyMiningTask::preProcess()
{
startDocId_ = classifyTable_.docIdNum();
const docid_t endDocId = documentManager_.getMaxDocId();
LOG(INFO) << "category classify mining task"
<< ", start docid: " << startDocId_
<< ", end docid: " << endDocId;
if (startDocId_ > endDocId)
return false;
classifyTable_.resize(endDocId + 1);
return true;
}
bool CategoryClassifyMiningTask::postProcess()
{
if (!classifyTable_.flush())
{
LOG(ERROR) << "failed in CategoryClassifyTable::flush()";
return false;
}
return true;
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/Rpc.h>
#include <vw/Plate/IndexService.h>
#include <vw/Core/Stopwatch.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Core/Log.h>
#include <signal.h>
#include <boost/format.hpp>
#include <google/protobuf/descriptor.h>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace vw::platefile;
using namespace vw;
// ------------------------------ SIGNAL HANDLER -------------------------------
volatile bool process_messages = true;
volatile bool force_sync = false;
void sig_unexpected_shutdown(int sig_num) {
signal(sig_num, SIG_IGN);
process_messages = false;
signal(sig_num, sig_unexpected_shutdown);
}
void sig_sync(int sig_num) {
signal(sig_num, SIG_IGN);
force_sync = true;
signal(sig_num, sig_sync);
}
struct Options {
Url url;
std::string root;
float sync_interval;
bool debug;
bool help;
};
VW_DEFINE_EXCEPTION(Usage, Exception);
void process_args(Options& opt, int argc, char *argv[]) {
po::options_description general_options("Runs a master index manager.\n\nGeneral Options:");
general_options.add_options()
("url", po::value(&opt.url), "Url to listen on")
("debug", po::bool_switch(&opt.debug)->default_value(false), "Allow server to die.")
("help,h", po::bool_switch(&opt.help)->default_value(false), "Display this help message")
("sync-interval,s", po::value(&opt.sync_interval)->default_value(60.),
"Specify the time interval (in minutes) for automatically synchronizing the index to disk.");
po::options_description hidden_options("");
hidden_options.add_options()
("root-directory", po::value(&opt.root));
po::options_description options("Allowed Options");
options.add(general_options).add(hidden_options);
po::positional_options_description p;
p.add("root-directory", -1);
po::variables_map vm;
po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
po::notify( vm );
std::ostringstream usage;
usage << "Usage: " << argv[0] << " --url <url> root_directory" << std::endl << std::endl;
usage << general_options << std::endl;
if(opt.help)
vw_throw(Usage() << usage.str());
if( vm.count("root-directory") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nError: must specify a root directory that contains plate files!");
}
if ( vm.count("url") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nMust specify a url to listen on");
}
}
int main(int argc, char** argv) {
Options opt;
try {
process_args(opt, argc, argv);
} catch (const Usage& u) {
std::cerr << u.what() << std::endl;
::exit(EXIT_FAILURE);
}
// Install Unix Signal Handlers. These will help us to gracefully
// recover and salvage the index under most unexpected error
// conditions.
signal(SIGINT, sig_unexpected_shutdown);
signal(SIGUSR1, sig_sync);
// Start the server task in another thread
RpcServer<IndexServiceImpl> server(opt.url, new IndexServiceImpl(opt.root));
server.set_debug(opt.debug);
vw_out(InfoMessage) << "Starting index server\n\n";
uint64 sync_interval_us = uint64(opt.sync_interval * 60000000);
uint64 t0 = Stopwatch::microtime(), t1;
uint64 next_sync = t0 + sync_interval_us;
size_t win = 0, lose = 0, draw = 0, total = 0;
boost::format status("qps[%7.1f] total[%9u] server_err[%9u] client_err[%9u]\r");
while(process_messages) {
bool should_sync = force_sync || (Stopwatch::microtime() >= next_sync);
if (should_sync) {
vw_out(InfoMessage) << "\nStarting sync to disk. (" << (force_sync ? "auto" : "manual") << ")\n";
uint64 s0 = Stopwatch::microtime();
server.impl()->sync();
uint64 s1 = Stopwatch::microtime();
next_sync = s1 + sync_interval_us;
vw_out(InfoMessage) << "Sync complete (took " << float(s1-s0) / 1e6 << " seconds).\n";
force_sync = false;
}
t1 = Stopwatch::microtime();
size_t win_dt, lose_dt, draw_dt, total_dt;
{
ThreadMap::Locked stats = server.stats();
win_dt = stats.get("msgs");
lose_dt = stats.get("server_error");
draw_dt = stats.get("client_error");
stats.clear();
}
total_dt = win_dt + lose_dt + draw_dt;
win += win_dt;
lose += lose_dt;
draw += draw_dt;
total += total_dt;
float dt = float(t1 - t0) / 1e6f;
t0 = t1;
vw_out(InfoMessage)
<< status % (float(total_dt)/dt) % total % lose % draw
<< std::flush;
Thread::sleep_ms(500);
}
vw_out(InfoMessage) << "\nShutting down the index service safely.\n";
server.stop();
server.impl()->sync();
return 0;
}
<commit_msg>fix sync message logic (it was inverted)<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/Rpc.h>
#include <vw/Plate/IndexService.h>
#include <vw/Core/Stopwatch.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Core/Log.h>
#include <signal.h>
#include <boost/format.hpp>
#include <google/protobuf/descriptor.h>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace vw::platefile;
using namespace vw;
// ------------------------------ SIGNAL HANDLER -------------------------------
volatile bool process_messages = true;
volatile bool force_sync = false;
void sig_unexpected_shutdown(int sig_num) {
signal(sig_num, SIG_IGN);
process_messages = false;
signal(sig_num, sig_unexpected_shutdown);
}
void sig_sync(int sig_num) {
signal(sig_num, SIG_IGN);
force_sync = true;
signal(sig_num, sig_sync);
}
struct Options {
Url url;
std::string root;
float sync_interval;
bool debug;
bool help;
};
VW_DEFINE_EXCEPTION(Usage, Exception);
void process_args(Options& opt, int argc, char *argv[]) {
po::options_description general_options("Runs a master index manager.\n\nGeneral Options:");
general_options.add_options()
("url", po::value(&opt.url), "Url to listen on")
("debug", po::bool_switch(&opt.debug)->default_value(false), "Allow server to die.")
("help,h", po::bool_switch(&opt.help)->default_value(false), "Display this help message")
("sync-interval,s", po::value(&opt.sync_interval)->default_value(60.),
"Specify the time interval (in minutes) for automatically synchronizing the index to disk.");
po::options_description hidden_options("");
hidden_options.add_options()
("root-directory", po::value(&opt.root));
po::options_description options("Allowed Options");
options.add(general_options).add(hidden_options);
po::positional_options_description p;
p.add("root-directory", -1);
po::variables_map vm;
po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
po::notify( vm );
std::ostringstream usage;
usage << "Usage: " << argv[0] << " --url <url> root_directory" << std::endl << std::endl;
usage << general_options << std::endl;
if(opt.help)
vw_throw(Usage() << usage.str());
if( vm.count("root-directory") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nError: must specify a root directory that contains plate files!");
}
if ( vm.count("url") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nMust specify a url to listen on");
}
}
int main(int argc, char** argv) {
Options opt;
try {
process_args(opt, argc, argv);
} catch (const Usage& u) {
std::cerr << u.what() << std::endl;
::exit(EXIT_FAILURE);
}
// Install Unix Signal Handlers. These will help us to gracefully
// recover and salvage the index under most unexpected error
// conditions.
signal(SIGINT, sig_unexpected_shutdown);
signal(SIGUSR1, sig_sync);
// Start the server task in another thread
RpcServer<IndexServiceImpl> server(opt.url, new IndexServiceImpl(opt.root));
server.set_debug(opt.debug);
vw_out(InfoMessage) << "Starting index server\n\n";
uint64 sync_interval_us = uint64(opt.sync_interval * 60000000);
uint64 t0 = Stopwatch::microtime(), t1;
uint64 next_sync = t0 + sync_interval_us;
size_t win = 0, lose = 0, draw = 0, total = 0;
boost::format status("qps[%7.1f] total[%9u] server_err[%9u] client_err[%9u]\r");
while(process_messages) {
bool should_sync = force_sync || (Stopwatch::microtime() >= next_sync);
if (should_sync) {
vw_out(InfoMessage) << "\nStarting sync to disk. (" << (force_sync ? "manual" : "auto") << ")\n";
uint64 s0 = Stopwatch::microtime();
server.impl()->sync();
uint64 s1 = Stopwatch::microtime();
next_sync = s1 + sync_interval_us;
vw_out(InfoMessage) << "Sync complete (took " << float(s1-s0) / 1e6 << " seconds).\n";
force_sync = false;
}
t1 = Stopwatch::microtime();
size_t win_dt, lose_dt, draw_dt, total_dt;
{
ThreadMap::Locked stats = server.stats();
win_dt = stats.get("msgs");
lose_dt = stats.get("server_error");
draw_dt = stats.get("client_error");
stats.clear();
}
total_dt = win_dt + lose_dt + draw_dt;
win += win_dt;
lose += lose_dt;
draw += draw_dt;
total += total_dt;
float dt = float(t1 - t0) / 1e6f;
t0 = t1;
vw_out(InfoMessage)
<< status % (float(total_dt)/dt) % total % lose % draw
<< std::flush;
Thread::sleep_ms(500);
}
vw_out(InfoMessage) << "\nShutting down the index service safely.\n";
server.stop();
server.impl()->sync();
return 0;
}
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* 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 <utility>
#include "types/type.h"
#include "types/map.h"
#include "compiler/compiler.h"
namespace clever {
/**
* Void Map::__assign__(Map)
*/
CLEVER_METHOD(Map::do_assign) {
CLEVER_THIS()->copy(CLEVER_ARG(0));
}
/**
* Int Map<K, V [,C]>::size()
*/
CLEVER_METHOD(Map::size) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
CLEVER_RETURN_INT(map->m_map.size());
}
/**
* Bool Map<K, V [,C]>::isEmpty()
*/
CLEVER_METHOD(Map::isEmpty) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
CLEVER_RETURN_BOOL(map->m_map.empty());
}
/**
* Void Map<K, V [,C]>::insert(K, V)
*/
CLEVER_METHOD(Map::insert) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
map->m_map.insert(std::make_pair(CLEVER_ARG(0), CLEVER_ARG(1)));
CLEVER_ARG(0)->addRef();
CLEVER_ARG(1)->addRef();
}
/**
* Void Map<K, V [,C]>::clear()
*/
CLEVER_METHOD(Map::clear) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
MapValue::iterator it = map->m_map.begin(),
end = map->m_map.end();
while (it != end) {
it->first->delRef();
it->second->delRef();
++it;
}
map->m_map.clear();
}
/**
* String Map<K, V [,C]>::toString()
*/
CLEVER_METHOD(Map::toString) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
MapValue::iterator it = map->m_map.begin(),
end = map->m_map.end();
std::string ret = "[", sep = ", ";
if (it != end) {
ret += it->first->toString() + " => "
+ it->second->toString();
while (++it != end) {
ret += sep + it->first->toString() + " => "
+ it->second->toString();
}
}
ret += "]";
CLEVER_RETURN_STR(CSTRING(ret));
}
/**
* Bool Map<K, V [, C]>::hasKey(K)
*/
CLEVER_METHOD(Map::hasKey) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
MapValue::iterator it = map->m_map.begin(),
end = map->m_map.end();
bool ret = false;
if (it != end) {
if (it->first->toString() == CLEVER_ARG(0)->toString()) {
ret = true;
}
while (++it != end && !ret) {
if (it->first->toString() == CLEVER_ARG(0)->toString()) {
ret = true;
}
}
}
CLEVER_RETURN_BOOL(ret);
}
/**
* Map type initializator
*/
void Map::init() {
/**
* Check if we are in our "virtual" Map type
*/
if (CLEVER_TPL_ARG(0) == NULL) {
return;
}
addMethod((new Method("insert", (MethodPtr)&Map::insert, CLEVER_VOID, false))
->addArg("key", CLEVER_TPL_ARG(0))
->addArg("value", CLEVER_TPL_ARG(1))
);
addMethod(new Method("toString", (MethodPtr)&Map::toString, CLEVER_STR));
addMethod(new Method("size", (MethodPtr)&Map::size, CLEVER_INT));
addMethod(new Method("isEmpty", (MethodPtr)&Map::isEmpty, CLEVER_BOOL));
addMethod(new Method("clear", (MethodPtr)&Map::clear, CLEVER_VOID));
addMethod((new Method("hasKey", (MethodPtr)&Map::hasKey, CLEVER_BOOL))
->addArg("key", CLEVER_TPL_ARG(0))
);
}
DataValue* Map::allocateValue() const {
if (this->getNumArgs() == 2) {
TypeVector tv(2, getTypeArg(0));
return new MapValue(getTypeArg(0)
->getMethod(CSTRING(CLEVER_OPERATOR_LESS), &tv));
}
TypeVector tv(2, getTypeArg(0));
return new MapValue(getTypeArg(2)
->getMethod(CSTRING("compare"), &tv), new Value(getTypeArg(2)));
}
} // clever
<commit_msg>Making Map<>::hasKey() to be O(log n)<commit_after>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* 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 <utility>
#include "types/type.h"
#include "types/map.h"
#include "compiler/compiler.h"
namespace clever {
/**
* Void Map::__assign__(Map)
*/
CLEVER_METHOD(Map::do_assign) {
CLEVER_THIS()->copy(CLEVER_ARG(0));
}
/**
* Int Map<K, V [,C]>::size()
*/
CLEVER_METHOD(Map::size) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
CLEVER_RETURN_INT(map->m_map.size());
}
/**
* Bool Map<K, V [,C]>::isEmpty()
*/
CLEVER_METHOD(Map::isEmpty) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
CLEVER_RETURN_BOOL(map->m_map.empty());
}
/**
* Void Map<K, V [,C]>::insert(K, V)
*/
CLEVER_METHOD(Map::insert) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
map->m_map.insert(std::make_pair(CLEVER_ARG(0), CLEVER_ARG(1)));
CLEVER_ARG(0)->addRef();
CLEVER_ARG(1)->addRef();
}
/**
* Void Map<K, V [,C]>::clear()
*/
CLEVER_METHOD(Map::clear) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
MapValue::iterator it = map->m_map.begin(),
end = map->m_map.end();
while (it != end) {
it->first->delRef();
it->second->delRef();
++it;
}
map->m_map.clear();
}
/**
* String Map<K, V [,C]>::toString()
*/
CLEVER_METHOD(Map::toString) {
MapValue* map = CLEVER_GET_VALUE(MapValue*, value);
MapValue::iterator it = map->m_map.begin(),
end = map->m_map.end();
std::string ret = "[", sep = ", ";
if (it != end) {
ret += it->first->toString() + " => "
+ it->second->toString();
while (++it != end) {
ret += sep + it->first->toString() + " => "
+ it->second->toString();
}
}
ret += "]";
CLEVER_RETURN_STR(CSTRING(ret));
}
/**
* Bool Map<K, V [, C]>::hasKey(K)
*/
CLEVER_METHOD(Map::hasKey) {
MapValue::ValueType& map = CLEVER_GET_VALUE(MapValue*, value)->getMap();
Value* search = CLEVER_ARG(0);
MapValue::Iterator it = map.find(search);
CLEVER_RETURN_BOOL(it != map.end());
}
/**
* Map type initializator
*/
void Map::init() {
/**
* Check if we are in our "virtual" Map type
*/
if (CLEVER_TPL_ARG(0) == NULL) {
return;
}
addMethod((new Method("insert", (MethodPtr)&Map::insert, CLEVER_VOID, false))
->addArg("key", CLEVER_TPL_ARG(0))
->addArg("value", CLEVER_TPL_ARG(1))
);
addMethod(new Method("toString", (MethodPtr)&Map::toString, CLEVER_STR));
addMethod(new Method("size", (MethodPtr)&Map::size, CLEVER_INT));
addMethod(new Method("isEmpty", (MethodPtr)&Map::isEmpty, CLEVER_BOOL));
addMethod(new Method("clear", (MethodPtr)&Map::clear, CLEVER_VOID));
addMethod((new Method("hasKey", (MethodPtr)&Map::hasKey, CLEVER_BOOL))
->addArg("key", CLEVER_TPL_ARG(0))
);
}
DataValue* Map::allocateValue() const {
if (this->getNumArgs() == 2) {
TypeVector tv(2, getTypeArg(0));
return new MapValue(getTypeArg(0)
->getMethod(CSTRING(CLEVER_OPERATOR_LESS), &tv));
}
TypeVector tv(2, getTypeArg(0));
return new MapValue(getTypeArg(2)
->getMethod(CSTRING("compare"), &tv), new Value(getTypeArg(2)));
}
} // clever
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
const auto WINDOW_WIDTH = 800;
const auto WINDOW_HEIGHT = 600;
const auto WINDOW_TITLE = "GL Cook Book - Window Creation";
int main(int argc, char const *argv[])
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
auto window = glfwCreateWindow(
WINDOW_WIDTH,
WINDOW_HEIGHT,
WINDOW_TITLE,
nullptr,
nullptr);
glfwMakeContextCurrent(window);
// Give access to modern GL functions
glewExperimental = GL_TRUE;
glewInit();
// Sync the rendering window with GLFW window
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
while (! glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}<commit_msg>Pressing esc key exits GLFW window in window_creation.<commit_after>#include <GL/glew.h>
#include <GLFW/glfw3.h>
const auto WINDOW_WIDTH = 800;
const auto WINDOW_HEIGHT = 600;
const auto WINDOW_TITLE = "GL Cook Book - Window Creation";
void onKeyChange(GLFWwindow* window, int key, int scancode, int action, int mode);
int main(int argc, char const *argv[])
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
auto window = glfwCreateWindow(
WINDOW_WIDTH,
WINDOW_HEIGHT,
WINDOW_TITLE,
nullptr,
nullptr);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, onKeyChange);
// Give access to modern GL functions
glewExperimental = GL_TRUE;
glewInit();
// Sync the rendering window with GLFW window
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
while (! glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
void onKeyChange(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}<|endoftext|> |
<commit_before>/*
* WebSocket.cpp - Websocket Implementation - works on most browsers and Mobile Phones (but notably Not on IE8)
*
* Created: 3/30/2014 9:57:39 PM
*
* Aritech Alarm Panel Arduino Internet Enabled Keypad - CS350 - CD34 - CD72 - CD91 and more
*
* For Arduino (UNO or Leonardo) with added Ethernet Shield
*
* See Circuit Diagram for wiring instructions
*
* Author: Ozmo
*
* See: http://www.boards.ie/vbulletin/showthread.php?p=88215184
*
*/
#include "sha1.h"
#include "Base64.h"
#include "RKP.h" //for nKeyToSend
#include "LOG.h"
#include "websocket.h"
#ifdef AtmelStudio
//Other modules
#include <SPI.cpp>
#include <Ethernet.cpp>
#include <EthernetClient.cpp>
#include <EthernetServer.cpp>
#include <utility\socket.cpp>
#include <utility\w5100.cpp>
#else
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <util.h>
#endif
//Workaround if needed for http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734
#ifdef PROGMEM
#undef PROGMEM
#define PROGMEM __attribute__((section(".progmem.data")))
#endif
//--Sockets
//use this as password - pick random port - set code tamper on alarm also.
EthernetServer ethServer(IP_P);
//EthernetServer ethServerHTML(80);
EthernetClient ethClient;
//"*" will be replaced with button
char htmlSite[] PROGMEM=
"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'>"
"<html><head><title>Castle</title>"
"<meta name='viewport' content='width=320, initial-scale=1.2, user-scalable=no'>"
"<style>.long{height: 64px;} button{height: 35px;width: 35px;}</style>"
"<script src='http://goo.gl/m3GB3M' type='text/javascript'></script>"
"</head><body>"
"<div style='border: 5px solid black; width: 180px;'> <div id=msg1 style='float:left'></div><div id=msg2 style='float:right'></div></div>"
"<table>"
"<tr><td><button>1</button></td><td><button>2</button></td><td><button>3</button></td><td rowspan=2><button class=long>Y</button></td></tr>"
"<tr><td><button>4</button></td><td><button>5</button></td><td><button>6</button></td></tr>"
"<tr><td><button>7</button></td><td><button>8</button></td><td><button>9</button></td><td rowspan=2><button class=long>N</button></td></tr>"
"<tr><td><button>*</button></td><td><button>0</button></td><td><button>#</button></td></tr>"
"</table>"
"<script>var ws;$(document).ready(function(){"
"try{"
"ws = new WebSocket('ws://'+location.hostname+':8383/sock');"
"ws.onmessage = function (evt) {var d=evt.data.split('|');$('#msg1').text(d[0]);$('#msg2').text(d[1]);};"
"ws.onerror = function (evt) {$('#msg').append('ERR:' + evt.data);};"
"ws.onclose = function (evt) {$('#msg').text('Closed');};"
"ws.onopen = function () { };"
"} catch (ex) {alert(ex.message);}"
"$(document).keypress(function (e) {ws.send(e.which);});"
"$(':button').click(function (e) { ws.send(e.target.innerText.charCodeAt(0));});"
"});</script></body></html>";
void WebSocket::EtherPoll()
{
// Should be called for each loop.
EthernetClient cli;
if (cli = ethServer.available())
{
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
//LogLn(F("browser req"));
if (cli == true)
{
if (ethClient != cli)
{//New connection
//Secrisk
ethClient = cli;
WebSocket_doHandshake();
}
else
{//Existing connection
if (WebSocket_getFrame() == false)
{//Request to end comms (rarely happens)
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
//Got bad frame, disconnect
Log(F("Disconnect{"));
while(ethClient.available()>0)
ethClient.read();
ethClient.flush();
ethClient.stop();
}
}
}
}
/* if (cli = ethServerHTML.available())
{
//Log(cli.available());
if (cli == true)
SendHTMLSite();
}
*/
}
void WebSocket::SendHTMLSite(/*EthernetClient& cli*/)
{
//Log(F("ConnectWWW{"));
// while(ethClient.available()>0)
// Log((char)cli.read());
//LogLn(F("}"));
ethClient.println(F("HTTP/1.0 200 OK")); //
ethClient.println(F("Content-Type: text/html"));
ethClient.println(F("Connnection: close"));
ethClient.println();
char* p = &htmlSite[0];
for(int n=0;n<2000;n++)
{
char c = pgm_read_byte(p++);
if (c==0) break;
//Can use tokens to compress the HTML a bit
//if (c=='*')
// ethClient.print(F("button"));
//else
ethClient.print(c);
if (n%100==0)
RKPClass::loop_PanelMon(); //most important we poll this when doing other stuff or RKP will loose data
}
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
// close the connection so browser gets data
ethClient.flush();
//delay(1);
ethClient.stop();
LogLn("Sent Page");
}
// Create a Websocket server
void WebSocket::WebSocket_EtherInit( IPAddress ip, IPAddress gateway )
{
//IPAddress ip( 192, 168, 1 , 205); //Give the device a unique IP
//IPAddress gateway( 192, 168, 1, 1 ); //Gateway (the Router)
IPAddress subnet( 255, 255, 255, 0 ); //typically dont need change
// this sequence must be unique on your lan
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x59, 0x67 }; //typically dont need change
//Start Ethernet
Ethernet.begin(mac, ip, gateway, gateway, subnet);
ethServer.begin();
//ethServerHTML.begin();
Log(F("server is at ")); LogLn(Ethernet.localIP());
delay(150); // Settle time
}
//Send something to connected browser
bool WebSocket::WebSocket_send(char* data, byte length)
{
if (!ethClient.connected())
{
LogLn(F("No Client."));
return false;
}
//int length = strlen(data);
ethClient.write(0x81);// string type
if (length > 125) {
ethClient.write(126);
ethClient.write((uint8_t) (length >> 8));
ethClient.write((uint8_t) (length && 0xFF));
}
else
ethClient.write((uint8_t) length);
for (int i=0; i<length; ++i)
ethClient.write(data[i]);
//LogLn(F("Sent OK."));
return true;
}
void WebSocket::WebSocket_doHandshake()
{
LogLn("HS");
char htmlline[128]; //TODO: there are 3 buffers used - htmlline, key and sha - maybe could merge them
char key[80];
bool hasKey = false;
bool bReqWebPage = false;
byte counter = 0;
while(ethClient.available()>0)
{//Read each line
byte bite = ethClient.read();
//Log(bite);
htmlline[counter++] = bite;
if (counter > 127)
{
LogLn(F("HandShake Overflow{"));
while(ethClient.available()>0)
LogHex(ethClient.read());
LogLn(F("}"));
//htmlline[127] = 0;
//LogHex(htmlline);
counter=0;
continue;
}
if (bite == '\n')
{ // Parse the line
htmlline[counter - 2] = 0; // Terminate string before CRLF
bool bFound = (strstr_P(htmlline, PSTR("Sec-WebSocket-Key:")) != NULL);
if (bFound)
{
hasKey = true;
strtok(htmlline, " ");
strcpy(key, strtok(NULL, " ")); //TODO: Not safe - need specify max 80 limit
}
if (strstr_P(htmlline, PSTR("GET / HTTP")) != NULL)
{
LogLn(F("Page Req"));
bReqWebPage=true;
}
counter = 0; // Start saving new header string
//Each Line - check if there is any comms to do
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
}
}
//Log("Got header: ");LogHex((byte*)htmlline,counter);
if (hasKey)
{
LogLn(F("WS Req"));
strcat_P(key, PSTR("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); // Magic Number GUID
Sha1.init();
Sha1.print(key);
uint8_t* hash = Sha1.result();
base64_encode(htmlline, (char*)hash, 20); //reuse htmlline buffer
ethClient.print(F("HTTP/1.1 101 Switching Protocols\r\n"));
ethClient.print(F("Upgrade: websocket\r\n"));
ethClient.print(F("Connection: Upgrade\r\n"));
ethClient.print(F("Sec-WebSocket-Accept: "));
ethClient.print(htmlline); //eg. VoNhf1LMVVTziHWxjiajVem5DB4=
ethClient.print(F("\r\n\r\n"));
LogLn(F("Connected"));
//Send any display we might have
RKPClass::bScreenHasUpdated = true; //RKPClass::SendDisplayToBrowser();
}
else if (bReqWebPage)
{// Nope, Not a websocket request - send the main webpage
//LogLn(F("WebPageReq"));
SendHTMLSite();
}
else
{
ethClient.println(F("HTTP/1.0 404 File Not Found")); //
ethClient.println(F("Content-Type: text/html"));
ethClient.println(F("Connnection: close"));
ethClient.println();
//delay(1);
ethClient.stop();
}
return;
}
struct Frame {
bool isMasked;
bool isFinal;
byte opcode;
byte mask[4];
byte length;
char data[64+1];
} frame;
byte WebSocket::ReadNext()
{
byte bite = ethClient.read();
//LogHex(bite);
return bite;
}
bool WebSocket::WebSocket_getFrame()
{
// Get opcode
byte bite = ReadNext(); if (bite==0xFF) return false;
frame.opcode = bite & 0xf; // Opcode
frame.isFinal = bite & 0x80; // Final frame?
// Determine length (only accept <= 64 for now)
bite = ReadNext(); if (bite==0xFF) return false;
frame.length = bite & 0x7f; // Length of payload
if (frame.length >= 64)
{//Unlikely to happen
Log(F("Frame Too Big")); LogLn(bite);
return false;
}
// Client should always send mask, but check just to be sure
frame.isMasked = bite & 0x80;
if (frame.isMasked) {
frame.mask[0] = ReadNext();
frame.mask[1] = ReadNext();
frame.mask[2] = ReadNext();
frame.mask[3] = ReadNext();
}
// Get message bytes and unmask them if necessary
int i = 0;
for (; i < frame.length; i++)
{
bite = ReadNext();
if (frame.isMasked)
frame.data[i] = bite ^ frame.mask[i % 4];
else
frame.data[i] = bite;
}
frame.data[i]=0;
// Frame complete!
if (!frame.isFinal)
{ // We don't handle fragments! Close and disconnect.
LogLn(F("Unsurp"));
return false; //RejectBroswerMsg();
}
if (frame.opcode== 0x01)
{// Txt frame
Log(F("Data: ")); //Got Data
LogLn(frame.data);
RKPClass::PushKey(atoi(frame.data));
return true;
}
if (frame.opcode== 0x08)
{
// Close frame. Answer with close and terminate tcp connection
LogLn(F("Close")); //Close frame
ethClient.write((uint8_t) 0x08);
return false;
}
// Unexpected. Ignore?
LogLn(F("Ex.")); //Unhandled frame ignored
return false;
}
<commit_msg>Update WebSocket.cpp<commit_after>/*
* WebSocket.cpp - Websocket Implementation - works on most browsers and Mobile Phones (but notably Not on IE8)
*
* Created: 3/30/2014 9:57:39 PM
*
* Aritech Alarm Panel Arduino Internet Enabled Keypad - CS350 - CD34 - CD72 - CD91 and more
*
* For Arduino (UNO or Leonardo) with added Ethernet Shield
*
* See Circuit Diagram for wiring instructions
*
* Author: Ozmo
*
* See: http://www.boards.ie/vbulletin/showthread.php?p=88215184
*
*/
#include "sha1.h"
#include "Base64.h"
#include "RKP.h" //for nKeyToSend
#include "LOG.h"
#include "websocket.h"
#ifdef AtmelStudio
//Other modules
#include <SPI.cpp>
#include <Ethernet.cpp>
#include <EthernetClient.cpp>
#include <EthernetServer.cpp>
#include <utility\socket.cpp>
#include <utility\w5100.cpp>
#else
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <util.h>
#endif
//Workaround if needed for http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734
#ifdef PROGMEM
#undef PROGMEM
#define PROGMEM __attribute__((section(".progmem.data")))
#endif
//--Sockets
//use this as password - pick random port - set code tamper on alarm also.
EthernetServer ethServer(IP_P);
//EthernetServer ethServerHTML(80);
EthernetClient ethClient;
//"*" will be replaced with button
char htmlSite[] PROGMEM=
"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'>"
"<html><head><title>Castle</title>"
"<meta name='viewport' content='width=320, initial-scale=1.2, user-scalable=no'>"
"<style>.long{height: 64px;} button{height: 35px;width: 35px;}</style>"
"<script src='http://goo.gl/m3GB3M' type='text/javascript'></script>"
"</head><body>"
"<div style='border: 5px solid black; width: 180px;'> <div id=msg1 style='float:left'></div><div id=msg2 style='float:right'></div></div>"
"<table>"
"<tr><td><button>1</button></td><td><button>2</button></td><td><button>3</button></td><td rowspan=2><button class=long>Y</button></td></tr>"
"<tr><td><button>4</button></td><td><button>5</button></td><td><button>6</button></td></tr>"
"<tr><td><button>7</button></td><td><button>8</button></td><td><button>9</button></td><td rowspan=2><button class=long>N</button></td></tr>"
"<tr><td><button>*</button></td><td><button>0</button></td><td><button>#</button></td></tr>"
"</table>"
"<script>var ws;$(document).ready(function(){"
"try{"
"ws = new WebSocket('ws://'+location.hostname+':8383/sock');"
//"ws = new WebSocket('ws://x');"
"ws.onmessage = function (evt) {var d=evt.data.split('|');$('#msg1').text(d[0]);$('#msg2').text(d[1]);};"
"ws.onerror = function (evt) {$('#msg').append('ERR:' + evt.data);};"
"ws.onclose = function (evt) {$('#msg').text('Closed');};"
"ws.onopen = function () { };"
"} catch (ex) {alert(ex.message);}"
"$(document).keypress(function (e) {ws.send(e.which);});"
"$(':button').click(function (e) { ws.send(e.target.innerText.charCodeAt(0));});"
"});</script></body></html>";
void WebSocket::EtherPoll()
{
// Should be called for each loop.
EthernetClient cli;
if (cli = ethServer.available())
{
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
//LogLn(F("browser req"));
if (cli == true)
{
if (ethClient != cli)
{//New connection
//Secrisk
ethClient = cli;
WebSocket_doHandshake();
}
else
{//Existing connection
if (WebSocket_getFrame() == false)
{//Request to end comms (rarely happens)
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
//Got bad frame, disconnect
Log(F("Disconnect{"));
while(ethClient.available()>0)
ethClient.read();
ethClient.flush();
ethClient.stop();
}
}
}
}
/* if (cli = ethServerHTML.available())
{
//Log(cli.available());
if (cli == true)
SendHTMLSite();
}
*/
}
void WebSocket::SendHTMLSite(/*EthernetClient& cli*/)
{
//Log(F("ConnectWWW{"));
// while(ethClient.available()>0)
// Log((char)cli.read());
//LogLn(F("}"));
ethClient.println(F("HTTP/1.0 200 OK")); //
ethClient.println(F("Content-Type: text/html"));
ethClient.println(F("Connnection: close"));
ethClient.println();
char* p = &htmlSite[0];
for(int n=0;n<2000;n++)
{
char c = pgm_read_byte(p++);
if (c==0) break;
//Can use tokens to compress the HTML a bit
//if (c=='*')
// ethClient.print(F("button"));
//else
ethClient.print(c);
if (n%100==0)
RKPClass::loop_PanelMon(); //most important we poll this when doing other stuff or RKP will loose data
}
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
// close the connection so browser gets data
ethClient.flush();
//delay(1);
ethClient.stop();
LogLn("Sent Page");
}
// Create a Websocket server
void WebSocket::WebSocket_EtherInit( IPAddress ip, IPAddress gateway )
{
//IPAddress ip( 192, 168, 1 , 205); //Give the device a unique IP
//IPAddress gateway( 192, 168, 1, 1 ); //Gateway (the Router)
IPAddress subnet( 255, 255, 255, 0 ); //typically dont need change
// this sequence must be unique on your lan
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x59, 0x67 }; //typically dont need change
//Start Ethernet
Ethernet.begin(mac, ip, gateway, gateway, subnet);
ethServer.begin();
//ethServerHTML.begin();
Log(F("server is at ")); LogLn(Ethernet.localIP());
delay(150); // Settle time
}
//Send something to connected browser
bool WebSocket::WebSocket_send(char* data, byte length)
{
if (!ethClient.connected())
{
LogLn(F("No Client."));
return false;
}
//int length = strlen(data);
ethClient.write(0x81);// string type
if (length > 125) {
ethClient.write(126);
ethClient.write((uint8_t) (length >> 8));
ethClient.write((uint8_t) (length && 0xFF));
}
else
ethClient.write((uint8_t) length);
for (int i=0; i<length; ++i)
ethClient.write(data[i]);
//LogLn(F("Sent OK."));
return true;
}
void WebSocket::WebSocket_doHandshake()
{
LogLn("HS");
char htmlline[128]; //TODO: there are 3 buffers used - htmlline, key and sha - maybe could merge them
char key[80];
bool hasKey = false;
bool bReqWebPage = false;
byte counter = 0;
while(ethClient.available()>0)
{//Read each line
byte bite = ethClient.read();
//Log(bite);
htmlline[counter++] = bite;
if (counter > 127)
{
LogLn(F("HandShake Overflow{"));
while(ethClient.available()>0)
LogHex(ethClient.read());
LogLn(F("}"));
//htmlline[127] = 0;
//LogHex(htmlline);
counter=0;
continue;
}
if (bite == '\n')
{ // Parse the line
htmlline[counter - 2] = 0; // Terminate string before CRLF
bool bFound = (strstr_P(htmlline, PSTR("Sec-WebSocket-Key:")) != NULL);
if (bFound)
{
hasKey = true;
strtok(htmlline, " ");
strcpy(key, strtok(NULL, " ")); //TODO: Not safe - need specify max 80 limit
}
if (strstr_P(htmlline, PSTR("GET / HTTP")) != NULL)
{
LogLn(F("Page Req"));
bReqWebPage=true;
}
counter = 0; // Start saving new header string
//Each Line - check if there is any comms to do
RKPClass::loop_PanelMon(); //most important we poll this or RKP will loose data
}
}
//Log("Got header: ");LogHex((byte*)htmlline,counter);
if (hasKey)
{
LogLn(F("WS Req"));
strcat_P(key, PSTR("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); // Magic Number GUID
Sha1.init();
Sha1.print(key);
uint8_t* hash = Sha1.result();
base64_encode(htmlline, (char*)hash, 20); //reuse htmlline buffer
ethClient.print(F("HTTP/1.1 101 Switching Protocols\r\n"));
ethClient.print(F("Upgrade: websocket\r\n"));
ethClient.print(F("Connection: Upgrade\r\n"));
ethClient.print(F("Sec-WebSocket-Accept: "));
ethClient.print(htmlline); //eg. VoNhf1LMVVTziHWxjiajVem5DB4=
ethClient.print(F("\r\n\r\n"));
LogLn(F("Connected"));
//Send any display we might have
RKPClass::bScreenHasUpdated = true; //RKPClass::SendDisplayToBrowser();
}
else if (bReqWebPage)
{// Nope, Not a websocket request - send the main webpage
//LogLn(F("WebPageReq"));
SendHTMLSite();
}
else
{
ethClient.println(F("HTTP/1.0 404 File Not Found")); //
ethClient.println(F("Content-Type: text/html"));
ethClient.println(F("Connnection: close"));
ethClient.println();
//delay(1);
ethClient.stop();
}
return;
}
struct Frame {
bool isMasked;
bool isFinal;
byte opcode;
byte mask[4];
byte length;
char data[64+1];
} frame;
byte WebSocket::ReadNext()
{
byte bite = ethClient.read();
//LogHex(bite);
return bite;
}
bool WebSocket::WebSocket_getFrame()
{
// Get opcode
byte bite = ReadNext(); if (bite==0xFF) return false;
frame.opcode = bite & 0xf; // Opcode
frame.isFinal = bite & 0x80; // Final frame?
// Determine length (only accept <= 64 for now)
bite = ReadNext(); if (bite==0xFF) return false;
frame.length = bite & 0x7f; // Length of payload
if (frame.length >= 64)
{//Unlikely to happen
Log(F("Frame Too Big")); LogLn(bite);
return false;
}
// Client should always send mask, but check just to be sure
frame.isMasked = bite & 0x80;
if (frame.isMasked) {
frame.mask[0] = ReadNext();
frame.mask[1] = ReadNext();
frame.mask[2] = ReadNext();
frame.mask[3] = ReadNext();
}
// Get message bytes and unmask them if necessary
int i = 0;
for (; i < frame.length; i++)
{
bite = ReadNext();
if (frame.isMasked)
frame.data[i] = bite ^ frame.mask[i % 4];
else
frame.data[i] = bite;
}
frame.data[i]=0;
// Frame complete!
if (!frame.isFinal)
{ // We don't handle fragments! Close and disconnect.
LogLn(F("Unsurp"));
return false; //RejectBroswerMsg();
}
if (frame.opcode== 0x01)
{// Txt frame
Log(F("Data: ")); //Got Data
LogLn(frame.data);
RKPClass::PushKey(atoi(frame.data));
return true;
}
if (frame.opcode== 0x08)
{
// Close frame. Answer with close and terminate tcp connection
LogLn(F("Close")); //Close frame
ethClient.write((uint8_t) 0x08);
return false;
}
// Unexpected. Ignore?
LogLn(F("Ex.")); //Unhandled frame ignored
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <string.h>
#include "main/imports.h"
#include "main/simple_list.h"
#include "ir.h"
#include "glsl_types.h"
ir_assignment::ir_assignment(ir_rvalue *lhs, ir_rvalue *rhs,
ir_rvalue *condition)
: ir_rvalue()
{
this->lhs = lhs;
this->rhs = rhs;
this->condition = condition;
}
ir_expression::ir_expression(int op, const struct glsl_type *type,
ir_rvalue *op0, ir_rvalue *op1)
: ir_rvalue()
{
this->type = type;
this->operation = ir_expression_operation(op);
this->operands[0] = op0;
this->operands[1] = op1;
}
ir_label::ir_label(const char *label)
: ir_instruction(), label(label)
{
/* empty */
}
ir_constant::ir_constant(const struct glsl_type *type, const void *data)
: ir_rvalue()
{
unsigned size = 0;
this->type = type;
switch (type->base_type) {
case GLSL_TYPE_UINT: size = sizeof(this->value.u[0]); break;
case GLSL_TYPE_INT: size = sizeof(this->value.i[0]); break;
case GLSL_TYPE_FLOAT: size = sizeof(this->value.f[0]); break;
case GLSL_TYPE_BOOL: size = sizeof(this->value.b[0]); break;
default:
/* FINISHME: What to do? Exceptions are not the answer.
*/
break;
}
memcpy(& this->value, data, size * type->components());
}
ir_constant::ir_constant(float f)
: ir_rvalue()
{
this->type = glsl_type::float_type;
this->value.f[0] = f;
}
ir_constant::ir_constant(unsigned int u)
: ir_rvalue()
{
this->type = glsl_type::uint_type;
this->value.u[0] = u;
}
ir_constant::ir_constant(int i)
: ir_rvalue()
{
this->type = glsl_type::int_type;
this->value.i[0] = i;
}
ir_constant::ir_constant(bool b)
: ir_rvalue()
{
this->type = glsl_type::bool_type;
this->value.b[0] = b;
}
ir_dereference::ir_dereference(ir_instruction *var)
: ir_rvalue()
{
this->mode = ir_reference_variable;
this->var = var;
this->type = (var != NULL) ? var->type : glsl_type::error_type;
}
ir_dereference::ir_dereference(ir_instruction *var,
ir_rvalue *array_index)
: ir_rvalue(), mode(ir_reference_array),
var(var)
{
this->type = (var != NULL) ? var->type : glsl_type::error_type;
this->selector.array_index = array_index;
}
ir_swizzle::ir_swizzle(ir_rvalue *val, unsigned x, unsigned y, unsigned z,
unsigned w, unsigned count)
: val(val)
{
assert((count >= 1) && (count <= 4));
const unsigned dup_mask = 0
| ((count > 1) ? ((1U << y) & ((1U << x) )) : 0)
| ((count > 2) ? ((1U << z) & ((1U << x) | (1U << y) )) : 0)
| ((count > 3) ? ((1U << w) & ((1U << x) | (1U << y) | (1U << z))) : 0);
assert(x <= 3);
assert(y <= 3);
assert(z <= 3);
assert(w <= 3);
mask.x = x;
mask.y = y;
mask.z = z;
mask.w = w;
mask.num_components = count;
mask.has_duplicates = dup_mask != 0;
/* Based on the number of elements in the swizzle and the base type
* (i.e., float, int, unsigned, or bool) of the vector being swizzled,
* generate the type of the resulting value.
*/
type = glsl_type::get_instance(val->type->base_type, mask.num_components, 1);
}
#define X 1
#define R 5
#define S 9
#define I 13
ir_swizzle *
ir_swizzle::create(ir_rvalue *val, const char *str, unsigned vector_length)
{
/* For each possible swizzle character, this table encodes the value in
* \c idx_map that represents the 0th element of the vector. For invalid
* swizzle characters (e.g., 'k'), a special value is used that will allow
* detection of errors.
*/
static const unsigned char base_idx[26] = {
/* a b c d e f g h i j k l m */
R, R, I, I, I, I, R, I, I, I, I, I, I,
/* n o p q r s t u v w x y z */
I, I, S, S, R, S, S, I, I, X, X, X, X
};
/* Each valid swizzle character has an entry in the previous table. This
* table encodes the base index encoded in the previous table plus the actual
* index of the swizzle character. When processing swizzles, the first
* character in the string is indexed in the previous table. Each character
* in the string is indexed in this table, and the value found there has the
* value form the first table subtracted. The result must be on the range
* [0,3].
*
* For example, the string "wzyx" will get X from the first table. Each of
* the charcaters will get X+3, X+2, X+1, and X+0 from this table. After
* subtraction, the swizzle values are { 3, 2, 1, 0 }.
*
* The string "wzrg" will get X from the first table. Each of the characters
* will get X+3, X+2, R+0, and R+1 from this table. After subtraction, the
* swizzle values are { 3, 2, 4, 5 }. Since 4 and 5 are outside the range
* [0,3], the error is detected.
*/
static const unsigned char idx_map[26] = {
/* a b c d e f g h i j k l m */
R+3, R+2, 0, 0, 0, 0, R+1, 0, 0, 0, 0, 0, 0,
/* n o p q r s t u v w x y z */
0, 0, S+2, S+3, R+0, S+0, S+1, 0, 0, X+3, X+0, X+1, X+2
};
int swiz_idx[4] = { 0, 0, 0, 0 };
unsigned i;
/* Validate the first character in the swizzle string and look up the base
* index value as described above.
*/
if ((str[0] < 'a') || (str[0] > 'z'))
return NULL;
const unsigned base = base_idx[str[0] - 'a'];
for (i = 0; (i < 4) && (str[i] != '\0'); i++) {
/* Validate the next character, and, as described above, convert it to a
* swizzle index.
*/
if ((str[i] < 'a') || (str[i] > 'z'))
return NULL;
swiz_idx[i] = idx_map[str[i] - 'a'] - base;
if ((swiz_idx[i] < 0) || (swiz_idx[i] >= (int) vector_length))
return NULL;
}
if (str[i] != '\0')
return NULL;
return new ir_swizzle(val, swiz_idx[0], swiz_idx[1], swiz_idx[2],
swiz_idx[3], i);
}
#undef X
#undef R
#undef S
#undef I
ir_variable::ir_variable(const struct glsl_type *type, const char *name)
: ir_instruction(), read_only(false), centroid(false), invariant(false),
mode(ir_var_auto), interpolation(ir_var_smooth)
{
this->type = type;
this->name = name;
}
ir_function_signature::ir_function_signature(const glsl_type *return_type)
: ir_instruction(), return_type(return_type), definition(NULL)
{
/* empty */
}
ir_function::ir_function(const char *name)
: ir_instruction(), name(name)
{
/* empty */
}
ir_call *
ir_call::get_error_instruction()
{
ir_call *call = new ir_call;
call->type = glsl_type::error_type;
return call;
}
<commit_msg>Set variables with the sampler base type to read only.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <string.h>
#include "main/imports.h"
#include "main/simple_list.h"
#include "ir.h"
#include "glsl_types.h"
ir_assignment::ir_assignment(ir_rvalue *lhs, ir_rvalue *rhs,
ir_rvalue *condition)
: ir_rvalue()
{
this->lhs = lhs;
this->rhs = rhs;
this->condition = condition;
}
ir_expression::ir_expression(int op, const struct glsl_type *type,
ir_rvalue *op0, ir_rvalue *op1)
: ir_rvalue()
{
this->type = type;
this->operation = ir_expression_operation(op);
this->operands[0] = op0;
this->operands[1] = op1;
}
ir_label::ir_label(const char *label)
: ir_instruction(), label(label)
{
/* empty */
}
ir_constant::ir_constant(const struct glsl_type *type, const void *data)
: ir_rvalue()
{
unsigned size = 0;
this->type = type;
switch (type->base_type) {
case GLSL_TYPE_UINT: size = sizeof(this->value.u[0]); break;
case GLSL_TYPE_INT: size = sizeof(this->value.i[0]); break;
case GLSL_TYPE_FLOAT: size = sizeof(this->value.f[0]); break;
case GLSL_TYPE_BOOL: size = sizeof(this->value.b[0]); break;
default:
/* FINISHME: What to do? Exceptions are not the answer.
*/
break;
}
memcpy(& this->value, data, size * type->components());
}
ir_constant::ir_constant(float f)
: ir_rvalue()
{
this->type = glsl_type::float_type;
this->value.f[0] = f;
}
ir_constant::ir_constant(unsigned int u)
: ir_rvalue()
{
this->type = glsl_type::uint_type;
this->value.u[0] = u;
}
ir_constant::ir_constant(int i)
: ir_rvalue()
{
this->type = glsl_type::int_type;
this->value.i[0] = i;
}
ir_constant::ir_constant(bool b)
: ir_rvalue()
{
this->type = glsl_type::bool_type;
this->value.b[0] = b;
}
ir_dereference::ir_dereference(ir_instruction *var)
: ir_rvalue()
{
this->mode = ir_reference_variable;
this->var = var;
this->type = (var != NULL) ? var->type : glsl_type::error_type;
}
ir_dereference::ir_dereference(ir_instruction *var,
ir_rvalue *array_index)
: ir_rvalue(), mode(ir_reference_array),
var(var)
{
this->type = (var != NULL) ? var->type : glsl_type::error_type;
this->selector.array_index = array_index;
}
ir_swizzle::ir_swizzle(ir_rvalue *val, unsigned x, unsigned y, unsigned z,
unsigned w, unsigned count)
: val(val)
{
assert((count >= 1) && (count <= 4));
const unsigned dup_mask = 0
| ((count > 1) ? ((1U << y) & ((1U << x) )) : 0)
| ((count > 2) ? ((1U << z) & ((1U << x) | (1U << y) )) : 0)
| ((count > 3) ? ((1U << w) & ((1U << x) | (1U << y) | (1U << z))) : 0);
assert(x <= 3);
assert(y <= 3);
assert(z <= 3);
assert(w <= 3);
mask.x = x;
mask.y = y;
mask.z = z;
mask.w = w;
mask.num_components = count;
mask.has_duplicates = dup_mask != 0;
/* Based on the number of elements in the swizzle and the base type
* (i.e., float, int, unsigned, or bool) of the vector being swizzled,
* generate the type of the resulting value.
*/
type = glsl_type::get_instance(val->type->base_type, mask.num_components, 1);
}
#define X 1
#define R 5
#define S 9
#define I 13
ir_swizzle *
ir_swizzle::create(ir_rvalue *val, const char *str, unsigned vector_length)
{
/* For each possible swizzle character, this table encodes the value in
* \c idx_map that represents the 0th element of the vector. For invalid
* swizzle characters (e.g., 'k'), a special value is used that will allow
* detection of errors.
*/
static const unsigned char base_idx[26] = {
/* a b c d e f g h i j k l m */
R, R, I, I, I, I, R, I, I, I, I, I, I,
/* n o p q r s t u v w x y z */
I, I, S, S, R, S, S, I, I, X, X, X, X
};
/* Each valid swizzle character has an entry in the previous table. This
* table encodes the base index encoded in the previous table plus the actual
* index of the swizzle character. When processing swizzles, the first
* character in the string is indexed in the previous table. Each character
* in the string is indexed in this table, and the value found there has the
* value form the first table subtracted. The result must be on the range
* [0,3].
*
* For example, the string "wzyx" will get X from the first table. Each of
* the charcaters will get X+3, X+2, X+1, and X+0 from this table. After
* subtraction, the swizzle values are { 3, 2, 1, 0 }.
*
* The string "wzrg" will get X from the first table. Each of the characters
* will get X+3, X+2, R+0, and R+1 from this table. After subtraction, the
* swizzle values are { 3, 2, 4, 5 }. Since 4 and 5 are outside the range
* [0,3], the error is detected.
*/
static const unsigned char idx_map[26] = {
/* a b c d e f g h i j k l m */
R+3, R+2, 0, 0, 0, 0, R+1, 0, 0, 0, 0, 0, 0,
/* n o p q r s t u v w x y z */
0, 0, S+2, S+3, R+0, S+0, S+1, 0, 0, X+3, X+0, X+1, X+2
};
int swiz_idx[4] = { 0, 0, 0, 0 };
unsigned i;
/* Validate the first character in the swizzle string and look up the base
* index value as described above.
*/
if ((str[0] < 'a') || (str[0] > 'z'))
return NULL;
const unsigned base = base_idx[str[0] - 'a'];
for (i = 0; (i < 4) && (str[i] != '\0'); i++) {
/* Validate the next character, and, as described above, convert it to a
* swizzle index.
*/
if ((str[i] < 'a') || (str[i] > 'z'))
return NULL;
swiz_idx[i] = idx_map[str[i] - 'a'] - base;
if ((swiz_idx[i] < 0) || (swiz_idx[i] >= (int) vector_length))
return NULL;
}
if (str[i] != '\0')
return NULL;
return new ir_swizzle(val, swiz_idx[0], swiz_idx[1], swiz_idx[2],
swiz_idx[3], i);
}
#undef X
#undef R
#undef S
#undef I
ir_variable::ir_variable(const struct glsl_type *type, const char *name)
: ir_instruction(), read_only(false), centroid(false), invariant(false),
mode(ir_var_auto), interpolation(ir_var_smooth)
{
this->type = type;
this->name = name;
if (type && type->base_type == GLSL_TYPE_SAMPLER)
this->read_only = true;
}
ir_function_signature::ir_function_signature(const glsl_type *return_type)
: ir_instruction(), return_type(return_type), definition(NULL)
{
/* empty */
}
ir_function::ir_function(const char *name)
: ir_instruction(), name(name)
{
/* empty */
}
ir_call *
ir_call::get_error_instruction()
{
ir_call *call = new ir_call;
call->type = glsl_type::error_type;
return call;
}
<|endoftext|> |
<commit_before>/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* 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.
*/
/**
*@author Grégory Van den Borre
*/
#include "../includes/Root.hpp"
#include "../includes/EnumConversion.h"
#include "../includes/JniRoot.h"
JNIEXPORT void JNICALL Java_jni_JniRoot_constructor(
JNIEnv *env,
jobject) {
LOG_FUNCTION
try {
yz::Root::create();
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_initPhysFS(
JNIEnv *env,
jobject,
POINTER vfsPointer) {
LOG_FUNCTION
yz::Root::get()->initPhysFS(reinterpret_cast<yz::physfs::Wrapper*>(vfsPointer));
}
JNIEXPORT void JNICALL Java_jni_JniRoot_loadPlugin(
JNIEnv* env,
jobject,
jstring jplugin) {
LOG_FUNCTION
JniStringWrapper plugin = JniStringWrapper(env, jplugin);
try {
yz::Root::get()->loadPlugin(plugin.getValue());
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_loadRenderer(
JNIEnv *env,
jobject,
jstring jrenderer) {
LOG_FUNCTION
JniStringWrapper renderer = JniStringWrapper(env, jrenderer);
try {
yz::Root::get()->initialise(renderer.getValue());
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT POINTER JNICALL Java_jni_JniRoot_createSceneManager(
JNIEnv* env,
jobject,
jstring jname) {
LOG_FUNCTION
JniStringWrapper name = JniStringWrapper(env, jname);
try {
return reinterpret_cast<POINTER>(yz::Root::get()->createSceneManager(name.getValue()));
} catch (std::exception& e) {
throwException(env, e.what());
}
return INVALID_POINTER;
}
JNIEXPORT void JNICALL Java_jni_JniRoot_createRenderWindow(
JNIEnv* env,
jobject,
jint width,
jint height,
jlong handle) {
LOG_FUNCTION
try {
yz::Root::get()->createRenderWindow(width, height, handle);
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_createRenderWindowGlContext(
JNIEnv* env,
jobject,
jint width,
jint height) {
LOG_FUNCTION
try {
yz::Root::get()->createRenderWindow(width, height);
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_addResourcePath(
JNIEnv* env,
jobject,
jstring jname,
jstring jpath,
jint type) {
LOG_FUNCTION
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper path = JniStringWrapper(env, jpath);
try {
yz::Root::get()->addResourcePath(name.getValue(), path.getValue(), type);
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_renderOneFrame(
JNIEnv* env,
jobject) {
LOG_FUNCTION
try {
yz::Root::get()->renderOneFrame();
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_close(
JNIEnv* env,
jobject) {
LOG_FUNCTION
try {
yz::Root::get()->close();
} catch (std::exception& e) {
throwException(env, e.what());
}
}
<commit_msg>Update JniRoot.cpp<commit_after>/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* 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.
*/
/**
*@author Grégory Van den Borre
*/
#include "../includes/Root.hpp"
#include "../includes/EnumConversion.h"
#include "../includes/JniRoot.h"
JNIEXPORT void JNICALL Java_jni_JniRoot_constructor(
JNIEnv *env,
jobject) {
LOG_FUNCTION
try {
yz::Root::create();
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_initPhysFS(
JNIEnv *env,
jobject,
POINTER vfsPointer) {
LOG_FUNCTION
yz::ogre::vfs::registerPhysFSToOgre(reinterpret_cast<yz::physfs::Wrapper*>(vfsPointer));
}
JNIEXPORT void JNICALL Java_jni_JniRoot_loadPlugin(
JNIEnv* env,
jobject,
jstring jplugin) {
LOG_FUNCTION
JniStringWrapper plugin = JniStringWrapper(env, jplugin);
try {
yz::Root::get()->loadPlugin(plugin.getValue());
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_loadRenderer(
JNIEnv *env,
jobject,
jstring jrenderer) {
LOG_FUNCTION
JniStringWrapper renderer = JniStringWrapper(env, jrenderer);
try {
yz::Root::get()->initialise(renderer.getValue());
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT POINTER JNICALL Java_jni_JniRoot_createSceneManager(
JNIEnv* env,
jobject,
jstring jname) {
LOG_FUNCTION
JniStringWrapper name = JniStringWrapper(env, jname);
try {
return reinterpret_cast<POINTER>(yz::Root::get()->createSceneManager(name.getValue()));
} catch (std::exception& e) {
throwException(env, e.what());
}
return INVALID_POINTER;
}
JNIEXPORT void JNICALL Java_jni_JniRoot_createRenderWindow(
JNIEnv* env,
jobject,
jint width,
jint height,
jlong handle) {
LOG_FUNCTION
try {
yz::Root::get()->createRenderWindow(width, height, handle);
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_createRenderWindowGlContext(
JNIEnv* env,
jobject,
jint width,
jint height) {
LOG_FUNCTION
try {
yz::Root::get()->createRenderWindow(width, height);
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_addResourcePath(
JNIEnv* env,
jobject,
jstring jname,
jstring jpath,
jint type) {
LOG_FUNCTION
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper path = JniStringWrapper(env, jpath);
try {
yz::Root::get()->addResourcePath(name.getValue(), path.getValue(), type);
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_renderOneFrame(
JNIEnv* env,
jobject) {
LOG_FUNCTION
try {
yz::Root::get()->renderOneFrame();
} catch (std::exception& e) {
throwException(env, e.what());
}
}
JNIEXPORT void JNICALL Java_jni_JniRoot_close(
JNIEnv* env,
jobject) {
LOG_FUNCTION
try {
yz::Root::get()->close();
} catch (std::exception& e) {
throwException(env, e.what());
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/platform_label.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/placeable_concept.hpp>
#include <string>
#include <cassert>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <GG/TextControl.h>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
label_t::label_t(const std::string& name,
const std::string& alt_text,
std::size_t characters,
theme_t theme) :
window_m(0),
theme_m(theme),
name_m(name),
alt_text_m(alt_text),
characters_m(characters)
{ }
/****************************************************************************************************/
void place(label_t& value, const place_data_t& place_data)
{
implementation::set_control_bounds(value.window_m, place_data);
if (!value.alt_text_m.empty())
implementation::set_control_alt_text(value.window_m, value.alt_text_m);
}
/****************************************************************************************************/
void measure(label_t& value, extents_t& result)
{
assert(value.window_m);
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
GG::Pt size =
style->DefaultFont()->TextExtent(value.name_m, value.window_m->GetTextFormat());
result.horizontal().length_m = Value(size.x);
assert(result.horizontal().length_m);
}
/****************************************************************************************************/
void measure_vertical(label_t& value, extents_t& calculated_horizontal,
const place_data_t& placed_horizontal)
{
assert(value.window_m);
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
GG::Pt size =
style->DefaultFont()->TextExtent(value.name_m, value.window_m->GetTextFormat(),
GG::X(width(placed_horizontal)));
calculated_horizontal.vertical().length_m = Value(size.y);
calculated_horizontal.vertical().guide_set_m.push_back(
Value(style->DefaultFont()->Ascent()));
}
/****************************************************************************************************/
void enable(label_t& value, bool make_enabled)
{ value.window_m->Disable(make_enabled); }
/****************************************************************************************************/
extents_t measure_text(const std::string& text, const boost::shared_ptr<GG::Font>& font)
{
extents_t result;
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
GG::Pt size = font->TextExtent(text);
result.horizontal().length_m = Value(size.x);
result.vertical().length_m = Value(size.y);
return result;
}
/****************************************************************************************************/
std::string get_control_string(const label_t& widget)
{ return widget.window_m->Text(); }
/****************************************************************************************************/
// REVISIT: MM--we need to replace the display_t mechanism with concepts/any_*/
// container idiom for event and drawing system.
template <>
platform_display_type insert<label_t>(display_t& display,
platform_display_type& parent,
label_t& element)
{
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
element.window_m = style->NewTextControl(GG::X0, GG::Y0, GG::X(100), GG::Y(100),
element.name_m, style->DefaultFont());
if (!element.alt_text_m.empty())
implementation::set_control_alt_text(element.window_m, element.alt_text_m);
return display.insert(parent, get_display(element));
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<commit_msg>Corrected the size and default format (added FORMAT_WORDBREAK) of labels/static_texts the experimental Eve bindings.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/platform_label.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/placeable_concept.hpp>
#include <string>
#include <cassert>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <GG/TextControl.h>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
label_t::label_t(const std::string& name,
const std::string& alt_text,
std::size_t characters,
theme_t theme) :
window_m(0),
theme_m(theme),
name_m(name),
alt_text_m(alt_text),
characters_m(characters)
{ }
/****************************************************************************************************/
void place(label_t& value, const place_data_t& place_data)
{
implementation::set_control_bounds(value.window_m, place_data);
if (!value.alt_text_m.empty())
implementation::set_control_alt_text(value.window_m, value.alt_text_m);
}
/****************************************************************************************************/
void measure(label_t& value, extents_t& result)
{
assert(value.window_m);
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
GG::Pt size =
style->DefaultFont()->TextExtent(value.characters_m ?
std::string(value.characters_m, '0') :
value.name_m,
value.window_m->GetTextFormat());
result.horizontal().length_m = Value(size.x);
assert(result.horizontal().length_m);
}
/****************************************************************************************************/
void measure_vertical(label_t& value, extents_t& calculated_horizontal,
const place_data_t& placed_horizontal)
{
assert(value.window_m);
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
GG::Pt size =
style->DefaultFont()->TextExtent(value.name_m, value.window_m->GetTextFormat(),
GG::X(width(placed_horizontal)));
calculated_horizontal.vertical().length_m = Value(size.y);
calculated_horizontal.vertical().guide_set_m.push_back(
Value(style->DefaultFont()->Ascent()));
}
/****************************************************************************************************/
void enable(label_t& value, bool make_enabled)
{ value.window_m->Disable(make_enabled); }
/****************************************************************************************************/
extents_t measure_text(const std::string& text, const boost::shared_ptr<GG::Font>& font)
{
extents_t result;
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
GG::Pt size = font->TextExtent(text);
result.horizontal().length_m = Value(size.x);
result.vertical().length_m = Value(size.y);
return result;
}
/****************************************************************************************************/
std::string get_control_string(const label_t& widget)
{ return widget.window_m->Text(); }
/****************************************************************************************************/
// REVISIT: MM--we need to replace the display_t mechanism with concepts/any_*/
// container idiom for event and drawing system.
template <>
platform_display_type insert<label_t>(display_t& display,
platform_display_type& parent,
label_t& element)
{
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
element.window_m = style->NewTextControl(GG::X0, GG::Y0, GG::X(100), GG::Y(100),
element.name_m, style->DefaultFont(),
GG::CLR_BLACK, GG::FORMAT_WORDBREAK);
if (!element.alt_text_m.empty())
implementation::set_control_alt_text(element.window_m, element.alt_text_m);
return display.insert(parent, get_display(element));
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <SDL_messagebox.h>
#include "Debug.h"
#include "String.h"
namespace
{
const std::map<Debug::MessageType, std::string> DebugMessageTypeNames =
{
{ Debug::MessageType::Info, "" },
{ Debug::MessageType::Warning, "Warning: " },
{ Debug::MessageType::Error, "Error: " },
};
}
const std::string Debug::LOG_FILENAME = "log.txt";
std::string Debug::getShorterPath(const char *__file__)
{
// Replace back-slashes with forward slashes, then split.
const std::string path = String::replace(std::string(__file__), '\\', '/');
const std::vector<std::string> tokens = String::split(path, '/');
std::string shortPath;
if (tokens.size() >= 2)
{
shortPath = tokens.at(tokens.size() - 2) + '/' + tokens.back();
}
else if (tokens.size() == 1)
{
shortPath = tokens.front();
}
return shortPath;
}
void Debug::write(Debug::MessageType type, const std::string &filePath,
int lineNumber, const std::string &message)
{
const std::string &messageType = DebugMessageTypeNames.at(type);
std::cerr << "[" << filePath << "(" << std::to_string(lineNumber) << ")] " <<
messageType << message << "\n";
}
void Debug::mention(const char *__file__, int lineNumber, const std::string &message)
{
Debug::write(Debug::MessageType::Info, Debug::getShorterPath(__file__),
lineNumber, message);
}
void Debug::warning(const char *__file__, int lineNumber, const std::string &message)
{
Debug::write(Debug::MessageType::Warning, Debug::getShorterPath(__file__),
lineNumber, message);
}
void Debug::crash(const char *__file__, int lineNumber, const std::string &message)
{
Debug::write(Debug::MessageType::Error, Debug::getShorterPath(__file__),
lineNumber, message);
const std::string platformName(SDL_GetPlatform());
if (platformName == "Mac OS X") {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", message.c_str(), NULL);
} else {
std::getchar();
}
exit(EXIT_FAILURE);
}
void Debug::check(bool condition, const char *__file__, int lineNumber,
const std::string &message)
{
if (!condition)
{
Debug::crash(__file__, lineNumber, message);
}
}
<commit_msg>Changing NULL to nullptr<commit_after>#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <SDL_messagebox.h>
#include "Debug.h"
#include "String.h"
namespace
{
const std::map<Debug::MessageType, std::string> DebugMessageTypeNames =
{
{ Debug::MessageType::Info, "" },
{ Debug::MessageType::Warning, "Warning: " },
{ Debug::MessageType::Error, "Error: " },
};
}
const std::string Debug::LOG_FILENAME = "log.txt";
std::string Debug::getShorterPath(const char *__file__)
{
// Replace back-slashes with forward slashes, then split.
const std::string path = String::replace(std::string(__file__), '\\', '/');
const std::vector<std::string> tokens = String::split(path, '/');
std::string shortPath;
if (tokens.size() >= 2)
{
shortPath = tokens.at(tokens.size() - 2) + '/' + tokens.back();
}
else if (tokens.size() == 1)
{
shortPath = tokens.front();
}
return shortPath;
}
void Debug::write(Debug::MessageType type, const std::string &filePath,
int lineNumber, const std::string &message)
{
const std::string &messageType = DebugMessageTypeNames.at(type);
std::cerr << "[" << filePath << "(" << std::to_string(lineNumber) << ")] " <<
messageType << message << "\n";
}
void Debug::mention(const char *__file__, int lineNumber, const std::string &message)
{
Debug::write(Debug::MessageType::Info, Debug::getShorterPath(__file__),
lineNumber, message);
}
void Debug::warning(const char *__file__, int lineNumber, const std::string &message)
{
Debug::write(Debug::MessageType::Warning, Debug::getShorterPath(__file__),
lineNumber, message);
}
void Debug::crash(const char *__file__, int lineNumber, const std::string &message)
{
Debug::write(Debug::MessageType::Error, Debug::getShorterPath(__file__),
lineNumber, message);
const std::string platformName(SDL_GetPlatform());
if (platformName == "Mac OS X") {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", message.c_str(), nullptr);
} else {
std::getchar();
}
exit(EXIT_FAILURE);
}
void Debug::check(bool condition, const char *__file__, int lineNumber,
const std::string &message)
{
if (!condition)
{
Debug::crash(__file__, lineNumber, message);
}
}
<|endoftext|> |
<commit_before>/*
Source File : PrimitiveObjectsWriter.cpp
Copyright 2011 Gal Kahana PDFWriter
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "PrimitiveObjectsWriter.h"
#include "SafeBufferMacrosDefs.h"
#include "IByteWriter.h"
using namespace IOBasicTypes;
PrimitiveObjectsWriter::PrimitiveObjectsWriter(IByteWriter* inStreamForWriting)
{
mStreamForWriting = inStreamForWriting;
}
PrimitiveObjectsWriter::~PrimitiveObjectsWriter(void)
{
}
static const IOBasicTypes::Byte scSpace[] = {' '};
void PrimitiveObjectsWriter::WriteTokenSeparator(ETokenSeparator inSeparate)
{
if(eTokenSeparatorSpace == inSeparate)
mStreamForWriting->Write(scSpace,1);
else if(eTokenSeparatorEndLine == inSeparate)
EndLine();
}
static const IOBasicTypes::Byte scNewLine[2] = {'\r','\n'};
void PrimitiveObjectsWriter::EndLine()
{
mStreamForWriting->Write(scNewLine,2);
}
void PrimitiveObjectsWriter::WriteKeyword(const std::string& inKeyword)
{
mStreamForWriting->Write((const IOBasicTypes::Byte *)inKeyword.c_str(),inKeyword.size());
EndLine();
}
static const IOBasicTypes::Byte scSlash[1] = {'/'};
void PrimitiveObjectsWriter::WriteName(const std::string& inName,ETokenSeparator inSeparate)
{
/*
from the pdf reference:
This syntax is required to represent any of the delimiter or white-space characters or the number sign character itself;
it is recommended but not required for characters whose codes are outside the range 33 (!) to 126 (~).
*/
mStreamForWriting->Write(scSlash,1);
IOBasicTypes::Byte buffer[5];
std::string::const_iterator it = inName.begin();
for(;it != inName.end();++it)
{
Byte aValue = *it;
if(aValue < 33 || aValue > 126)
{
SAFE_SPRINTF_1((char*)buffer,5,"#%02x",aValue);
mStreamForWriting->Write(buffer,strlen((char*)buffer));
}
else
{
buffer[0] = aValue;
mStreamForWriting->Write(buffer,1);
}
}
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::WriteInteger(long long inIntegerToken,ETokenSeparator inSeparate)
{
char buffer[512];
SAFE_SPRINTF_1(buffer,512,"%lld",inIntegerToken);
mStreamForWriting->Write((const IOBasicTypes::Byte *)buffer,strlen(buffer));
WriteTokenSeparator(inSeparate);
}
static const IOBasicTypes::Byte scLeftParanthesis[1] = {'('};
static const IOBasicTypes::Byte scRightParanthesis[1] = {')'};
void PrimitiveObjectsWriter::WriteUnsafeLiteralString(const std::string& inString,ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scLeftParanthesis,1);
mStreamForWriting->Write((const IOBasicTypes::Byte *)inString.c_str(),inString.size());
mStreamForWriting->Write(scRightParanthesis,1);
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::WriteLiteralString(const std::string& inString,ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scLeftParanthesis,1);
// doing some string conversion, so that charachters are written as safe ones.
IOBasicTypes::Byte buffer[5];
std::string::const_iterator it = inString.begin();
for(;it != inString.end();++it)
{
Byte aValue = *it;
if(aValue == '(' || aValue == ')' || aValue == '\\')
{
buffer[0] = '\\';
buffer[1] = aValue;
mStreamForWriting->Write(buffer,2);
}
else if (aValue < 32 || aValue > 126) // grabbing all nonprintable chars
{
SAFE_SPRINTF_1((char*)buffer,5,"\\%03o",aValue);
mStreamForWriting->Write(buffer,4);
}
else
{
buffer[0] = aValue;
mStreamForWriting->Write(buffer,1);
}
}
mStreamForWriting->Write(scRightParanthesis,1);
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::WriteDouble(double inDoubleToken,ETokenSeparator inSeparate)
{
char buffer[512];
SAFE_SPRINTF_1(buffer,512,"%lf",inDoubleToken);
LongBufferSizeType sizeToWrite = DetermineDoubleTrimmedLength(buffer);
mStreamForWriting->Write((const IOBasicTypes::Byte *)buffer,sizeToWrite);
WriteTokenSeparator(inSeparate);
}
size_t PrimitiveObjectsWriter::DetermineDoubleTrimmedLength(const char* inBufferWithDouble)
{
size_t result = strlen(inBufferWithDouble);
// remove all ending 0's
while(result > 0 && inBufferWithDouble[result-1] == '0')
--result;
// if it's actually an integer, remove also decimal point
if(result > 0 && inBufferWithDouble[result-1] == '.')
--result;
return result;
}
static const IOBasicTypes::Byte scTrue[4] = {'t','r','u','e'};
static const IOBasicTypes::Byte scFalse[5] = {'f','a','l','s','e'};
void PrimitiveObjectsWriter::WriteBoolean(bool inBoolean,ETokenSeparator inSeparate)
{
if(inBoolean)
mStreamForWriting->Write(scTrue,4);
else
mStreamForWriting->Write(scFalse,5);
WriteTokenSeparator(inSeparate);
}
static const IOBasicTypes::Byte scNull[4] = {'n','u','l','l'};
void PrimitiveObjectsWriter::WriteNull(ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scNull,4);
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::SetStreamForWriting(IByteWriter* inStreamForWriting)
{
mStreamForWriting = inStreamForWriting;
}
static const IOBasicTypes::Byte scOpenBracketSpace[2] = {'[',' '};
void PrimitiveObjectsWriter::StartArray()
{
mStreamForWriting->Write(scOpenBracketSpace,2);
}
static const IOBasicTypes::Byte scCloseBracket[1] = {']'};
void PrimitiveObjectsWriter::EndArray(ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scCloseBracket,1);
WriteTokenSeparator(inSeparate);
}
static const IOBasicTypes::Byte scLeftAngle[1] = {'<'};
static const IOBasicTypes::Byte scRightAngle[1] = {'>'};
void PrimitiveObjectsWriter::WriteHexString(const std::string& inString,ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scLeftAngle,1);
mStreamForWriting->Write((const IOBasicTypes::Byte *)inString.c_str(),inString.size());
mStreamForWriting->Write(scRightAngle,1);
WriteTokenSeparator(inSeparate);
}
IByteWriter* PrimitiveObjectsWriter::GetWritingStream()
{
return mStreamForWriting;
}<commit_msg>Update PrimitiveObjectsWriter.cpp<commit_after>/*
Source File : PrimitiveObjectsWriter.cpp
Copyright 2011 Gal Kahana PDFWriter
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "PrimitiveObjectsWriter.h"
#include "SafeBufferMacrosDefs.h"
#include "IByteWriter.h"
using namespace IOBasicTypes;
PrimitiveObjectsWriter::PrimitiveObjectsWriter(IByteWriter* inStreamForWriting)
{
mStreamForWriting = inStreamForWriting;
}
PrimitiveObjectsWriter::~PrimitiveObjectsWriter(void)
{
}
static const IOBasicTypes::Byte scSpace[] = {' '};
void PrimitiveObjectsWriter::WriteTokenSeparator(ETokenSeparator inSeparate)
{
if(eTokenSeparatorSpace == inSeparate)
mStreamForWriting->Write(scSpace,1);
else if(eTokenSeparatorEndLine == inSeparate)
EndLine();
}
static const IOBasicTypes::Byte scNewLine[2] = {'\r','\n'};
void PrimitiveObjectsWriter::EndLine()
{
mStreamForWriting->Write(scNewLine,2);
}
void PrimitiveObjectsWriter::WriteKeyword(const std::string& inKeyword)
{
mStreamForWriting->Write((const IOBasicTypes::Byte *)inKeyword.c_str(),inKeyword.size());
EndLine();
}
static const IOBasicTypes::Byte scSlash[1] = {'/'};
static const std::string scSpecialChars("()<>[]{}/%#");
void PrimitiveObjectsWriter::WriteName(const std::string& inName,ETokenSeparator inSeparate)
{
/*
from the pdf reference:
This syntax is required to represent any of the delimiter or white-space characters or the number sign character itself;
it is recommended but not required for characters whose codes are outside the range 33 (!) to 126 (~).
*/
mStreamForWriting->Write(scSlash,1);
IOBasicTypes::Byte buffer[5];
std::string::const_iterator it = inName.begin();
for(;it != inName.end();++it)
{
Byte aValue = *it;
if(aValue < 33 || aValue > 126 || scSpecialChars.find(aValue) != scSpecialChars.npos)
{
SAFE_SPRINTF_1((char*)buffer,5,"#%02x",aValue);
mStreamForWriting->Write(buffer,strlen((char*)buffer));
}
else
{
buffer[0] = aValue;
mStreamForWriting->Write(buffer,1);
}
}
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::WriteInteger(long long inIntegerToken,ETokenSeparator inSeparate)
{
char buffer[512];
SAFE_SPRINTF_1(buffer,512,"%lld",inIntegerToken);
mStreamForWriting->Write((const IOBasicTypes::Byte *)buffer,strlen(buffer));
WriteTokenSeparator(inSeparate);
}
static const IOBasicTypes::Byte scLeftParanthesis[1] = {'('};
static const IOBasicTypes::Byte scRightParanthesis[1] = {')'};
void PrimitiveObjectsWriter::WriteUnsafeLiteralString(const std::string& inString,ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scLeftParanthesis,1);
mStreamForWriting->Write((const IOBasicTypes::Byte *)inString.c_str(),inString.size());
mStreamForWriting->Write(scRightParanthesis,1);
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::WriteLiteralString(const std::string& inString,ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scLeftParanthesis,1);
// doing some string conversion, so that charachters are written as safe ones.
IOBasicTypes::Byte buffer[5];
std::string::const_iterator it = inString.begin();
for(;it != inString.end();++it)
{
Byte aValue = *it;
if(aValue == '(' || aValue == ')' || aValue == '\\')
{
buffer[0] = '\\';
buffer[1] = aValue;
mStreamForWriting->Write(buffer,2);
}
else if (aValue < 32 || aValue > 126) // grabbing all nonprintable chars
{
SAFE_SPRINTF_1((char*)buffer,5,"\\%03o",aValue);
mStreamForWriting->Write(buffer,4);
}
else
{
buffer[0] = aValue;
mStreamForWriting->Write(buffer,1);
}
}
mStreamForWriting->Write(scRightParanthesis,1);
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::WriteDouble(double inDoubleToken,ETokenSeparator inSeparate)
{
char buffer[512];
SAFE_SPRINTF_1(buffer,512,"%lf",inDoubleToken);
LongBufferSizeType sizeToWrite = DetermineDoubleTrimmedLength(buffer);
mStreamForWriting->Write((const IOBasicTypes::Byte *)buffer,sizeToWrite);
WriteTokenSeparator(inSeparate);
}
size_t PrimitiveObjectsWriter::DetermineDoubleTrimmedLength(const char* inBufferWithDouble)
{
size_t result = strlen(inBufferWithDouble);
// remove all ending 0's
while(result > 0 && inBufferWithDouble[result-1] == '0')
--result;
// if it's actually an integer, remove also decimal point
if(result > 0 && inBufferWithDouble[result-1] == '.')
--result;
return result;
}
static const IOBasicTypes::Byte scTrue[4] = {'t','r','u','e'};
static const IOBasicTypes::Byte scFalse[5] = {'f','a','l','s','e'};
void PrimitiveObjectsWriter::WriteBoolean(bool inBoolean,ETokenSeparator inSeparate)
{
if(inBoolean)
mStreamForWriting->Write(scTrue,4);
else
mStreamForWriting->Write(scFalse,5);
WriteTokenSeparator(inSeparate);
}
static const IOBasicTypes::Byte scNull[4] = {'n','u','l','l'};
void PrimitiveObjectsWriter::WriteNull(ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scNull,4);
WriteTokenSeparator(inSeparate);
}
void PrimitiveObjectsWriter::SetStreamForWriting(IByteWriter* inStreamForWriting)
{
mStreamForWriting = inStreamForWriting;
}
static const IOBasicTypes::Byte scOpenBracketSpace[2] = {'[',' '};
void PrimitiveObjectsWriter::StartArray()
{
mStreamForWriting->Write(scOpenBracketSpace,2);
}
static const IOBasicTypes::Byte scCloseBracket[1] = {']'};
void PrimitiveObjectsWriter::EndArray(ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scCloseBracket,1);
WriteTokenSeparator(inSeparate);
}
static const IOBasicTypes::Byte scLeftAngle[1] = {'<'};
static const IOBasicTypes::Byte scRightAngle[1] = {'>'};
void PrimitiveObjectsWriter::WriteHexString(const std::string& inString,ETokenSeparator inSeparate)
{
mStreamForWriting->Write(scLeftAngle,1);
mStreamForWriting->Write((const IOBasicTypes::Byte *)inString.c_str(),inString.size());
mStreamForWriting->Write(scRightAngle,1);
WriteTokenSeparator(inSeparate);
}
IByteWriter* PrimitiveObjectsWriter::GetWritingStream()
{
return mStreamForWriting;
}
<|endoftext|> |
<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() {
printf("Call to AliAnalysisVertexingHF parameters setting :\n");
vHF = new AliAnalysisVertexingHF();
//--- switch-off candidates finding (default: all on)
//vHF->SetD0toKpiOff();
//vHF->SetJPSItoEleOff();
//vHF->Set3ProngOff();
vHF->SetLikeSignOn(); // like-sign pairs and triplets
//vHF->Set4ProngOff();
//vHF->SetDstarOff();
vHF->SetFindVertexForDstar(kFALSE);
//--- secondary vertex with KF?
//vHF->SetSecVtxWithKF();
//--- set cuts for single-track selection
AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCuts->SetRequireITSRefit(kTRUE);
esdTrackCuts->SetMinNClustersITS(5);
esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
AliESDtrackCuts::kBoth);
esdTrackCuts->SetMinDCAToVertexXY(0.);
esdTrackCuts->SetPtRange(0.3,1.e10);
AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
trkFilter->AddCuts(esdTrackCuts);
vHF->SetTrackFilter(trkFilter);
AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCutsSoftPi->SetRequireITSRefit(kTRUE);
AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
//--- set cuts for candidates selection
vHF->SetD0toKpiCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
vHF->SetBtoJPSICuts(0.350);
vHF->SetDplusCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85);
vHF->SetDsCuts(0.2,0.4,0.4,0.,0.,0.005,0.06,0.,0.,0.85,0.,0.1,0.1);
vHF->SetLcCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.,0.,0.85);
vHF->SetD0to4ProngsCuts(0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.);
vHF->SetDstarCuts(0.3, 0.1, 0.05, 100000000000.0, 0.5);
vHF->SetD0fromDstarCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
//--- set this if you want to reconstruct primary vertex candidate by
// candidate using other tracks in the event (for pp, broad
// interaction region)
//vHF->SetRecoPrimVtxSkippingTrks();
//--- OR set this if you want to remove the candidate daughters from
// the primary vertex, without recostructing it from scratch
//vHF->SetRmTrksFromPrimVtx();
//--- check the settings
vHF->PrintStatus();
//--- verbose
//AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);
return vHF;
}
<commit_msg>Added kTPCrefit and nTPCcls>50 requirements for displaced tracks; remove kITSrefit for soft-pi (just nITScls>=4)<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {
printf("Call to AliAnalysisVertexingHF parameters setting :\n");
vHF = new AliAnalysisVertexingHF();
//--- switch-off candidates finding (default: all on)
//vHF->SetD0toKpiOff();
//vHF->SetJPSItoEleOff();
//vHF->Set3ProngOff();
vHF->SetLikeSignOn(); // like-sign pairs and triplets
//vHF->Set4ProngOff();
//vHF->SetDstarOff();
vHF->SetFindVertexForDstar(kFALSE);
//--- secondary vertex with KF?
//vHF->SetSecVtxWithKF();
//--- set cuts for single-track selection
// displaced tracks
AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCuts->SetRequireTPCRefit(kTRUE);
esdTrackCuts->SetMinNClustersTPC(50);
esdTrackCuts->SetRequireITSRefit(kTRUE);
esdTrackCuts->SetMinNClustersITS(5);
esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
AliESDtrackCuts::kBoth);
esdTrackCuts->SetMinDCAToVertexXY(0.);
esdTrackCuts->SetPtRange(0.3,1.e10);
AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
trkFilter->AddCuts(esdTrackCuts);
vHF->SetTrackFilter(trkFilter);
// D* soft pion tracks
AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCutsSoftPi->SetMinNClustersITS(4);
AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
//--- set cuts for candidates selection
vHF->SetD0toKpiCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
vHF->SetBtoJPSICuts(0.350);
vHF->SetDplusCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85);
vHF->SetDsCuts(0.2,0.4,0.4,0.,0.,0.005,0.06,0.,0.,0.85,0.,0.1,0.1);
vHF->SetLcCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.,0.,0.85);
vHF->SetD0to4ProngsCuts(0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.);
vHF->SetDstarCuts(0.3, 0.1, 0.05, 100000000000.0, 0.5);
vHF->SetD0fromDstarCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
//--- set this if you want to reconstruct primary vertex candidate by
// candidate using other tracks in the event (for pp, broad
// interaction region)
//vHF->SetRecoPrimVtxSkippingTrks();
//--- OR set this if you want to remove the candidate daughters from
// the primary vertex, without recostructing it from scratch
//vHF->SetRmTrksFromPrimVtx();
//--- check the settings
vHF->PrintStatus();
//--- verbose
//AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);
return vHF;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.