text stringlengths 54 60.6k |
|---|
<commit_before>TChain *MakeAODInputChain(const char* collectionfileAOD,
const char* collectionfileAODfriend,Int_t nfiles=-1) {
//
// Check one-to-one correspondence of the two collections
// Create AOD chain with friend AODVertexingHF chain
// Origin: A.Rossi, andrea.rossi@ts.infn.it
//
TAlienCollection *collectionAOD = TAlienCollection::Open(collectionfileAOD);
TGridResult *tagResultAOD = collectionAOD->GetGridResult("",0,0);
TChain *chainAOD = new TChain("aodTree");
TChain *chainAODfriend = new TChain("aodTree");
Int_t nmaxentr;
if(collectionfileAODfriend!="none"){
TAlienCollection *collectionAODfriend = TAlienCollection::Open(collectionfileAODfriend);
TGridResult *tagResultAODFriend = collectionAODfriend->GetGridResult("",0,0);
// tagResultAOD->Print();
TMap *mappa;
TObjString *filename;
Int_t event,dir,pos;
string str;
Int_t lastAOD[1000],lastAODFriend[1000];
TArrayI ***arrAOD=new TArrayI**[1000];
TArrayI ***arrAODFriend=new TArrayI**[1000];
for(Int_t j=0;j<1000;j++) {
arrAOD[j]=new TArrayI*[2];
arrAOD[j][0]=new TArrayI(100);
arrAOD[j][0]->Reset(0);
arrAOD[j][1]=new TArrayI(100);
arrAOD[j][1]->Reset(-1);
arrAODFriend[j]=new TArrayI*[2];
arrAODFriend[j][0]=new TArrayI(100);
arrAODFriend[j][0]->Reset(0);
arrAODFriend[j][1]=new TArrayI(100);
arrAODFriend[j][1]->Reset(-1);
lastAOD[j]=0;
lastAODFriend[j]=0;
}
nmaxentr=tagResultAOD->GetEntries();
if(nfiles>0&&nmaxentr>nfiles)nmaxentr=nfiles;
for(Int_t j=0;j<tagResultAOD->GetEntries();j++) {
mappa=(TMap*)tagResultAOD->At(j);
filename=(TObjString*)mappa->GetValue("turl");
str=filename->GetString();
pos=str.find_last_of("/");
str.string::replace(pos,50,"");
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&event);
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&dir);
arrAOD[event][0]->AddAt(dir,lastAOD[event]);
arrAOD[event][1]->AddAt(j,lastAOD[event]);
// printf("Adding AOD, event:%d,dir:%d,position:%d\n",event,dir,j);
lastAOD[event]++;
}
for(Int_t j=0;j<tagResultAODFriend->GetEntries();j++) {
mappa=(TMap*)tagResultAODFriend->At(j);
filename=(TObjString*)mappa->GetValue("turl");
str=filename->GetString();
pos=str.find_last_of("/");
str.string::replace(pos,50,"");
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&event);
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&dir);
arrAODFriend[event][0]->AddAt(dir,lastAODFriend[event]);
arrAODFriend[event][1]->AddAt(j,lastAODFriend[event]);
//printf("Adding AODFriend, event:%d,dir:%d,position:%d\n",event,dir,j);
lastAODFriend[event]++;
}
for(Int_t ev=0;ev<1000;ev++) {
for(Int_t j=0;j<lastAOD[ev];j++) {
dir= arrAOD[ev][0]->At(j);
for(Int_t k=0;k<lastAODFriend[ev];k++) {
if(arrAODFriend[ev][0]->At(k)==dir){
chainAOD->Add((((TObjString*)((TMap*)tagResultAOD->At(arrAOD[ev][1]->At(j)))->GetValue("turl"))->GetString()).Data());
chainAODfriend->Add((((TObjString*)((TMap*)tagResultAODFriend->At(arrAODFriend[ev][1]->At(k)))->GetValue("turl"))->GetString()).Data());
printf("Events: %d, adding AOD at position %d,dir:%d posarray:%d \n and Friend at %d, dir:%d , posarray: %d \n \n",ev,arrAOD[ev][1]->At(j),arrAOD[ev][0]->At(j),j,arrAODFriend[ev][1]->At(k),arrAODFriend[ev][0]->At(k),k);
break;
}
}
}
}
}
else {
nmaxentr=tagResultAOD->GetEntries();
if(nfiles>0&&nmaxentr>nfiles)nmaxentr=nfiles;
TString aodlfn,vertexlfn;
for(Int_t ifile=0; ifile<nmaxentr; ifile++) {
aodlfn=tagResultAOD->GetKey(ifile,"lfn");
vertexlfn=aodlfn;
vertexlfn.ReplaceAll("AliAOD.root","");
TGridResult *r=gGrid->Query(vertexlfn.Data(),"AliAOD.VertexingHF.root");
if(r->GetEntries()!=1)continue;
printf("Adding file : %s \n",tagResultAOD->GetKey(ifile,"turl"));
chainAOD->Add(tagResultAOD->GetKey(ifile,"turl"));
printf("Adding friend file : %s \n \n",r->GetKey(0,"turl"));
chainAODfriend->Add(r->GetKey(0,"turl"));
}
}
chainAOD->AddFriend(chainAODfriend);
return chainAOD;
}
//----------------------------------------------------------------------------
TChain *MakeAODInputChain(const char* pathname="",
Int_t firstdir=1,Int_t lastdir=-1) {
//
// Create AOD chain with friend AODVertexingHF chain
// Example path: "alien:///alice/cern.ch/user/r/rbala/analysis/out_lhcw/290001/"
// Origin: A.Rossi, andrea.rossi@ts.infn.it
//
TChain *chainAOD = new TChain("aodTree");
TChain *chainAODfriend = new TChain("aodTree");
if(firstdir==-1) {
// require the path is an alien path (!!!but without alien::// or /alien/ ), use lastdir as the requested number of files
TGridResult* resultAOD=gGrid->Query(pathname,"AliAOD.root","","");
Int_t nfiles=resultAOD->GetEntries();
TString aodlfn,vertexlfn;
if(lastdir>nfiles)lastdir=nfiles;
for(Int_t ifile=0; ifile<nfiles; ifile++) {
aodlfn=resultAOD->GetKey(ifile,"lfn");
vertexlfn=aodlfn;
vertexlfn.ReplaceAll("AliAOD.root","");
TGridResult *r=gGrid->Query(vertexlfn.Data(),"AliAOD.VertexingHF.root");
if(r->GetEntries()!=1)continue;
chainAOD->Add(resultAOD->GetKey(ifile,"turl"));
chainAODfriend->Add(r->GetKey(0,"turl"));
}
}
else{
if(lastdir==-1) { // only one pair of files
chainAOD->Add("AliAOD.root");
chainAODfriend->Add("AliAOD.VertexingHF.root");
} else {
// set the path to the files (can be local or on alien)
for(Int_t idir=firstdir; idir<=lastdir; idir++) {
TString aodname=pathname;
TString aodHFname=pathname;
aodname+=idir;
aodHFname+=idir;
aodname.Append("/AliAOD.root");
aodHFname.Append("/AliAOD.VertexingHF.root");
chainAOD->Add(aodname.Data());
chainAODfriend->Add(aodHFname.Data());
}
}
}
chainAOD->AddFriend(chainAODfriend);
return chainAOD;
}
<commit_msg>Added methods to stage a dataset on CAF (Andrea R, Andrea D)<commit_after>TChain *MakeAODInputChain(const char* collectionfileAOD,
const char* collectionfileAODfriend,Int_t nfiles=-1) {
//
// Check one-to-one correspondence of the two collections
// Create AOD chain with friend AODVertexingHF chain
// Origin: A.Rossi, andrea.rossi@ts.infn.it
//
TAlienCollection *collectionAOD = TAlienCollection::Open(collectionfileAOD);
TGridResult *tagResultAOD = collectionAOD->GetGridResult("",0,0);
TChain *chainAOD = new TChain("aodTree");
TChain *chainAODfriend = new TChain("aodTree");
Int_t nmaxentr;
if(collectionfileAODfriend!="none"){
TAlienCollection *collectionAODfriend = TAlienCollection::Open(collectionfileAODfriend);
TGridResult *tagResultAODFriend = collectionAODfriend->GetGridResult("",0,0);
// tagResultAOD->Print();
TMap *mappa;
TObjString *filename;
Int_t event,dir,pos;
string str;
Int_t lastAOD[1000],lastAODFriend[1000];
TArrayI ***arrAOD=new TArrayI**[1000];
TArrayI ***arrAODFriend=new TArrayI**[1000];
for(Int_t j=0;j<1000;j++) {
arrAOD[j]=new TArrayI*[2];
arrAOD[j][0]=new TArrayI(100);
arrAOD[j][0]->Reset(0);
arrAOD[j][1]=new TArrayI(100);
arrAOD[j][1]->Reset(-1);
arrAODFriend[j]=new TArrayI*[2];
arrAODFriend[j][0]=new TArrayI(100);
arrAODFriend[j][0]->Reset(0);
arrAODFriend[j][1]=new TArrayI(100);
arrAODFriend[j][1]->Reset(-1);
lastAOD[j]=0;
lastAODFriend[j]=0;
}
nmaxentr=tagResultAOD->GetEntries();
if(nfiles>0&&nmaxentr>nfiles)nmaxentr=nfiles;
for(Int_t j=0;j<tagResultAOD->GetEntries();j++) {
mappa=(TMap*)tagResultAOD->At(j);
filename=(TObjString*)mappa->GetValue("turl");
str=filename->GetString();
pos=str.find_last_of("/");
str.string::replace(pos,50,"");
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&event);
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&dir);
arrAOD[event][0]->AddAt(dir,lastAOD[event]);
arrAOD[event][1]->AddAt(j,lastAOD[event]);
// printf("Adding AOD, event:%d,dir:%d,position:%d\n",event,dir,j);
lastAOD[event]++;
}
for(Int_t j=0;j<tagResultAODFriend->GetEntries();j++) {
mappa=(TMap*)tagResultAODFriend->At(j);
filename=(TObjString*)mappa->GetValue("turl");
str=filename->GetString();
pos=str.find_last_of("/");
str.string::replace(pos,50,"");
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&event);
pos=str.find_last_of("/");
str.string::replace(pos,1," ");
sscanf(str.data(),"%*s %d",&dir);
arrAODFriend[event][0]->AddAt(dir,lastAODFriend[event]);
arrAODFriend[event][1]->AddAt(j,lastAODFriend[event]);
//printf("Adding AODFriend, event:%d,dir:%d,position:%d\n",event,dir,j);
lastAODFriend[event]++;
}
for(Int_t ev=0;ev<1000;ev++) {
for(Int_t j=0;j<lastAOD[ev];j++) {
dir= arrAOD[ev][0]->At(j);
for(Int_t k=0;k<lastAODFriend[ev];k++) {
if(arrAODFriend[ev][0]->At(k)==dir){
chainAOD->Add((((TObjString*)((TMap*)tagResultAOD->At(arrAOD[ev][1]->At(j)))->GetValue("turl"))->GetString()).Data());
chainAODfriend->Add((((TObjString*)((TMap*)tagResultAODFriend->At(arrAODFriend[ev][1]->At(k)))->GetValue("turl"))->GetString()).Data());
printf("Events: %d, adding AOD at position %d,dir:%d posarray:%d \n and Friend at %d, dir:%d , posarray: %d \n \n",ev,arrAOD[ev][1]->At(j),arrAOD[ev][0]->At(j),j,arrAODFriend[ev][1]->At(k),arrAODFriend[ev][0]->At(k),k);
break;
}
}
}
}
}
else {
nmaxentr=tagResultAOD->GetEntries();
if(nfiles>0&&nmaxentr>nfiles)nmaxentr=nfiles;
TString aodlfn,vertexlfn;
for(Int_t ifile=0; ifile<nmaxentr; ifile++) {
aodlfn=tagResultAOD->GetKey(ifile,"lfn");
vertexlfn=aodlfn;
vertexlfn.ReplaceAll("AliAOD.root","");
TGridResult *r=gGrid->Query(vertexlfn.Data(),"AliAOD.VertexingHF.root");
if(r->GetEntries()!=1)continue;
printf("Adding file : %s \n",tagResultAOD->GetKey(ifile,"turl"));
chainAOD->Add(tagResultAOD->GetKey(ifile,"turl"));
printf("Adding friend file : %s \n \n",r->GetKey(0,"turl"));
chainAODfriend->Add(r->GetKey(0,"turl"));
}
}
chainAOD->AddFriend(chainAODfriend);
return chainAOD;
}
//----------------------------------------------------------------------------
TChain *MakeAODInputChain(const char* pathname="",
Int_t firstdir=1,Int_t lastdir=-1) {
//
// Create AOD chain with friend AODVertexingHF chain
// Example path: "alien:///alice/cern.ch/user/r/rbala/analysis/out_lhcw/290001/"
// Origin: A.Rossi, andrea.rossi@ts.infn.it
//
TChain *chainAOD = new TChain("aodTree");
TChain *chainAODfriend = new TChain("aodTree");
if(firstdir==-1) {
// require the path is an alien path (!!!but without alien::// or /alien/ ), use lastdir as the requested number of files
TGridResult* resultAOD=gGrid->Query(pathname,"AliAOD.root","","");
Int_t nfiles=resultAOD->GetEntries();
TString aodlfn,vertexlfn;
if(lastdir>nfiles)lastdir=nfiles;
for(Int_t ifile=0; ifile<nfiles; ifile++) {
aodlfn=resultAOD->GetKey(ifile,"lfn");
vertexlfn=aodlfn;
vertexlfn.ReplaceAll("AliAOD.root","");
TGridResult *r=gGrid->Query(vertexlfn.Data(),"AliAOD.VertexingHF.root");
if(r->GetEntries()!=1)continue;
chainAOD->Add(resultAOD->GetKey(ifile,"turl"));
chainAODfriend->Add(r->GetKey(0,"turl"));
}
}
else{
if(lastdir==-1) { // only one pair of files
chainAOD->Add("AliAOD.root");
chainAODfriend->Add("AliAOD.VertexingHF.root");
} else {
// set the path to the files (can be local or on alien)
for(Int_t idir=firstdir; idir<=lastdir; idir++) {
TString aodname=pathname;
TString aodHFname=pathname;
aodname+=idir;
aodHFname+=idir;
aodname.Append("/AliAOD.root");
aodHFname.Append("/AliAOD.VertexingHF.root");
chainAOD->Add(aodname.Data());
chainAODfriend->Add(aodHFname.Data());
}
}
}
chainAOD->AddFriend(chainAODfriend);
return chainAOD;
}
//----------------------------------------------------------------------------
TFileCollection* MakeRootArchFileCollection(const char* collectionfileAOD,
Int_t nfiles=-1){
// METHOD USEFUL FOR ANALYSIS ON THE CAF
// Check the presence of both AliAOD.root and AODVertexingHF.root files
// in the same path
// returns a TFileCollection suitable for storing datasets in CAF
// Origin: A.Rossi, andrea.rossi@ts.infn.it
//
TAlienCollection *collectionAOD = TAlienCollection::Open(collectionfileAOD);
TGridResult *tagResultAOD = collectionAOD->GetGridResult("",0,0);
Int_t nmaxentr;
TFileCollection *proofColl=new TFileCollection("proofColl","proofColl");
nmaxentr=tagResultAOD->GetEntries();
if(nfiles>0&&nmaxentr>nfiles)nmaxentr=nfiles;
TString aodlfn;
for(Int_t ifile=0; ifile<nmaxentr; ifile++) {
aodlfn=tagResultAOD->GetKey(ifile,"lfn");
aodlfn.ReplaceAll("AliAOD.root","");
aodlfn.ReplaceAll("AliAODs.root","");
TGridResult *r=gGrid->Query(aodlfn.Data(),"AliAOD.VertexingHF.root");
if(r->GetEntries()!=1)continue;
r=gGrid->Query(aodlfn.Data(),"root_archive.zip");
if(r->GetEntries()!=1)continue;
aodlfn.Append("root_archive.zip");
printf("Adding file %s\n",aodlfn.Data());
proofColl->Add(r->GetKey(0,"turl"));
}
return proofColl;
}
//----------------------------------------------------------------------------
void StageToCAF(TString xmlcoll="collAODLHC08x.xml",
TString datasetname="AODVertexingHF_LHC08x_10files",
Int_t nfiles=-1) {
//
// Staging a dataset to CAF
// andrea.dainese@pd.infn.it
//
//gROOT->LoadMacro("MakeAODInputChain.C");
TGrid::Connect("alien://");
// find -x collAODLHC08x -z /alice/cern.ch/user/r/rbala/newtrain/out_lhc08x/* AliAOD.root > collAODLHC08x.xml
TFileCollection *proofColl = MakeRootArchFileCollection(xmlcoll.Data(),nfiles);
proofColl->SetAnchor("AliAOD.root");
gEnv->SetValue("XSec.GSI.DelegProxy","2");
TProof::Open("dainesea:PWG3@alicecaf");
gProof->RegisterDataSet(datasetname.Data(),proofColl);
gProof->ShowDataSets();
return;
}
<|endoftext|> |
<commit_before>//https://code.google.com/p/nya-engine/
#include "nms.h"
#include "memory/memory_reader.h"
#include "memory/memory_writer.h"
#include <stdio.h>
#include <stdint.h>
namespace { const char nms_sign[]={'n','y','a',' ','m','e','s','h'}; }
namespace nya_formats
{
static std::string read_string(nya_memory::memory_reader &reader)
{
unsigned short size=reader.read<unsigned short>();
const char *str=(const char *)reader.get_data();
if(!size || !str || !reader.check_remained(size))
{
reader.skip(size);
return "";
}
reader.skip(size);
return std::string(str,size);
}
bool nms::read_chunks_info(const void *data,size_t size)
{
*this=nms();
if(!data || !size)
return false;
const char *cdata=(const char *)data;
const char *const data_end=cdata+size;
header h;
cdata+=read_header(h,data,size);
if(cdata==data)
return false;
version=h.version;
chunks.resize(h.chunks_count);
for(size_t i=0;i<chunks.size();++i)
{
cdata+=read_chunk_info(chunks[i],cdata,data_end-cdata);
cdata+=chunks[i].size;
if(cdata>data_end)
{
*this=nms();
return false;
}
}
return true;
}
size_t nms::read_header(header &out_header,const void *data,size_t size)
{
out_header.version=out_header.chunks_count=0;
if(size<nms_header_size)
return 0;
nya_memory::memory_reader reader(data,size);
if(!reader.test(nms_sign,sizeof(nms_sign)))
return 0;
out_header.version=reader.read<uint32_t>();
if(!out_header.version)
return 0;
out_header.chunks_count=reader.read<uint32_t>();
return reader.get_offset();
}
size_t nms::read_chunk_info(chunk_info &out_chunk_info,const void *data,size_t size)
{
if(size<sizeof(uint32_t)*2)
return 0;
out_chunk_info.type=out_chunk_info.size=0;
nya_memory::memory_reader reader(data,size);
out_chunk_info.type=reader.read<uint32_t>();
out_chunk_info.size=reader.read<uint32_t>();
out_chunk_info.data=reader.get_data();
return reader.get_offset();
}
size_t nms::get_nms_size()
{
size_t size=nms_header_size;
for(size_t i=0;i<chunks.size();++i)
size+=get_chunk_write_size(chunks[i].size);
return size;
}
size_t nms::write_to_buf(void *data,size_t size)
{
if(!data)
return 0;
char *cdata=(char *)data;
const char *const data_end=cdata+size;
header h;
h.version=version;
h.chunks_count=(unsigned int)chunks.size();
cdata+=write_header_to_buf(h,data,size);
if(data==cdata)
return 0;
for(size_t i=0;i<chunks.size();++i)
cdata+=write_chunk_to_buf(chunks[i],cdata,data_end-cdata);
return cdata-(char *)data;
}
size_t nms::write_header_to_buf(const header &h,void *to_data,size_t to_size)
{
if(!to_data || to_size<nms_header_size)
return 0;
nya_memory::memory_writer writer(to_data,to_size);
writer.write(nms_sign,sizeof(nms_sign));
writer.write_uint(h.version);
writer.write_uint(h.chunks_count);
return writer.get_offset();
}
size_t nms::get_chunk_write_size(size_t chunk_data_size) { return chunk_data_size+sizeof(uint32_t)*2; }
size_t nms::write_chunk_to_buf(const chunk_info &chunk,void *to_data,size_t to_size)
{
if(!to_data || to_size<get_chunk_write_size(chunk.size))
return 0;
nya_memory::memory_writer writer(to_data,to_size);
writer.write_uint(chunk.type);
writer.write_uint(chunk.size);
if(!chunk.size)
return writer.get_offset();
if(!chunk.data)
return 0;
writer.write(chunk.data,chunk.size);
return writer.get_offset();
}
size_t nms_mesh_chunk::read_header(const void *data, size_t size, int version)
{
*this=nms_mesh_chunk();
if(!data || !size)
return false;
typedef uint32_t uint;
typedef uint16_t ushort;
typedef uint8_t uchar;
nya_memory::memory_reader reader(data,size);
aabb_min=reader.read<nya_math::vec3>();
aabb_max=reader.read<nya_math::vec3>();
elements.resize(reader.read<uchar>());
for(size_t i=0;i<elements.size();++i)
{
element &e=elements[i];
e.type=reader.read<uchar>();
e.dimension=reader.read<uchar>();
uchar data_type=float32;
if(version>1)
{
data_type=reader.read<uchar>();
if(data_type!=float16 && data_type!=float32)
{
*this=nms_mesh_chunk();
return 0;
}
}
e.data_type=(vertex_atrib_type)data_type;
read_string(reader); //semantics
vertex_stride+=e.dimension*sizeof(float);
}
if(!vertex_stride)
{
*this=nms_mesh_chunk();
return false;
}
verts_count=reader.read<uint>();
if(!reader.check_remained(verts_count*vertex_stride))
{
*this=nms_mesh_chunk();
return false;
}
vertices_data=reader.get_data();
if(!reader.skip(verts_count*vertex_stride))
{
*this=nms_mesh_chunk();
return false;
}
index_size=reader.read<uchar>();
if(index_size)
{
indices_count=reader.read<uint>();
if(!reader.check_remained(indices_count*index_size))
return false;
indices_data=reader.get_data();
if(!reader.skip(index_size*indices_count))
return false;
}
lods.resize(reader.read<ushort>());
for(size_t i=0;i<lods.size();++i)
{
lod &l=lods[i];
l.groups.resize(reader.read<ushort>());
for(size_t j=0;j<l.groups.size();++j)
{
group &g=l.groups[j];
g.name=read_string(reader);
g.aabb_min=reader.read<nya_math::vec3>();
g.aabb_max=reader.read<nya_math::vec3>();
g.material_idx=reader.read<ushort>();
g.offset=reader.read<uint>();
g.count=reader.read<uint>();
g.element_type=version>1?draw_element_type(reader.read<uchar>()):triangles;
}
}
return 0;
}
bool nms_material_chunk::read(const void *data,size_t size,int version)
{
*this=nms_material_chunk();
if(!data || !size)
return false;
nya_memory::memory_reader reader(data,size);
materials.resize(reader.read<uint16_t>());
for(size_t i=0;i<materials.size();++i)
{
material_info &m=materials[i];
m.name=read_string(reader);
m.textures.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.textures.size();++j)
{
m.textures[j].semantics=read_string(reader);
m.textures[j].filename=read_string(reader);
}
m.strings.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.strings.size();++j)
{
m.strings[j].name=read_string(reader);
m.strings[j].value=read_string(reader);
}
m.vectors.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.vectors.size();++j)
{
m.vectors[j].name=read_string(reader);
m.vectors[j].value.x=reader.read<float>();
m.vectors[j].value.y=reader.read<float>();
m.vectors[j].value.z=reader.read<float>();
m.vectors[j].value.w=reader.read<float>();
}
m.ints.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.ints.size();++j)
{
m.ints[j].name=read_string(reader);
m.ints[j].value=reader.read<int32_t>();
}
}
return true;
}
size_t nms_material_chunk::write_to_buf(void *to_data,size_t to_size)
{
nya_memory::memory_writer writer(to_data,to_size);
writer.write_ushort((unsigned short)materials.size());
for(size_t i=0;i<materials.size();++i)
{
material_info &m=materials[i];
writer.write_string(m.name);
writer.write_ushort((unsigned short)m.textures.size());
for(size_t j=0;j<m.textures.size();++j)
{
writer.write_string(m.textures[j].semantics);
writer.write_string(m.textures[j].filename);
}
writer.write_ushort((unsigned short)m.strings.size());
for(size_t j=0;j<m.strings.size();++j)
{
writer.write_string(m.strings[j].name);
writer.write_string(m.strings[j].value);
}
writer.write_ushort((unsigned short)m.vectors.size());
for(size_t j=0;j<m.vectors.size();++j)
{
writer.write_string(m.vectors[j].name);
writer.write_float(m.vectors[j].value.x);
writer.write_float(m.vectors[j].value.y);
writer.write_float(m.vectors[j].value.z);
writer.write_float(m.vectors[j].value.w);
}
writer.write_ushort((unsigned short)m.ints.size());
for(size_t j=0;j<m.ints.size();++j)
{
writer.write_string(m.ints[j].name);
writer.write_int(m.ints[j].value);
}
}
return writer.get_offset();
}
bool nms_skeleton_chunk::read(const void *data,size_t size,int version)
{
*this=nms_skeleton_chunk();
if(!data || !size)
return false;
nya_memory::memory_reader reader(data,size);
bones.resize(reader.read<int32_t>());
for(size_t i=0;i<bones.size();++i)
{
bone &b=bones[i];
b.name=read_string(reader);
b.rot=reader.read<nya_math::quat>();
b.pos=reader.read<nya_math::vec3>();
b.parent=reader.read<int32_t>();
}
return true;
}
}
<commit_msg>formats: nms<commit_after>//https://code.google.com/p/nya-engine/
#include "nms.h"
#include "memory/memory_reader.h"
#include "memory/memory_writer.h"
#include <stdio.h>
#include <stdint.h>
namespace { const char nms_sign[]={'n','y','a',' ','m','e','s','h'}; }
namespace nya_formats
{
static std::string read_string(nya_memory::memory_reader &reader)
{
unsigned short size=reader.read<unsigned short>();
const char *str=(const char *)reader.get_data();
if(!size || !str || !reader.check_remained(size))
{
reader.skip(size);
return "";
}
reader.skip(size);
return std::string(str,size);
}
bool nms::read_chunks_info(const void *data,size_t size)
{
*this=nms();
if(!data || !size)
return false;
const char *cdata=(const char *)data;
const char *const data_end=cdata+size;
header h;
cdata+=read_header(h,data,size);
if(cdata==data)
return false;
version=h.version;
chunks.resize(h.chunks_count);
for(size_t i=0;i<chunks.size();++i)
{
cdata+=read_chunk_info(chunks[i],cdata,data_end-cdata);
cdata+=chunks[i].size;
if(cdata>data_end)
{
*this=nms();
return false;
}
}
return true;
}
size_t nms::read_header(header &out_header,const void *data,size_t size)
{
out_header.version=out_header.chunks_count=0;
if(size<nms_header_size)
return 0;
nya_memory::memory_reader reader(data,size);
if(!reader.test(nms_sign,sizeof(nms_sign)))
return 0;
out_header.version=reader.read<uint32_t>();
if(!out_header.version)
return 0;
out_header.chunks_count=reader.read<uint32_t>();
return reader.get_offset();
}
size_t nms::read_chunk_info(chunk_info &out_chunk_info,const void *data,size_t size)
{
if(size<sizeof(uint32_t)*2)
return 0;
out_chunk_info.type=out_chunk_info.size=0;
nya_memory::memory_reader reader(data,size);
out_chunk_info.type=reader.read<uint32_t>();
out_chunk_info.size=reader.read<uint32_t>();
out_chunk_info.data=reader.get_data();
return reader.get_offset();
}
size_t nms::get_nms_size()
{
size_t size=nms_header_size;
for(size_t i=0;i<chunks.size();++i)
size+=get_chunk_write_size(chunks[i].size);
return size;
}
size_t nms::write_to_buf(void *data,size_t size)
{
if(!data)
return 0;
char *cdata=(char *)data;
const char *const data_end=cdata+size;
header h;
h.version=version;
h.chunks_count=(unsigned int)chunks.size();
cdata+=write_header_to_buf(h,data,size);
if(data==cdata)
return 0;
for(size_t i=0;i<chunks.size();++i)
cdata+=write_chunk_to_buf(chunks[i],cdata,data_end-cdata);
return cdata-(char *)data;
}
size_t nms::write_header_to_buf(const header &h,void *to_data,size_t to_size)
{
if(!to_data || to_size<nms_header_size)
return 0;
nya_memory::memory_writer writer(to_data,to_size);
writer.write(nms_sign,sizeof(nms_sign));
writer.write_uint(h.version);
writer.write_uint(h.chunks_count);
return writer.get_offset();
}
size_t nms::get_chunk_write_size(size_t chunk_data_size) { return chunk_data_size+sizeof(uint32_t)*2; }
size_t nms::write_chunk_to_buf(const chunk_info &chunk,void *to_data,size_t to_size)
{
if(!to_data || to_size<get_chunk_write_size(chunk.size))
return 0;
nya_memory::memory_writer writer(to_data,to_size);
writer.write_uint(chunk.type);
writer.write_uint(chunk.size);
if(!chunk.size)
return writer.get_offset();
if(!chunk.data)
return 0;
writer.write(chunk.data,chunk.size);
return writer.get_offset();
}
size_t nms_mesh_chunk::read_header(const void *data, size_t size, int version)
{
*this=nms_mesh_chunk();
if(!data || !size)
return 0;
typedef uint32_t uint;
typedef uint16_t ushort;
typedef uint8_t uchar;
nya_memory::memory_reader reader(data,size);
aabb_min=reader.read<nya_math::vec3>();
aabb_max=reader.read<nya_math::vec3>();
elements.resize(reader.read<uchar>());
for(size_t i=0;i<elements.size();++i)
{
element &e=elements[i];
e.type=reader.read<uchar>();
e.dimension=reader.read<uchar>();
uchar data_type=float32;
if(version>1)
{
data_type=reader.read<uchar>();
if(data_type!=float16 && data_type!=float32)
{
*this=nms_mesh_chunk();
return 0;
}
}
e.data_type=(vertex_atrib_type)data_type;
read_string(reader); //semantics
vertex_stride+=e.dimension*sizeof(float);
}
if(!vertex_stride)
{
*this=nms_mesh_chunk();
return 0;
}
verts_count=reader.read<uint>();
if(!reader.check_remained(verts_count*vertex_stride))
{
*this=nms_mesh_chunk();
return 0;
}
vertices_data=reader.get_data();
if(!reader.skip(verts_count*vertex_stride))
{
*this=nms_mesh_chunk();
return 0;
}
index_size=reader.read<uchar>();
if(index_size)
{
indices_count=reader.read<uint>();
if(!reader.check_remained(indices_count*index_size))
return 0;
indices_data=reader.get_data();
if(!reader.skip(index_size*indices_count))
return 0;
}
lods.resize(reader.read<ushort>());
for(size_t i=0;i<lods.size();++i)
{
lod &l=lods[i];
l.groups.resize(reader.read<ushort>());
for(size_t j=0;j<l.groups.size();++j)
{
group &g=l.groups[j];
g.name=read_string(reader);
g.aabb_min=reader.read<nya_math::vec3>();
g.aabb_max=reader.read<nya_math::vec3>();
g.material_idx=reader.read<ushort>();
g.offset=reader.read<uint>();
g.count=reader.read<uint>();
g.element_type=version>1?draw_element_type(reader.read<uchar>()):triangles;
}
}
return reader.get_offset();
}
bool nms_material_chunk::read(const void *data,size_t size,int version)
{
*this=nms_material_chunk();
if(!data || !size)
return false;
nya_memory::memory_reader reader(data,size);
materials.resize(reader.read<uint16_t>());
for(size_t i=0;i<materials.size();++i)
{
material_info &m=materials[i];
m.name=read_string(reader);
m.textures.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.textures.size();++j)
{
m.textures[j].semantics=read_string(reader);
m.textures[j].filename=read_string(reader);
}
m.strings.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.strings.size();++j)
{
m.strings[j].name=read_string(reader);
m.strings[j].value=read_string(reader);
}
m.vectors.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.vectors.size();++j)
{
m.vectors[j].name=read_string(reader);
m.vectors[j].value.x=reader.read<float>();
m.vectors[j].value.y=reader.read<float>();
m.vectors[j].value.z=reader.read<float>();
m.vectors[j].value.w=reader.read<float>();
}
m.ints.resize(reader.read<uint16_t>());
for(size_t j=0;j<m.ints.size();++j)
{
m.ints[j].name=read_string(reader);
m.ints[j].value=reader.read<int32_t>();
}
}
return true;
}
size_t nms_material_chunk::write_to_buf(void *to_data,size_t to_size)
{
nya_memory::memory_writer writer(to_data,to_size);
writer.write_ushort((unsigned short)materials.size());
for(size_t i=0;i<materials.size();++i)
{
material_info &m=materials[i];
writer.write_string(m.name);
writer.write_ushort((unsigned short)m.textures.size());
for(size_t j=0;j<m.textures.size();++j)
{
writer.write_string(m.textures[j].semantics);
writer.write_string(m.textures[j].filename);
}
writer.write_ushort((unsigned short)m.strings.size());
for(size_t j=0;j<m.strings.size();++j)
{
writer.write_string(m.strings[j].name);
writer.write_string(m.strings[j].value);
}
writer.write_ushort((unsigned short)m.vectors.size());
for(size_t j=0;j<m.vectors.size();++j)
{
writer.write_string(m.vectors[j].name);
writer.write_float(m.vectors[j].value.x);
writer.write_float(m.vectors[j].value.y);
writer.write_float(m.vectors[j].value.z);
writer.write_float(m.vectors[j].value.w);
}
writer.write_ushort((unsigned short)m.ints.size());
for(size_t j=0;j<m.ints.size();++j)
{
writer.write_string(m.ints[j].name);
writer.write_int(m.ints[j].value);
}
}
return writer.get_offset();
}
bool nms_skeleton_chunk::read(const void *data,size_t size,int version)
{
*this=nms_skeleton_chunk();
if(!data || !size)
return false;
nya_memory::memory_reader reader(data,size);
bones.resize(reader.read<int32_t>());
for(size_t i=0;i<bones.size();++i)
{
bone &b=bones[i];
b.name=read_string(reader);
b.rot=reader.read<nya_math::quat>();
b.pos=reader.read<nya_math::vec3>();
b.parent=reader.read<int32_t>();
}
return true;
}
}
<|endoftext|> |
<commit_before>#include "openhevcfilter.h"
#include "common.h"
#include <QDebug>
#include <QSettings>
enum OHThreadType {OH_THREAD_FRAME = 1, OH_THREAD_SLICE = 2, OH_THREAD_FRAMESLICE = 3};
OpenHEVCFilter::OpenHEVCFilter(QString id, StatisticsInterface *stats):
Filter(id, "OpenHEVC", stats, HEVCVIDEO, YUV420VIDEO),
handle_(),
parameterSets_(false),
waitFrames_(0),
slices_(true)
{}
bool OpenHEVCFilter::init()
{
qDebug() << getName() << "iniating";
QSettings settings("kvazzup.ini", QSettings::IniFormat);
handle_ = libOpenHevcInit(settings.value("video/OPENHEVC_threads").toInt(), OH_THREAD_FRAME);
libOpenHevcSetDebugMode(handle_, 0);
if(libOpenHevcStartDecoder(handle_) == -1)
{
printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to start decoder.");
return false;
}
libOpenHevcSetTemporalLayer_id(handle_, 0);
libOpenHevcSetActiveDecoders(handle_, 0);
libOpenHevcSetViewLayers(handle_, 0);
qDebug() << getName() << "initiation success. Version: " << libOpenHevcVersion(handle_);
// This is because we don't know anything about the incoming stream
maxBufferSize_ = -1; // no buffer limit
return true;
}
void OpenHEVCFilter::uninit()
{
qDebug() << getName() << "uniniating.";
libOpenHevcFlush(handle_);
libOpenHevcClose(handle_);
}
void OpenHEVCFilter::run()
{
// TODO: if not iniated, init
// TODO: call uninit when stopping?
setPriority(QThread::HighPriority);
Filter::run();
}
void OpenHEVCFilter::combineFrame(std::unique_ptr<Data>& combinedFrame)
{
if(sliceBuffer_.size() == 0)
{
qDebug() << "No previous slices";
return;
}
combinedFrame = std::unique_ptr<Data>(shallowDataCopy(sliceBuffer_.at(0).get()));
combinedFrame->data_size = 0;
for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)
{
combinedFrame->data_size += sliceBuffer_.at(i)->data_size;
}
combinedFrame->data = std::unique_ptr<uchar[]>(new uchar[combinedFrame->data_size]);
uint32_t dataWritten = 0;
for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)
{
memcpy(combinedFrame->data.get() + dataWritten,
sliceBuffer_.at(i)->data.get(), sliceBuffer_.at(i)->data_size );
dataWritten += sliceBuffer_.at(i)->data_size;
}
if(slices_ && sliceBuffer_.size() == 1)
{
slices_ = false;
qDebug() << getName() << "Detected no slices in incoming stream.";
uninit();
init();
}
sliceBuffer_.clear();
return;
}
void OpenHEVCFilter::process()
{
std::unique_ptr<Data> input = getInput();
while(input)
{
const unsigned char *buff = input->data.get();
bool nextSlice = buff[0] == 0
&& buff[1] == 0
&& buff[2] == 0;
if(!slices_ && buff[0] == 0
&& buff[1] == 0
&& buff[2] == 1)
{
slices_ = true;
qDebug() << "Detected slices in incoming stream";
uninit();
init();
}
if(!parameterSets_ && (buff[4] >> 1) == 32)
{
parameterSets_ = true;
qDebug() << getName() << ": Parameter set found after" << waitFrames_ << "frames";
}
if(parameterSets_)
{
if(nextSlice && sliceBuffer_.size() != 0)
{
std::unique_ptr<Data> frame;
combineFrame(frame);
if (frame == nullptr)
{
break;
}
int64_t pts = frame->presentationTime.tv_sec*90000 + frame->presentationTime.tv_usec*90000/1000000;
int gotPicture = libOpenHevcDecode(handle_, frame->data.get(), frame->data_size, pts);
OpenHevc_Frame openHevcFrame;
if( gotPicture == -1)
{
printDebug(DEBUG_ERROR, this, "Error while decoding.");
}
else if(!gotPicture && frame->data_size >= 2)
{
const unsigned char *buff2 = frame->data.get();
printDebug(DEBUG_WARNING, getName(), "Could not decode video frame.",
{"NAL type"}, {QString() + QString::number(buff2[0]) + QString::number(buff2[1])
+ QString::number(buff2[2]) + QString::number(buff2[3]) + QString::number(buff2[4] >> 1) });
}
else if( libOpenHevcGetOutput(handle_, gotPicture, &openHevcFrame) == -1 )
{
printDebug(DEBUG_ERROR, this, "Failed to get output.");
}
else
{
frame->width = openHevcFrame.frameInfo.nWidth;
frame->height = openHevcFrame.frameInfo.nHeight;
uint32_t finalDataSize = frame->width*frame->height + frame->width*frame->height/2;
std::unique_ptr<uchar[]> yuv_frame(new uchar[finalDataSize]);
uint8_t* pY = (uint8_t*)yuv_frame.get();
uint8_t* pU = (uint8_t*)&(yuv_frame.get()[frame->width*frame->height]);
uint8_t* pV = (uint8_t*)&(yuv_frame.get()[frame->width*frame->height + frame->width*frame->height/4]);
uint32_t s_stride = openHevcFrame.frameInfo.nYPitch;
uint32_t qs_stride = openHevcFrame.frameInfo.nUPitch/2;
uint32_t d_stride = frame->width/2;
uint32_t dd_stride = frame->width;
for (int i=0; i<frame->height; i++) {
memcpy(pY, (uint8_t *) openHevcFrame.pvY + i*s_stride, dd_stride);
pY += dd_stride;
if (! (i%2) ) {
memcpy(pU, (uint8_t *) openHevcFrame.pvU + i*qs_stride, d_stride);
pU += d_stride;
memcpy(pV, (uint8_t *) openHevcFrame.pvV + i*qs_stride, d_stride);
pV += d_stride;
}
}
// TODO: put delay into deque, and set timestamp accordingly to get more accurate latency.
frame->type = YUV420VIDEO;
frame->framerate = openHevcFrame.frameInfo.frameRate.num/openHevcFrame.frameInfo.frameRate.den;
frame->data_size = finalDataSize;
frame->data = std::move(yuv_frame);
sendOutput(std::move(frame));
}
}
sliceBuffer_.push_back(std::move(input));
}
else
{
++waitFrames_;
}
input = getInput();
}
}
<commit_msg>fix(Processing): Fixed missing new presentationTime type usage.<commit_after>#include "openhevcfilter.h"
#include "common.h"
#include <QDebug>
#include <QSettings>
enum OHThreadType {OH_THREAD_FRAME = 1, OH_THREAD_SLICE = 2, OH_THREAD_FRAMESLICE = 3};
OpenHEVCFilter::OpenHEVCFilter(QString id, StatisticsInterface *stats):
Filter(id, "OpenHEVC", stats, HEVCVIDEO, YUV420VIDEO),
handle_(),
parameterSets_(false),
waitFrames_(0),
slices_(true)
{}
bool OpenHEVCFilter::init()
{
qDebug() << getName() << "iniating";
QSettings settings("kvazzup.ini", QSettings::IniFormat);
handle_ = libOpenHevcInit(settings.value("video/OPENHEVC_threads").toInt(), OH_THREAD_FRAME);
libOpenHevcSetDebugMode(handle_, 0);
if(libOpenHevcStartDecoder(handle_) == -1)
{
printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to start decoder.");
return false;
}
libOpenHevcSetTemporalLayer_id(handle_, 0);
libOpenHevcSetActiveDecoders(handle_, 0);
libOpenHevcSetViewLayers(handle_, 0);
qDebug() << getName() << "initiation success. Version: " << libOpenHevcVersion(handle_);
// This is because we don't know anything about the incoming stream
maxBufferSize_ = -1; // no buffer limit
return true;
}
void OpenHEVCFilter::uninit()
{
qDebug() << getName() << "uniniating.";
libOpenHevcFlush(handle_);
libOpenHevcClose(handle_);
}
void OpenHEVCFilter::run()
{
// TODO: if not iniated, init
// TODO: call uninit when stopping?
setPriority(QThread::HighPriority);
Filter::run();
}
void OpenHEVCFilter::combineFrame(std::unique_ptr<Data>& combinedFrame)
{
if(sliceBuffer_.size() == 0)
{
qDebug() << "No previous slices";
return;
}
combinedFrame = std::unique_ptr<Data>(shallowDataCopy(sliceBuffer_.at(0).get()));
combinedFrame->data_size = 0;
for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)
{
combinedFrame->data_size += sliceBuffer_.at(i)->data_size;
}
combinedFrame->data = std::unique_ptr<uchar[]>(new uchar[combinedFrame->data_size]);
uint32_t dataWritten = 0;
for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)
{
memcpy(combinedFrame->data.get() + dataWritten,
sliceBuffer_.at(i)->data.get(), sliceBuffer_.at(i)->data_size );
dataWritten += sliceBuffer_.at(i)->data_size;
}
if(slices_ && sliceBuffer_.size() == 1)
{
slices_ = false;
qDebug() << getName() << "Detected no slices in incoming stream.";
uninit();
init();
}
sliceBuffer_.clear();
return;
}
void OpenHEVCFilter::process()
{
std::unique_ptr<Data> input = getInput();
while(input)
{
const unsigned char *buff = input->data.get();
bool nextSlice = buff[0] == 0
&& buff[1] == 0
&& buff[2] == 0;
if(!slices_ && buff[0] == 0
&& buff[1] == 0
&& buff[2] == 1)
{
slices_ = true;
qDebug() << "Detected slices in incoming stream";
uninit();
init();
}
if(!parameterSets_ && (buff[4] >> 1) == 32)
{
parameterSets_ = true;
qDebug() << getName() << ": Parameter set found after" << waitFrames_ << "frames";
}
if(parameterSets_)
{
if(nextSlice && sliceBuffer_.size() != 0)
{
std::unique_ptr<Data> frame;
combineFrame(frame);
if (frame == nullptr)
{
break;
}
int64_t pts = frame->presentationTime;
int gotPicture = libOpenHevcDecode(handle_, frame->data.get(), frame->data_size, pts);
OpenHevc_Frame openHevcFrame;
if( gotPicture == -1)
{
printDebug(DEBUG_ERROR, this, "Error while decoding.");
}
else if(!gotPicture && frame->data_size >= 2)
{
const unsigned char *buff2 = frame->data.get();
printDebug(DEBUG_WARNING, getName(), "Could not decode video frame.",
{"NAL type"}, {QString() + QString::number(buff2[0]) + QString::number(buff2[1])
+ QString::number(buff2[2]) + QString::number(buff2[3]) + QString::number(buff2[4] >> 1) });
}
else if( libOpenHevcGetOutput(handle_, gotPicture, &openHevcFrame) == -1 )
{
printDebug(DEBUG_ERROR, this, "Failed to get output.");
}
else
{
frame->width = openHevcFrame.frameInfo.nWidth;
frame->height = openHevcFrame.frameInfo.nHeight;
uint32_t finalDataSize = frame->width*frame->height + frame->width*frame->height/2;
std::unique_ptr<uchar[]> yuv_frame(new uchar[finalDataSize]);
uint8_t* pY = (uint8_t*)yuv_frame.get();
uint8_t* pU = (uint8_t*)&(yuv_frame.get()[frame->width*frame->height]);
uint8_t* pV = (uint8_t*)&(yuv_frame.get()[frame->width*frame->height + frame->width*frame->height/4]);
uint32_t s_stride = openHevcFrame.frameInfo.nYPitch;
uint32_t qs_stride = openHevcFrame.frameInfo.nUPitch/2;
uint32_t d_stride = frame->width/2;
uint32_t dd_stride = frame->width;
for (int i=0; i<frame->height; i++) {
memcpy(pY, (uint8_t *) openHevcFrame.pvY + i*s_stride, dd_stride);
pY += dd_stride;
if (! (i%2) ) {
memcpy(pU, (uint8_t *) openHevcFrame.pvU + i*qs_stride, d_stride);
pU += d_stride;
memcpy(pV, (uint8_t *) openHevcFrame.pvV + i*qs_stride, d_stride);
pV += d_stride;
}
}
// TODO: put delay into deque, and set timestamp accordingly to get more accurate latency.
frame->type = YUV420VIDEO;
frame->framerate = openHevcFrame.frameInfo.frameRate.num/openHevcFrame.frameInfo.frameRate.den;
frame->data_size = finalDataSize;
frame->data = std::move(yuv_frame);
sendOutput(std::move(frame));
}
}
sliceBuffer_.push_back(std::move(input));
}
else
{
++waitFrames_;
}
input = getInput();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "../tags/Logics.hpp"
#include <boost/mpl/map/map50.hpp>
#include <boost/mpl/string.hpp>
#include <boost/utility/enable_if.hpp>
namespace metaSMT {
namespace predtags = ::metaSMT::logic::tag;
namespace bvtags = ::metaSMT::logic::QF_BV::tag;
namespace arraytags = ::metaSMT::logic::Array::tag;
namespace mpl = boost::mpl;
/** \cond **/
typedef mpl::map42<
mpl::pair<predtags::true_tag, mpl::string<'t', 'r', 'u', 'e'> >
, mpl::pair<predtags::false_tag, mpl::string<'f', 'a', 'l', 's', 'e'> >
, mpl::pair<bvtags::bvult_tag, mpl::string<'b', 'v', 'u', 'l', 't'> >
, mpl::pair<bvtags::bvneg_tag, mpl::string<'b', 'v', 'n', 'e', 'g'> >
, mpl::pair<bvtags::bvnot_tag, mpl::string<'b', 'v', 'n', 'o', 't'> >
, mpl::pair<bvtags::bvand_tag, mpl::string<'b', 'v', 'a', 'n', 'd'> >
, mpl::pair<bvtags::bvor_tag, mpl::string<'b', 'v', 'o', 'r'> >
, mpl::pair<bvtags::bvnand_tag, mpl::string<'b', 'v', 'n', 'a', 'n', 'd'> >
, mpl::pair<bvtags::bvnor_tag, mpl::string<'b', 'v', 'n', 'o', 'r'> >
, mpl::pair<bvtags::bvxor_tag, mpl::string<'b', 'v', 'x', 'o', 'r'> >
, mpl::pair<bvtags::bvxnor_tag, mpl::string<'b', 'v', 'x', 'n', 'o', 'r'> >
, mpl::pair<bvtags::bvadd_tag, mpl::string<'b', 'v', 'a', 'd', 'd'> >
, mpl::pair<bvtags::bvsub_tag, mpl::string<'b', 'v', 's', 'u', 'b'> >
, mpl::pair<bvtags::bvmul_tag, mpl::string<'b', 'v', 'm', 'u', 'l'> >
, mpl::pair<bvtags::bvudiv_tag, mpl::string<'b', 'v', 'u', 'd', 'i', 'v'> >
, mpl::pair<bvtags::bvsrem_tag, mpl::string<'b', 'v', 's', 'r', 'e', 'm'> >
, mpl::pair<bvtags::bvsdiv_tag, mpl::string<'b', 'v', 's', 'd', 'i', 'v'> >
, mpl::pair<bvtags::bvurem_tag, mpl::string<'b', 'v', 'u', 'r', 'e', 'm'> >
, mpl::pair<bvtags::bvsle_tag, mpl::string<'b', 'v', 's', 'l', 'e'> >
, mpl::pair<bvtags::bvslt_tag, mpl::string<'b', 'v', 's', 'l', 't'> >
, mpl::pair<bvtags::bvsge_tag, mpl::string<'b', 'v', 's', 'g', 'e'> >
, mpl::pair<bvtags::bvsgt_tag, mpl::string<'b', 'v', 's', 'g', 't'> >
, mpl::pair<bvtags::bvule_tag, mpl::string<'b', 'v', 'u', 'l', 'e'> >
, mpl::pair<bvtags::bvult_tag, mpl::string<'b', 'v', 'u', 'l', 't'> >
, mpl::pair<bvtags::bvuge_tag, mpl::string<'b', 'v', 'u', 'g', 'e'> >
, mpl::pair<bvtags::bvugt_tag, mpl::string<'b', 'v', 'u', 'g', 't'> >
, mpl::pair<predtags::implies_tag, mpl::string<'=', '>'> >
, mpl::pair<predtags::equal_tag, mpl::string<'='> >
, mpl::pair<predtags::xor_tag, mpl::string<'x', 'o', 'r'> >
, mpl::pair<predtags::and_tag, mpl::string<'a', 'n', 'd'> >
, mpl::pair<predtags::or_tag, mpl::string<'o', 'r'> >
, mpl::pair<bvtags::bit0_tag, mpl::string<'b', 'i', 't', '0'> >
, mpl::pair<bvtags::bit1_tag, mpl::string<'b', 'i', 't', '1'> >
, mpl::pair<predtags::ite_tag, mpl::string<'i', 't', 'e'> >
, mpl::pair<predtags::not_tag, mpl::string<'n', 'o', 't'> >
, mpl::pair<bvtags::bvcomp_tag, mpl::string<'b', 'v', 'c', 'o', 'm', 'p'> >
, mpl::pair<bvtags::concat_tag, mpl::string<'c', 'o', 'n', 'c', 'a', 't'> >
, mpl::pair<arraytags::select_tag, mpl::string<'s', 'e', 'l', 'e', 'c', 't'> >
, mpl::pair<arraytags::store_tag, mpl::string<'s', 't', 'o', 'r', 'e'> >
, mpl::pair<bvtags::bvshl_tag, mpl::string<'b', 'v', 's', 'h', 'l'> >
, mpl::pair<bvtags::bvshr_tag, mpl::string<'b', 'v', 'l', 's', 'h', 'r'> >
, mpl::pair<bvtags::bvashr_tag, mpl::string<'b', 'v', 'a', 's', 'h', 'r'> >
> SMT_NameMap;
/** \endcond **/
template<typename Tag>
inline typename boost::enable_if<
typename mpl::has_key< SMT_NameMap, Tag>::type
, std::string
>::type
get_tag_name(Tag const &t) {
typedef typename mpl::at< SMT_NameMap, Tag >::type name;
return mpl::c_str<name>::value;
}
template<typename Tag>
inline typename boost::disable_if<
typename mpl::has_key< SMT_NameMap, Tag>::type
, std::string
>::type
get_tag_name(Tag const &t) {
return "unknown_name";
}
typedef mpl::map<
mpl::pair<predtags::nequal_tag, mpl::pair<predtags::not_tag, predtags::equal_tag > >
, mpl::pair<predtags::nand_tag, mpl::pair<predtags::not_tag, predtags::and_tag > >
, mpl::pair<predtags::nor_tag, mpl::pair<predtags::not_tag, predtags::or_tag > >
, mpl::pair<predtags::xnor_tag, mpl::pair<predtags::not_tag, predtags::xor_tag > >
, mpl::pair<bvtags::bvnand_tag, mpl::pair<bvtags::bvnot_tag, bvtags::bvand_tag > >
, mpl::pair<bvtags::bvnor_tag, mpl::pair<bvtags::bvnot_tag, bvtags::bvor_tag > >
, mpl::pair<bvtags::bvxnor_tag, mpl::pair<bvtags::bvnot_tag, bvtags::bvxor_tag > >
> SMT_Negated_Map;
} // metaSMT
<commit_msg>fix map name in SMT_Tag_Mapping<commit_after>#pragma once
#include "../tags/Logics.hpp"
#include <boost/mpl/map/map50.hpp>
#include <boost/mpl/string.hpp>
#include <boost/utility/enable_if.hpp>
namespace metaSMT {
namespace predtags = ::metaSMT::logic::tag;
namespace bvtags = ::metaSMT::logic::QF_BV::tag;
namespace arraytags = ::metaSMT::logic::Array::tag;
namespace mpl = boost::mpl;
/** \cond **/
typedef mpl::map42<
mpl::pair<predtags::true_tag, mpl::string<'t', 'r', 'u', 'e'> >
, mpl::pair<predtags::false_tag, mpl::string<'f', 'a', 'l', 's', 'e'> >
, mpl::pair<bvtags::bvult_tag, mpl::string<'b', 'v', 'u', 'l', 't'> >
, mpl::pair<bvtags::bvneg_tag, mpl::string<'b', 'v', 'n', 'e', 'g'> >
, mpl::pair<bvtags::bvnot_tag, mpl::string<'b', 'v', 'n', 'o', 't'> >
, mpl::pair<bvtags::bvand_tag, mpl::string<'b', 'v', 'a', 'n', 'd'> >
, mpl::pair<bvtags::bvor_tag, mpl::string<'b', 'v', 'o', 'r'> >
, mpl::pair<bvtags::bvnand_tag, mpl::string<'b', 'v', 'n', 'a', 'n', 'd'> >
, mpl::pair<bvtags::bvnor_tag, mpl::string<'b', 'v', 'n', 'o', 'r'> >
, mpl::pair<bvtags::bvxor_tag, mpl::string<'b', 'v', 'x', 'o', 'r'> >
, mpl::pair<bvtags::bvxnor_tag, mpl::string<'b', 'v', 'x', 'n', 'o', 'r'> >
, mpl::pair<bvtags::bvadd_tag, mpl::string<'b', 'v', 'a', 'd', 'd'> >
, mpl::pair<bvtags::bvsub_tag, mpl::string<'b', 'v', 's', 'u', 'b'> >
, mpl::pair<bvtags::bvmul_tag, mpl::string<'b', 'v', 'm', 'u', 'l'> >
, mpl::pair<bvtags::bvudiv_tag, mpl::string<'b', 'v', 'u', 'd', 'i', 'v'> >
, mpl::pair<bvtags::bvsrem_tag, mpl::string<'b', 'v', 's', 'r', 'e', 'm'> >
, mpl::pair<bvtags::bvsdiv_tag, mpl::string<'b', 'v', 's', 'd', 'i', 'v'> >
, mpl::pair<bvtags::bvurem_tag, mpl::string<'b', 'v', 'u', 'r', 'e', 'm'> >
, mpl::pair<bvtags::bvsle_tag, mpl::string<'b', 'v', 's', 'l', 'e'> >
, mpl::pair<bvtags::bvslt_tag, mpl::string<'b', 'v', 's', 'l', 't'> >
, mpl::pair<bvtags::bvsge_tag, mpl::string<'b', 'v', 's', 'g', 'e'> >
, mpl::pair<bvtags::bvsgt_tag, mpl::string<'b', 'v', 's', 'g', 't'> >
, mpl::pair<bvtags::bvule_tag, mpl::string<'b', 'v', 'u', 'l', 'e'> >
, mpl::pair<bvtags::bvult_tag, mpl::string<'b', 'v', 'u', 'l', 't'> >
, mpl::pair<bvtags::bvuge_tag, mpl::string<'b', 'v', 'u', 'g', 'e'> >
, mpl::pair<bvtags::bvugt_tag, mpl::string<'b', 'v', 'u', 'g', 't'> >
, mpl::pair<predtags::implies_tag, mpl::string<'=', '>'> >
, mpl::pair<predtags::equal_tag, mpl::string<'='> >
, mpl::pair<predtags::xor_tag, mpl::string<'x', 'o', 'r'> >
, mpl::pair<predtags::and_tag, mpl::string<'a', 'n', 'd'> >
, mpl::pair<predtags::or_tag, mpl::string<'o', 'r'> >
, mpl::pair<bvtags::bit0_tag, mpl::string<'b', 'i', 't', '0'> >
, mpl::pair<bvtags::bit1_tag, mpl::string<'b', 'i', 't', '1'> >
, mpl::pair<predtags::ite_tag, mpl::string<'i', 't', 'e'> >
, mpl::pair<predtags::not_tag, mpl::string<'n', 'o', 't'> >
, mpl::pair<bvtags::bvcomp_tag, mpl::string<'b', 'v', 'c', 'o', 'm', 'p'> >
, mpl::pair<bvtags::concat_tag, mpl::string<'c', 'o', 'n', 'c', 'a', 't'> >
, mpl::pair<arraytags::select_tag, mpl::string<'s', 'e', 'l', 'e', 'c', 't'> >
, mpl::pair<arraytags::store_tag, mpl::string<'s', 't', 'o', 'r', 'e'> >
, mpl::pair<bvtags::bvshl_tag, mpl::string<'b', 'v', 's', 'h', 'l'> >
, mpl::pair<bvtags::bvshr_tag, mpl::string<'b', 'v', 'l', 's', 'h', 'r'> >
, mpl::pair<bvtags::bvashr_tag, mpl::string<'b', 'v', 'a', 's', 'h', 'r'> >
> SMT_NameMap;
/** \endcond **/
template<typename Tag>
inline typename boost::enable_if<
typename mpl::has_key< SMT_NameMap, Tag>::type
, std::string
>::type
get_tag_name(Tag const &t) {
typedef typename mpl::at< SMT_NameMap, Tag >::type name;
return mpl::c_str<name>::value;
}
template<typename Tag>
inline typename boost::disable_if<
typename mpl::has_key< SMT_NameMap, Tag>::type
, std::string
>::type
get_tag_name(Tag const &t) {
return "unknown_name";
}
typedef mpl::map7<
mpl::pair<predtags::nequal_tag, mpl::pair<predtags::not_tag, predtags::equal_tag > >
, mpl::pair<predtags::nand_tag, mpl::pair<predtags::not_tag, predtags::and_tag > >
, mpl::pair<predtags::nor_tag, mpl::pair<predtags::not_tag, predtags::or_tag > >
, mpl::pair<predtags::xnor_tag, mpl::pair<predtags::not_tag, predtags::xor_tag > >
, mpl::pair<bvtags::bvnand_tag, mpl::pair<bvtags::bvnot_tag, bvtags::bvand_tag > >
, mpl::pair<bvtags::bvnor_tag, mpl::pair<bvtags::bvnot_tag, bvtags::bvor_tag > >
, mpl::pair<bvtags::bvxnor_tag, mpl::pair<bvtags::bvnot_tag, bvtags::bvxor_tag > >
> SMT_Negated_Map;
} // metaSMT
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#ifndef INCLUDED_SC_SOURCE_CORE_INC_BCASLOT_HXX
#define INCLUDED_SC_SOURCE_CORE_INC_BCASLOT_HXX
#include <set>
#include <boost/unordered_set.hpp>
#include <functional>
#include <svl/broadcast.hxx>
#include "global.hxx"
#include "brdcst.hxx"
namespace sc {
struct AreaListener
{
ScRange maArea;
SvtListener* mpListener;
};
}
/**
Used in a Unique Associative Container.
*/
class ScBroadcastArea
{
private:
ScBroadcastArea* pUpdateChainNext;
SvtBroadcaster aBroadcaster;
ScRange aRange;
sal_uLong nRefCount;
bool bInUpdateChain;
public:
ScBroadcastArea( const ScRange& rRange )
: pUpdateChainNext( NULL ), aRange( rRange ),
nRefCount( 0 ), bInUpdateChain( false ) {}
inline SvtBroadcaster& GetBroadcaster() { return aBroadcaster; }
inline const SvtBroadcaster& GetBroadcaster() const { return aBroadcaster; }
inline void UpdateRange( const ScRange& rNewRange )
{ aRange = rNewRange; }
inline const ScRange& GetRange() const { return aRange; }
inline const ScAddress& GetStart() const { return aRange.aStart; }
inline const ScAddress& GetEnd() const { return aRange.aEnd; }
inline void IncRef() { ++nRefCount; }
inline sal_uLong DecRef() { return nRefCount ? --nRefCount : 0; }
inline sal_uLong GetRef() { return nRefCount; }
inline ScBroadcastArea* GetUpdateChainNext() const { return pUpdateChainNext; }
inline void SetUpdateChainNext( ScBroadcastArea* p ) { pUpdateChainNext = p; }
inline bool IsInUpdateChain() const { return bInUpdateChain; }
inline void SetInUpdateChain( bool b ) { bInUpdateChain = b; }
/** Equalness of this or range. */
inline bool operator==( const ScBroadcastArea & rArea ) const;
};
inline bool ScBroadcastArea::operator==( const ScBroadcastArea & rArea ) const
{
return aRange == rArea.aRange;
}
struct ScBroadcastAreaEntry
{
ScBroadcastArea* mpArea;
mutable bool mbErasure; ///< TRUE if marked for erasure in this set
ScBroadcastAreaEntry( ScBroadcastArea* p ) : mpArea( p), mbErasure( false) {}
};
struct ScBroadcastAreaHash
{
size_t operator()( const ScBroadcastAreaEntry& rEntry ) const
{
return rEntry.mpArea->GetRange().hashArea();
}
};
struct ScBroadcastAreaEqual
{
bool operator()( const ScBroadcastAreaEntry& rEntry1, const ScBroadcastAreaEntry& rEntry2) const
{
return *rEntry1.mpArea == *rEntry2.mpArea;
}
};
typedef ::boost::unordered_set< ScBroadcastAreaEntry, ScBroadcastAreaHash, ScBroadcastAreaEqual > ScBroadcastAreas;
struct ScBroadcastAreaBulkHash
{
size_t operator()( const ScBroadcastArea* p ) const
{
return reinterpret_cast<size_t>(p);
}
};
struct ScBroadcastAreaBulkEqual
{
bool operator()( const ScBroadcastArea* p1, const ScBroadcastArea* p2) const
{
return p1 == p2;
}
};
typedef ::boost::unordered_set< const ScBroadcastArea*, ScBroadcastAreaBulkHash,
ScBroadcastAreaBulkEqual > ScBroadcastAreasBulk;
class ScBroadcastAreaSlotMachine;
/// Collection of BroadcastAreas
class ScBroadcastAreaSlot
{
private:
ScBroadcastAreas aBroadcastAreaTbl;
mutable ScBroadcastArea aTmpSeekBroadcastArea; // for FindBroadcastArea()
ScDocument* pDoc;
ScBroadcastAreaSlotMachine* pBASM;
bool mbInBroadcastIteration;
/**
* If true, the slot has at least one area broadcaster marked for removal.
* This flag is used only during broadcast iteration, to speed up
* iteration. Using this flag is cheaper than dereferencing each iterator
* and checking its own flag inside especially when no areas are marked
* for removal.
*/
bool mbHasErasedArea;
ScBroadcastAreas::const_iterator FindBroadcastArea( const ScRange& rRange ) const;
/**
More hypothetical (memory would probably be doomed anyway) check
whether there would be an overflow when adding an area, setting the
proper state if so.
@return true if a HardRecalcState is effective and area is not to be
added.
*/
bool CheckHardRecalcStateCondition() const;
/** Finally erase all areas pushed as to-be-erased. */
void FinallyEraseAreas();
bool isMarkedErased( const ScBroadcastAreas::iterator& rIter )
{
return (*rIter).mbErasure;
}
public:
ScBroadcastAreaSlot( ScDocument* pDoc,
ScBroadcastAreaSlotMachine* pBASM );
~ScBroadcastAreaSlot();
const ScBroadcastAreas& GetBroadcastAreas() const
{ return aBroadcastAreaTbl; }
/**
Only here new ScBroadcastArea objects are created, prevention of dupes.
@param rpArea
If NULL, a new ScBroadcastArea is created and assigned ton the
reference if a matching area wasn't found. If a matching area was
found, that is assigned. In any case, the SvtListener is added to
the broadcaster.
If not NULL then no listeners are startet, only the area is
inserted and the reference count incremented. Effectively the same
as InsertListeningArea(), so use that instead.
@return
true if rpArea passed was NULL and ScBroadcastArea is newly
created.
*/
bool StartListeningArea( const ScRange& rRange,
SvtListener* pListener,
ScBroadcastArea*& rpArea );
/**
Insert a ScBroadcastArea obtained via StartListeningArea() to
subsequent slots.
*/
void InsertListeningArea( ScBroadcastArea* pArea );
void EndListeningArea( const ScRange& rRange,
SvtListener* pListener,
ScBroadcastArea*& rpArea );
bool AreaBroadcast( const ScHint& rHint );
/// @return true if at least one broadcast occurred.
bool AreaBroadcastInRange( const ScRange& rRange,
const ScHint& rHint );
void DelBroadcastAreasInRange( const ScRange& rRange );
void UpdateRemove( UpdateRefMode eUpdateRefMode,
const ScRange& rRange,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateRemoveArea( ScBroadcastArea* pArea );
void UpdateInsert( ScBroadcastArea* pArea );
bool IsInBroadcastIteration() const { return mbInBroadcastIteration; }
/** Erase an area from set and delete it if last reference, or if
mbInBroadcastIteration is set push it to the vector of to-be-erased
areas instead.
Meant to be used internally and from ScBroadcastAreaSlotMachine only.
*/
void EraseArea( ScBroadcastAreas::iterator& rIter );
void GetAllListeners(
const ScRange& rRange, std::vector<sc::AreaListener>& rListeners, sc::AreaOverlapType eType );
};
/**
BroadcastAreaSlots and their management, once per document.
*/
class ScBroadcastAreaSlotMachine
{
private:
/**
Slot offset arrangement of columns and rows, once per sheet.
+---+---+
| 0 | 3 |
+---+---+
| 1 | 4 |
+---+---+
| 2 | 5 |
+---+---+
*/
class TableSlots
{
public:
TableSlots();
~TableSlots();
inline ScBroadcastAreaSlot** getSlots() { return ppSlots; }
/**
Obtain slot pointer, no check on validity! It is assumed that
all calls are made with the results of ComputeSlotOffset(),
ComputeAreaPoints() and ComputeNextSlot()
*/
inline ScBroadcastAreaSlot* getAreaSlot( SCSIZE nOff ) { return *(ppSlots + nOff); }
private:
ScBroadcastAreaSlot** ppSlots;
// prevent usage
TableSlots( const TableSlots& );
TableSlots& operator=( const TableSlots& );
};
typedef ::std::map< SCTAB, TableSlots* > TableSlotsMap;
typedef ::std::vector< ::std::pair< ScBroadcastAreaSlot*, ScBroadcastAreas::iterator > > AreasToBeErased;
private:
ScBroadcastAreasBulk aBulkBroadcastAreas;
TableSlotsMap aTableSlotsMap;
AreasToBeErased maAreasToBeErased;
SvtBroadcaster *pBCAlways; // for the RC_ALWAYS special range
ScDocument *pDoc;
ScBroadcastArea *pUpdateChain;
ScBroadcastArea *pEOUpdateChain;
sal_uLong nInBulkBroadcast;
inline SCSIZE ComputeSlotOffset( const ScAddress& rAddress ) const;
void ComputeAreaPoints( const ScRange& rRange,
SCSIZE& nStart, SCSIZE& nEnd,
SCSIZE& nRowBreak ) const;
public:
ScBroadcastAreaSlotMachine( ScDocument* pDoc );
~ScBroadcastAreaSlotMachine();
void StartListeningArea( const ScRange& rRange,
SvtListener* pListener );
void EndListeningArea( const ScRange& rRange,
SvtListener* pListener );
bool AreaBroadcast( const ScHint& rHint ) const;
// return: at least one broadcast occurred
bool AreaBroadcastInRange( const ScRange& rRange, const ScHint& rHint ) const;
void DelBroadcastAreasInRange( const ScRange& rRange );
void UpdateBroadcastAreas( UpdateRefMode eUpdateRefMode,
const ScRange& rRange,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void EnterBulkBroadcast();
void LeaveBulkBroadcast();
bool InsertBulkArea( const ScBroadcastArea* p );
/// @return: how many removed
size_t RemoveBulkArea( const ScBroadcastArea* p );
inline ScBroadcastArea* GetUpdateChain() const { return pUpdateChain; }
inline void SetUpdateChain( ScBroadcastArea* p ) { pUpdateChain = p; }
inline ScBroadcastArea* GetEOUpdateChain() const { return pEOUpdateChain; }
inline void SetEOUpdateChain( ScBroadcastArea* p ) { pEOUpdateChain = p; }
inline bool IsInBulkBroadcast() const { return nInBulkBroadcast > 0; }
// only for ScBroadcastAreaSlot
void PushAreaToBeErased( ScBroadcastAreaSlot* pSlot,
ScBroadcastAreas::iterator& rIter );
// only for ScBroadcastAreaSlot
void FinallyEraseAreas( ScBroadcastAreaSlot* pSlot );
std::vector<sc::AreaListener> GetAllListeners(
const ScRange& rRange, sc::AreaOverlapType eType );
};
class ScBulkBroadcast
{
ScBroadcastAreaSlotMachine* pBASM;
public:
explicit ScBulkBroadcast( ScBroadcastAreaSlotMachine* p ) : pBASM(p)
{
if (pBASM)
pBASM->EnterBulkBroadcast();
}
~ScBulkBroadcast()
{
if (pBASM)
pBASM->LeaveBulkBroadcast();
}
void LeaveBulkBroadcast()
{
if (pBASM)
{
pBASM->LeaveBulkBroadcast();
pBASM = NULL;
}
}
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Unindent.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#ifndef INCLUDED_SC_SOURCE_CORE_INC_BCASLOT_HXX
#define INCLUDED_SC_SOURCE_CORE_INC_BCASLOT_HXX
#include <set>
#include <boost/unordered_set.hpp>
#include <functional>
#include <svl/broadcast.hxx>
#include "global.hxx"
#include "brdcst.hxx"
namespace sc {
struct AreaListener
{
ScRange maArea;
SvtListener* mpListener;
};
}
/**
Used in a Unique Associative Container.
*/
class ScBroadcastArea
{
private:
ScBroadcastArea* pUpdateChainNext;
SvtBroadcaster aBroadcaster;
ScRange aRange;
sal_uLong nRefCount;
bool bInUpdateChain;
public:
ScBroadcastArea( const ScRange& rRange )
: pUpdateChainNext( NULL ), aRange( rRange ),
nRefCount( 0 ), bInUpdateChain( false ) {}
inline SvtBroadcaster& GetBroadcaster() { return aBroadcaster; }
inline const SvtBroadcaster& GetBroadcaster() const { return aBroadcaster; }
inline void UpdateRange( const ScRange& rNewRange )
{ aRange = rNewRange; }
inline const ScRange& GetRange() const { return aRange; }
inline const ScAddress& GetStart() const { return aRange.aStart; }
inline const ScAddress& GetEnd() const { return aRange.aEnd; }
inline void IncRef() { ++nRefCount; }
inline sal_uLong DecRef() { return nRefCount ? --nRefCount : 0; }
inline sal_uLong GetRef() { return nRefCount; }
inline ScBroadcastArea* GetUpdateChainNext() const { return pUpdateChainNext; }
inline void SetUpdateChainNext( ScBroadcastArea* p ) { pUpdateChainNext = p; }
inline bool IsInUpdateChain() const { return bInUpdateChain; }
inline void SetInUpdateChain( bool b ) { bInUpdateChain = b; }
/** Equalness of this or range. */
inline bool operator==( const ScBroadcastArea & rArea ) const;
};
inline bool ScBroadcastArea::operator==( const ScBroadcastArea & rArea ) const
{
return aRange == rArea.aRange;
}
struct ScBroadcastAreaEntry
{
ScBroadcastArea* mpArea;
mutable bool mbErasure; ///< TRUE if marked for erasure in this set
ScBroadcastAreaEntry( ScBroadcastArea* p ) : mpArea( p), mbErasure( false) {}
};
struct ScBroadcastAreaHash
{
size_t operator()( const ScBroadcastAreaEntry& rEntry ) const
{
return rEntry.mpArea->GetRange().hashArea();
}
};
struct ScBroadcastAreaEqual
{
bool operator()( const ScBroadcastAreaEntry& rEntry1, const ScBroadcastAreaEntry& rEntry2) const
{
return *rEntry1.mpArea == *rEntry2.mpArea;
}
};
typedef ::boost::unordered_set< ScBroadcastAreaEntry, ScBroadcastAreaHash, ScBroadcastAreaEqual > ScBroadcastAreas;
struct ScBroadcastAreaBulkHash
{
size_t operator()( const ScBroadcastArea* p ) const
{
return reinterpret_cast<size_t>(p);
}
};
struct ScBroadcastAreaBulkEqual
{
bool operator()( const ScBroadcastArea* p1, const ScBroadcastArea* p2) const
{
return p1 == p2;
}
};
typedef ::boost::unordered_set< const ScBroadcastArea*, ScBroadcastAreaBulkHash,
ScBroadcastAreaBulkEqual > ScBroadcastAreasBulk;
class ScBroadcastAreaSlotMachine;
/// Collection of BroadcastAreas
class ScBroadcastAreaSlot
{
private:
ScBroadcastAreas aBroadcastAreaTbl;
mutable ScBroadcastArea aTmpSeekBroadcastArea; // for FindBroadcastArea()
ScDocument* pDoc;
ScBroadcastAreaSlotMachine* pBASM;
bool mbInBroadcastIteration;
/**
* If true, the slot has at least one area broadcaster marked for removal.
* This flag is used only during broadcast iteration, to speed up
* iteration. Using this flag is cheaper than dereferencing each iterator
* and checking its own flag inside especially when no areas are marked
* for removal.
*/
bool mbHasErasedArea;
ScBroadcastAreas::const_iterator FindBroadcastArea( const ScRange& rRange ) const;
/**
More hypothetical (memory would probably be doomed anyway) check
whether there would be an overflow when adding an area, setting the
proper state if so.
@return true if a HardRecalcState is effective and area is not to be
added.
*/
bool CheckHardRecalcStateCondition() const;
/** Finally erase all areas pushed as to-be-erased. */
void FinallyEraseAreas();
bool isMarkedErased( const ScBroadcastAreas::iterator& rIter )
{
return (*rIter).mbErasure;
}
public:
ScBroadcastAreaSlot( ScDocument* pDoc,
ScBroadcastAreaSlotMachine* pBASM );
~ScBroadcastAreaSlot();
const ScBroadcastAreas& GetBroadcastAreas() const
{ return aBroadcastAreaTbl; }
/**
Only here new ScBroadcastArea objects are created, prevention of dupes.
@param rpArea
If NULL, a new ScBroadcastArea is created and assigned ton the
reference if a matching area wasn't found. If a matching area was
found, that is assigned. In any case, the SvtListener is added to
the broadcaster.
If not NULL then no listeners are startet, only the area is
inserted and the reference count incremented. Effectively the same
as InsertListeningArea(), so use that instead.
@return
true if rpArea passed was NULL and ScBroadcastArea is newly
created.
*/
bool StartListeningArea( const ScRange& rRange,
SvtListener* pListener,
ScBroadcastArea*& rpArea );
/**
Insert a ScBroadcastArea obtained via StartListeningArea() to
subsequent slots.
*/
void InsertListeningArea( ScBroadcastArea* pArea );
void EndListeningArea( const ScRange& rRange,
SvtListener* pListener,
ScBroadcastArea*& rpArea );
bool AreaBroadcast( const ScHint& rHint );
/// @return true if at least one broadcast occurred.
bool AreaBroadcastInRange( const ScRange& rRange,
const ScHint& rHint );
void DelBroadcastAreasInRange( const ScRange& rRange );
void UpdateRemove( UpdateRefMode eUpdateRefMode,
const ScRange& rRange,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateRemoveArea( ScBroadcastArea* pArea );
void UpdateInsert( ScBroadcastArea* pArea );
bool IsInBroadcastIteration() const { return mbInBroadcastIteration; }
/** Erase an area from set and delete it if last reference, or if
mbInBroadcastIteration is set push it to the vector of to-be-erased
areas instead.
Meant to be used internally and from ScBroadcastAreaSlotMachine only.
*/
void EraseArea( ScBroadcastAreas::iterator& rIter );
void GetAllListeners(
const ScRange& rRange, std::vector<sc::AreaListener>& rListeners, sc::AreaOverlapType eType );
};
/**
BroadcastAreaSlots and their management, once per document.
*/
class ScBroadcastAreaSlotMachine
{
private:
/**
Slot offset arrangement of columns and rows, once per sheet.
+---+---+
| 0 | 3 |
+---+---+
| 1 | 4 |
+---+---+
| 2 | 5 |
+---+---+
*/
class TableSlots
{
public:
TableSlots();
~TableSlots();
inline ScBroadcastAreaSlot** getSlots() { return ppSlots; }
/**
Obtain slot pointer, no check on validity! It is assumed that
all calls are made with the results of ComputeSlotOffset(),
ComputeAreaPoints() and ComputeNextSlot()
*/
inline ScBroadcastAreaSlot* getAreaSlot( SCSIZE nOff ) { return *(ppSlots + nOff); }
private:
ScBroadcastAreaSlot** ppSlots;
// prevent usage
TableSlots( const TableSlots& );
TableSlots& operator=( const TableSlots& );
};
typedef ::std::map< SCTAB, TableSlots* > TableSlotsMap;
typedef ::std::vector< ::std::pair< ScBroadcastAreaSlot*, ScBroadcastAreas::iterator > > AreasToBeErased;
private:
ScBroadcastAreasBulk aBulkBroadcastAreas;
TableSlotsMap aTableSlotsMap;
AreasToBeErased maAreasToBeErased;
SvtBroadcaster *pBCAlways; // for the RC_ALWAYS special range
ScDocument *pDoc;
ScBroadcastArea *pUpdateChain;
ScBroadcastArea *pEOUpdateChain;
sal_uLong nInBulkBroadcast;
inline SCSIZE ComputeSlotOffset( const ScAddress& rAddress ) const;
void ComputeAreaPoints( const ScRange& rRange,
SCSIZE& nStart, SCSIZE& nEnd,
SCSIZE& nRowBreak ) const;
public:
ScBroadcastAreaSlotMachine( ScDocument* pDoc );
~ScBroadcastAreaSlotMachine();
void StartListeningArea( const ScRange& rRange,
SvtListener* pListener );
void EndListeningArea( const ScRange& rRange,
SvtListener* pListener );
bool AreaBroadcast( const ScHint& rHint ) const;
// return: at least one broadcast occurred
bool AreaBroadcastInRange( const ScRange& rRange, const ScHint& rHint ) const;
void DelBroadcastAreasInRange( const ScRange& rRange );
void UpdateBroadcastAreas( UpdateRefMode eUpdateRefMode,
const ScRange& rRange,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void EnterBulkBroadcast();
void LeaveBulkBroadcast();
bool InsertBulkArea( const ScBroadcastArea* p );
/// @return: how many removed
size_t RemoveBulkArea( const ScBroadcastArea* p );
inline ScBroadcastArea* GetUpdateChain() const { return pUpdateChain; }
inline void SetUpdateChain( ScBroadcastArea* p ) { pUpdateChain = p; }
inline ScBroadcastArea* GetEOUpdateChain() const { return pEOUpdateChain; }
inline void SetEOUpdateChain( ScBroadcastArea* p ) { pEOUpdateChain = p; }
inline bool IsInBulkBroadcast() const { return nInBulkBroadcast > 0; }
// only for ScBroadcastAreaSlot
void PushAreaToBeErased( ScBroadcastAreaSlot* pSlot,
ScBroadcastAreas::iterator& rIter );
// only for ScBroadcastAreaSlot
void FinallyEraseAreas( ScBroadcastAreaSlot* pSlot );
std::vector<sc::AreaListener> GetAllListeners(
const ScRange& rRange, sc::AreaOverlapType eType );
};
class ScBulkBroadcast
{
ScBroadcastAreaSlotMachine* pBASM;
public:
explicit ScBulkBroadcast( ScBroadcastAreaSlotMachine* p ) : pBASM(p)
{
if (pBASM)
pBASM->EnterBulkBroadcast();
}
~ScBulkBroadcast()
{
if (pBASM)
pBASM->LeaveBulkBroadcast();
}
void LeaveBulkBroadcast()
{
if (pBASM)
{
pBASM->LeaveBulkBroadcast();
pBASM = NULL;
}
}
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/**
* @file rectangle_tree.hpp
* @author Andrew Wells
*
* Include all the necessary filse to use the Rectangle Type Trees (RTree, RStarTree, XTree,
* and HilbertRTree.)
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_HPP
/* we include bounds.hpp since it gives us the necessary files.
* However, we will not use the "ballbounds" option.
*/
#include "bounds.hpp"
#include "rectangle_tree/rectangle_tree.hpp"
#include "rectangle_tree/single_tree_traverser.hpp"
#include "rectangle_tree/single_tree_traverser_impl.hpp"
#include "rectangle_tree/dual_tree_traverser.hpp"
#include "rectangle_tree/dual_tree_traverser_impl.hpp"
#include "rectangle_tree/r_tree_split.hpp"
#include "rectangle_tree/r_star_tree_split.hpp"
#include "rectangle_tree/r_tree_descent_heuristic.hpp"
#include "rectangle_tree/r_star_tree_descent_heuristic.hpp"
#include "rectangle_tree/traits.hpp"
#include "rectangle_tree/x_tree_split.hpp"
#include "rectangle_tree/typedef.hpp"
#endif
<commit_msg>Minor misspelling fix.<commit_after>/**
* @file rectangle_tree.hpp
* @author Andrew Wells
*
* Include all the necessary files to use the Rectangle Type Trees (RTree,
* RStarTree, XTree, and HilbertRTree).
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_HPP
/* We include bounds.hpp since it gives us the necessary files.
* However, we will not use the "ballbounds" option.
*/
#include "bounds.hpp"
#include "rectangle_tree/rectangle_tree.hpp"
#include "rectangle_tree/single_tree_traverser.hpp"
#include "rectangle_tree/single_tree_traverser_impl.hpp"
#include "rectangle_tree/dual_tree_traverser.hpp"
#include "rectangle_tree/dual_tree_traverser_impl.hpp"
#include "rectangle_tree/r_tree_split.hpp"
#include "rectangle_tree/r_star_tree_split.hpp"
#include "rectangle_tree/r_tree_descent_heuristic.hpp"
#include "rectangle_tree/r_star_tree_descent_heuristic.hpp"
#include "rectangle_tree/traits.hpp"
#include "rectangle_tree/x_tree_split.hpp"
#include "rectangle_tree/typedef.hpp"
#endif
<|endoftext|> |
<commit_before>void SETUP()
{
// we assume PWG0base (and thus ESD) already loaded
CheckLoadLibrary("libMinuit");
// this package depends on STEER
CheckLoadLibrary("libVMC");
CheckLoadLibrary("libMinuit");
CheckLoadLibrary("libSTEER");
// more packages to access the alice event header
CheckLoadLibrary("libEVGEN");
CheckLoadLibrary("libFASTSIM");
CheckLoadLibrary("libmicrocern");
CheckLoadLibrary("libpdf");
CheckLoadLibrary("libpythia6");
CheckLoadLibrary("libEGPythia6");
CheckLoadLibrary("libAliPythia6");
CheckLoadLibrary("libPWG0dep");
// Set the Include paths
gROOT->ProcessLine(".include PWG0dep");
}
Int_t CheckLoadLibrary(const char* library)
{
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
<commit_msg>added loading of lhapdf lib<commit_after>void SETUP()
{
// we assume PWG0base (and thus ESD) already loaded
CheckLoadLibrary("libMinuit");
// this package depends on STEER
CheckLoadLibrary("libVMC");
CheckLoadLibrary("libMinuit");
CheckLoadLibrary("libSTEER");
// more packages to access the alice event header
CheckLoadLibrary("libEVGEN");
CheckLoadLibrary("libFASTSIM");
CheckLoadLibrary("libmicrocern");
CheckLoadLibrary("libpdf"); // both are needed because old aliroot needs pdf, new one lhapdf
CheckLoadLibrary("liblhapdf"); //
CheckLoadLibrary("libpythia6");
CheckLoadLibrary("libEGPythia6");
CheckLoadLibrary("libAliPythia6");
CheckLoadLibrary("libPWG0dep");
// Set the Include paths
gROOT->ProcessLine(".include PWG0dep");
}
Int_t CheckLoadLibrary(const char* library)
{
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
<|endoftext|> |
<commit_before>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
using namespace ProbQA;
using namespace SRPlat;
//////TODO: move these to common routines when needed by something else
const uint64_t gPerfCntFreq = []() {
LARGE_INTEGER li;
if (!QueryPerformanceFrequency(&li)) {
printf("Can't get performance counter frequency: error %u.\n", GetLastError());
}
return li.QuadPart;
}();
uint64_t GetPerfCnt() {
LARGE_INTEGER li;
if (!QueryPerformanceCounter(&li)) {
printf("Failed QueryPerformanceCounter(): error %u.\n", GetLastError());
}
return li.QuadPart;
}
bool ExistsDirectory(const char* const szPath) {
DWORD dwAttrib = GetFileAttributesA(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
//////End of common routines
void InfLoopThread() {
for (;;) {}
}
void InfLoopHead() {
std::vector<std::thread> testLoad;
for (int i = 0; i < 16; i++) {
testLoad.emplace_back(&InfLoopThread);
}
for (int i = 0; i < 16; i++) {
testLoad[i].join();
}
}
namespace {
std::string gKbsDir;
} // anonymous namespace
int LearnBinarySearch(const char* const initKbFp) {
FILE *fpProgress = fopen("progress.txt", "wt");
PqaError err;
IPqaEngine *pEngine;
if (initKbFp == nullptr) {
EngineDefinition ed;
ed._dims._nAnswers = 5;
ed._dims._nQuestions = 1000;
ed._dims._nTargets = 1000;
ed._initAmount = 0.1;
ed._prec._type = TPqaPrecisionType::Double;
pEngine = PqaGetEngineFactory().CreateCpuEngine(err, ed);
if (!err.IsOk() || pEngine == nullptr) {
fprintf(stderr, "Failed to instantiate a ProbQA engine: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
else {
pEngine = PqaGetEngineFactory().LoadCpuEngine(err, initKbFp);
if (!err.IsOk() || pEngine == nullptr) {
fprintf(stderr, "Failed to load a ProbQA engine: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
SRFastRandom fr;
SREntropyAdapter ea(fr);
constexpr int64_t cnTrainings = 1000 * 1000;
constexpr int64_t cMaxQuizLen = 100;
constexpr int64_t cMaxTrialLen = 30;
constexpr int64_t cnTopRated = 1;
int64_t nCorrect = 0;
int64_t sumQuizLens = 0;
double totCertainty = 0;
uint64_t pcStart = GetPerfCnt();
uint64_t prevQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
for (int64_t i = 0; i < cnTrainings; i++) {
if (((i & 255) == 0) && (i != 0)) {
const uint64_t totQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
const double precision = nCorrect * 100.0 / 256;
const double elapsedSec = double(GetPerfCnt() - pcStart) / gPerfCntFreq;
printf("\n*%" PRIu64 ";%.2lf%%*", totQAsked, precision);
fprintf(fpProgress, "%" PRId64 "\t%" PRIu64 "\t%lf\t%lf\t%lf\t%lf\n", i, totQAsked, precision,
double(sumQuizLens) / nCorrect, totCertainty / nCorrect, (totQAsked - prevQAsked) / elapsedSec);
fflush(fpProgress);
char kbFile[128];
sprintf(kbFile, "%sdichotomy%.6" PRId64 ".kb", gKbsDir.c_str(), i);
err = pEngine->SaveKB(kbFile, false);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to save the KB.\n");
return int(SRExitCode::UnspecifiedError);
}
nCorrect = 0;
sumQuizLens = 0;
totCertainty = 0;
prevQAsked = totQAsked;
pcStart = GetPerfCnt();
}
const TPqaId guess = ea.Generate<TPqaId>(pEngine->CopyDims()._nTargets);
volatile TPqaId dbgGuess = guess;
const TPqaId iQuiz = pEngine->StartQuiz(err);
if (!err.IsOk() || iQuiz == cInvalidPqaId) {
fprintf(stderr, "Failed to create a quiz.\n");
return int(SRExitCode::UnspecifiedError);
}
int64_t j = 0;
for (; j < cMaxQuizLen; j++) {
const TPqaId iQuestion = pEngine->NextQuestion(err, iQuiz);
if (!err.IsOk() || iQuestion == cInvalidPqaId) {
fprintf(stderr, "Failed to query a next question.\n");
return int(SRExitCode::UnspecifiedError);
}
TPqaId iAnswer;
if (guess < iQuestion - 32) {
iAnswer = 0;
}
else if (iQuestion - 32 <= guess && guess < iQuestion) {
iAnswer = 1;
}
else if (iQuestion == guess) {
iAnswer = 2;
}
else if (iQuestion < guess && guess <= iQuestion + 32) {
iAnswer = 3;
}
else if (guess > iQuestion + 32) {
iAnswer = 4;
}
else {
fprintf(stderr, "Answering logic error.\n");
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->RecordAnswer(iQuiz, iAnswer);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record answer: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
RatedTarget rts[cnTopRated];
const TPqaId nListed = pEngine->ListTopTargets(err, iQuiz, cnTopRated, rts);
if (!err.IsOk() || nListed != cnTopRated) {
fprintf(stderr, "Failed to list top targets.\n");
return int(SRExitCode::UnspecifiedError);
}
//for (TPqaId k = 0; k < cnTopRated; k++) {
// printf(" [%g; %" PRId64 "] ", rts[k]._prob, rts[k]._iTarget);
//}
//printf("\n");
TPqaId posInTop = cInvalidPqaId;
for (TPqaId k = 0; k < cnTopRated; k++) {
if (rts[k]._iTarget == guess) {
posInTop = k;
break;
}
}
if (posInTop != cInvalidPqaId) {
const double certainty = rts[posInTop]._prob * 100;
nCorrect++;
sumQuizLens += j + 1;
totCertainty += certainty;
//printf("[guess=%" PRId64 ",top=%" PRId64 ",after=%" PRId64 "]", int64_t(guess), int64_t(posInTop),
// int64_t(j+1));
printf("[G=%" PRId64 ",A=%" PRId64 ",P=%.2lf%%]", int64_t(guess), int64_t(j + 1), certainty);
break;
}
}
if (j >= cMaxQuizLen) {
printf("-");
}
err = pEngine->RecordQuizTarget(iQuiz, guess);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record quiz target: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->ReleaseQuiz(iQuiz);
if (!err.IsOk()) {
fprintf(stderr, "Failed to release a quiz: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
delete pEngine;
fclose(fpProgress);
return 0;
}
int __cdecl main() {
const char* baseName = "Logs\\PqaClient";
if (!CreateDirectoryA("Logs", nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
baseName = "PqaClient";
}
}
SRDefaultLogger::Init(SRString::MakeUnowned(baseName));
gKbsDir = "E:\\Data\\Dev\\Engines\\ProbQA\\KBs\\";
if (!ExistsDirectory(gKbsDir.c_str())) {
const char* const sKBs = "KBs";
gKbsDir = std::string(sKBs) + "\\";
if (!CreateDirectoryA(sKBs, nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
fprintf(stderr, "Failed to ensure that a directory for KBs exists.\n");
return int(SRExitCode::UnspecifiedError);
}
}
}
//return LearnBinarySearch("KBs\\initial.kb"); // To load a saved KB
return LearnBinarySearch(nullptr); // To create a KB from scratch by training
}
<commit_msg>Changed max quiz length to 25 questions.<commit_after>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
using namespace ProbQA;
using namespace SRPlat;
//////TODO: move these to common routines when needed by something else
const uint64_t gPerfCntFreq = []() {
LARGE_INTEGER li;
if (!QueryPerformanceFrequency(&li)) {
printf("Can't get performance counter frequency: error %u.\n", GetLastError());
}
return li.QuadPart;
}();
uint64_t GetPerfCnt() {
LARGE_INTEGER li;
if (!QueryPerformanceCounter(&li)) {
printf("Failed QueryPerformanceCounter(): error %u.\n", GetLastError());
}
return li.QuadPart;
}
bool ExistsDirectory(const char* const szPath) {
DWORD dwAttrib = GetFileAttributesA(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
//////End of common routines
void InfLoopThread() {
for (;;) {}
}
void InfLoopHead() {
std::vector<std::thread> testLoad;
for (int i = 0; i < 16; i++) {
testLoad.emplace_back(&InfLoopThread);
}
for (int i = 0; i < 16; i++) {
testLoad[i].join();
}
}
namespace {
std::string gKbsDir;
} // anonymous namespace
int LearnBinarySearch(const char* const initKbFp) {
FILE *fpProgress = fopen("progress.txt", "wt");
PqaError err;
IPqaEngine *pEngine;
if (initKbFp == nullptr) {
EngineDefinition ed;
ed._dims._nAnswers = 5;
ed._dims._nQuestions = 1000;
ed._dims._nTargets = 1000;
ed._initAmount = 0.1;
ed._prec._type = TPqaPrecisionType::Double;
pEngine = PqaGetEngineFactory().CreateCpuEngine(err, ed);
if (!err.IsOk() || pEngine == nullptr) {
fprintf(stderr, "Failed to instantiate a ProbQA engine: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
else {
pEngine = PqaGetEngineFactory().LoadCpuEngine(err, initKbFp);
if (!err.IsOk() || pEngine == nullptr) {
fprintf(stderr, "Failed to load a ProbQA engine: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
SRFastRandom fr;
SREntropyAdapter ea(fr);
constexpr int64_t cnTrainings = 4 * 1000 * 1000;
constexpr int64_t cMaxQuizLen = 25;
constexpr int64_t cnTopRated = 1;
int64_t nCorrect = 0;
int64_t sumQuizLens = 0;
double totCertainty = 0;
uint64_t pcStart = GetPerfCnt();
uint64_t prevQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
for (int64_t i = 0; i < cnTrainings; i++) {
if (((i & 1023) == 0) && (i != 0)) {
const uint64_t totQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
const double precision = nCorrect * 100.0 / 1024;
const double elapsedSec = double(GetPerfCnt() - pcStart) / gPerfCntFreq;
printf("\n*%" PRIu64 ";%.2lf%%*", totQAsked, precision);
fprintf(fpProgress, "%" PRId64 "\t%" PRIu64 "\t%lf\t%lf\t%lf\t%lf\n", i, totQAsked, precision,
double(sumQuizLens) / nCorrect, totCertainty / nCorrect, (totQAsked - prevQAsked) / elapsedSec);
fflush(fpProgress);
char kbFile[128];
sprintf(kbFile, "%sdichotomy%.6" PRId64 ".kb", gKbsDir.c_str(), i);
err = pEngine->SaveKB(kbFile, false);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to save the KB.\n");
return int(SRExitCode::UnspecifiedError);
}
nCorrect = 0;
sumQuizLens = 0;
totCertainty = 0;
prevQAsked = totQAsked;
pcStart = GetPerfCnt();
}
const TPqaId guess = ea.Generate<TPqaId>(pEngine->CopyDims()._nTargets);
volatile TPqaId dbgGuess = guess;
const TPqaId iQuiz = pEngine->StartQuiz(err);
if (!err.IsOk() || iQuiz == cInvalidPqaId) {
fprintf(stderr, "Failed to create a quiz.\n");
return int(SRExitCode::UnspecifiedError);
}
int64_t j = 0;
for (; j < cMaxQuizLen; j++) {
const TPqaId iQuestion = pEngine->NextQuestion(err, iQuiz);
if (!err.IsOk() || iQuestion == cInvalidPqaId) {
fprintf(stderr, "Failed to query a next question.\n");
return int(SRExitCode::UnspecifiedError);
}
TPqaId iAnswer;
if (guess < iQuestion - 32) {
iAnswer = 0;
}
else if (iQuestion - 32 <= guess && guess < iQuestion) {
iAnswer = 1;
}
else if (iQuestion == guess) {
iAnswer = 2;
}
else if (iQuestion < guess && guess <= iQuestion + 32) {
iAnswer = 3;
}
else if (guess > iQuestion + 32) {
iAnswer = 4;
}
else {
fprintf(stderr, "Answering logic error.\n");
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->RecordAnswer(iQuiz, iAnswer);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record answer: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
RatedTarget rts[cnTopRated];
const TPqaId nListed = pEngine->ListTopTargets(err, iQuiz, cnTopRated, rts);
if (!err.IsOk() || nListed != cnTopRated) {
fprintf(stderr, "Failed to list top targets.\n");
return int(SRExitCode::UnspecifiedError);
}
//for (TPqaId k = 0; k < cnTopRated; k++) {
// printf(" [%g; %" PRId64 "] ", rts[k]._prob, rts[k]._iTarget);
//}
//printf("\n");
TPqaId posInTop = cInvalidPqaId;
for (TPqaId k = 0; k < cnTopRated; k++) {
if (rts[k]._iTarget == guess) {
posInTop = k;
break;
}
}
if (posInTop != cInvalidPqaId) {
const double certainty = rts[posInTop]._prob * 100;
nCorrect++;
sumQuizLens += j + 1;
totCertainty += certainty;
//printf("[guess=%" PRId64 ",top=%" PRId64 ",after=%" PRId64 "]", int64_t(guess), int64_t(posInTop),
// int64_t(j+1));
printf("[G=%" PRId64 ",A=%" PRId64 ",P=%.2lf%%]", int64_t(guess), int64_t(j + 1), certainty);
break;
}
}
if (j >= cMaxQuizLen) {
printf("-");
}
err = pEngine->RecordQuizTarget(iQuiz, guess);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record quiz target: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->ReleaseQuiz(iQuiz);
if (!err.IsOk()) {
fprintf(stderr, "Failed to release a quiz: %s\n", err.ToString(true).ToStd().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
delete pEngine;
fclose(fpProgress);
return 0;
}
int __cdecl main() {
const char* baseName = "Logs\\PqaClient";
if (!CreateDirectoryA("Logs", nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
baseName = "PqaClient";
}
}
SRDefaultLogger::Init(SRString::MakeUnowned(baseName));
gKbsDir = "E:\\Data\\Dev\\Engines\\ProbQA\\KBs\\";
if (!ExistsDirectory(gKbsDir.c_str())) {
const char* const sKBs = "KBs";
gKbsDir = std::string(sKBs) + "\\";
if (!CreateDirectoryA(sKBs, nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
fprintf(stderr, "Failed to ensure that a directory for KBs exists.\n");
return int(SRExitCode::UnspecifiedError);
}
}
}
//return LearnBinarySearch("KBs\\initial.kb"); // To load a saved KB
return LearnBinarySearch(nullptr); // To create a KB from scratch by training
}
<|endoftext|> |
<commit_before>#ifndef VXL_QUAT_HPP
# define VXL_QUAT_HPP
# pragma once
#include "matrix.hpp"
namespace vxl
{
template <typename T>
struct quat
{
typename vector_traits<T, 4>::vector_type data_;
// element access
constexpr auto operator()(unsigned const i) const noexcept
{
return data_[i];
}
constexpr void set_element(unsigned const i, T const v) noexcept
{
data_[i] = v;
}
// conversion
constexpr auto& ref() noexcept { return data_; }
constexpr auto& ref() const noexcept { return data_; }
};
template <typename T>
inline constexpr quat<T> operator+(quat<T> const& a,
quat<T> const& b) noexcept
{
return { a.data_ + b.data_ };
}
template <typename T>
inline constexpr quat<T> operator-(quat<T> const& a,
quat<T> const& b) noexcept
{
return { a.data_ - b.data_ };
}
template <typename T>
//__attribute__ ((noinline))
inline constexpr quat<T> operator*(
quat<T> const& l, quat<T> const& r) noexcept
{
// l(0)r(3) + l(1)r(2) - l(2)r(1) + l(3)r(0)
// -l(0)r(2) + l(1)r(3) + l(2)r(0) + l(3)r(1)
// l(0)r(1) - l(1)r(0) + l(2)r(3) + l(3)r(2)
// -l(0)r(0) - l(1)r(1) - l(2)r(2) + l(3)r(3)
using int_value_type = typename vector_traits<T, 4>::int_value_type;
using int_vector_type = typename vector_traits<T, 4>::int_vector_type;
#if defined(__clang__)
auto const t1(
l.data_ *
__builtin_shufflevector(r.data_, r.data_, 3, 3, 3, 3)
);
auto const t2(
__builtin_shufflevector(l.data_, l.data_, 1, 2, 0, 2) *
__builtin_shufflevector(r.data_, r.data_, 2, 0, 1, 2)
);
auto const t3(
__builtin_shufflevector(l.data_, l.data_, 3, 3, 3, 1) *
__builtin_shufflevector(r.data_, r.data_, 0, 1, 2, 1)
);
auto const t4(
__builtin_shufflevector(l.data_, l.data_, 2, 0, 1, 0) *
__builtin_shufflevector(r.data_, r.data_, 1, 2, 0, 0)
);
#else
auto const t1(
l.data_ *
__builtin_shuffle(r.data_, int_vector_type{3, 3, 3, 3})
);
auto const t2(
__builtin_shuffle(l.data_, int_vector_type{1, 2, 0, 2}) *
__builtin_shuffle(r.data_, int_vector_type{2, 0, 1, 2})
);
auto const t3(
__builtin_shuffle(l.data_, int_vector_type{3, 3, 3, 1}) *
__builtin_shuffle(r.data_, int_vector_type{0, 1, 2, 1})
);
auto const t4(
__builtin_shuffle(l.data_, int_vector_type{2, 0, 1, 0}) *
__builtin_shuffle(r.data_, int_vector_type{1, 2, 0, 0})
);
#endif
// negate the sign bit
constexpr int_vector_type mask{
0, 0, 0, 1 << (8 * sizeof(int_value_type) - 1)
};
return {
t1 +
decltype(t2)(int_vector_type(t2 + t3) ^ mask) -
t4
};
}
template <typename T>
inline constexpr auto& operator+=(quat<T>& a, quat<T> const& b) noexcept
{
return a.data_ += b.data_, a;
}
template <typename T>
inline constexpr auto& operator-=(quat<T>& a, quat<T> const& b) noexcept
{
return a.data_ -= b.data_, a;
}
// comparison
template <typename T>
inline bool operator==(quat<T> const& l, quat<T> const& r) noexcept
{
return detail::vector::all_zeros<T, 4>(l.data_ != r.data_,
std::make_index_sequence<detail::vector::log2(4)>()
);
}
template <typename T>
inline constexpr bool operator!=(quat<T> const& l, quat<T> const& r) noexcept
{
return !operator==(l, r);
}
// scalar part
template <typename T>
inline constexpr auto scalar(quat<T> const& x) noexcept
{
return x.data_[3];
}
namespace detail
{
namespace quat
{
template <typename T, unsigned N, std::size_t ...Is>
constexpr inline auto scalar_vector(vxl::quat<T> const& x,
std::index_sequence<Is...>) noexcept
{
#if defined(__clang__)
return __builtin_shufflevector(x.data_, x.data_, (Is, 3)...);
#else
using int_vector_type = typename vector_traits<T, N>::int_vector_type;
return __builtin_shuffle(x.data_, int_vector_type{(Is, 3)...});
#endif
}
}
}
template <typename T, unsigned N>
constexpr inline auto scalar_vector(quat<T> const& x) noexcept
{
return detail::quat::scalar_vector<T, N>(x,
std::make_index_sequence<4>()
);
}
// vector part
template <typename T>
constexpr inline auto vec(quat<T> const& x) noexcept
{
return vector<T, 3>{x.data_};
}
// conjugation
template <typename T>
inline constexpr void conjugate(quat<T>& x) noexcept
{
using int_vector_type = typename vector_traits<T, 4>::int_vector_type;
using vector_type = typename vector_traits<T, 4>::vector_type;
x.data_ = vector_type(
int_vector_type(x.data_) ^
int_vector_type(vector_type{T(-.0), T(-.0), T(-.0), T(.0)})
);
}
template <typename T>
inline constexpr quat<T> conjugated(quat<T> const& x) noexcept
{
using int_vector_type = typename vector_traits<T, 4>::int_vector_type;
using vector_type = typename vector_traits<T, 4>::vector_type;
return {
vector_type(
int_vector_type(x.data_) ^
int_vector_type(vector_type{T(-.0), T(-.0), T(-.0), T(.0)})
)
};
}
template <typename T>
inline constexpr auto norm2(quat<T> const& x) noexcept
{
vector<T, 4> const q{x.data_};
return dot(q, q);
}
}
// stream operators
template <typename T>
std::ostream& operator<<(std::ostream& os, vxl::quat<T> const& v)
{
os << '(';
for (unsigned i{}; i != 3; ++i)
{
os << v.data_[i] << ", ";
}
return os << v.data_[3] << ')';
}
#endif // VXL_QUAT_HPP
<commit_msg>some fixes<commit_after>#ifndef VXL_QUAT_HPP
# define VXL_QUAT_HPP
# pragma once
#include "matrix.hpp"
namespace vxl
{
template <typename T>
struct quat
{
typename vector_traits<T, 4>::vector_type data_;
// element access
constexpr auto operator()(unsigned const i) const noexcept
{
return data_[i];
}
constexpr void set_element(unsigned const i, T const v) noexcept
{
data_[i] = v;
}
// conversion
constexpr auto& ref() noexcept { return data_; }
constexpr auto& ref() const noexcept { return data_; }
};
template <typename T>
inline constexpr quat<T> operator+(quat<T> const& a,
quat<T> const& b) noexcept
{
return { a.data_ + b.data_ };
}
template <typename T>
inline constexpr quat<T> operator-(quat<T> const& a,
quat<T> const& b) noexcept
{
return { a.data_ - b.data_ };
}
template <typename T>
//__attribute__ ((noinline))
inline constexpr quat<T> operator*(
quat<T> const& l, quat<T> const& r) noexcept
{
// l(0)r(3) + l(1)r(2) - l(2)r(1) + l(3)r(0)
// -l(0)r(2) + l(1)r(3) + l(2)r(0) + l(3)r(1)
// l(0)r(1) - l(1)r(0) + l(2)r(3) + l(3)r(2)
// -l(0)r(0) - l(1)r(1) - l(2)r(2) + l(3)r(3)
using int_value_type = typename vector_traits<T, 4>::int_value_type;
using int_vector_type = typename vector_traits<T, 4>::int_vector_type;
#if defined(__clang__)
auto const t1(
l.data_ *
__builtin_shufflevector(r.data_, r.data_, 3, 3, 3, 3)
);
auto const t2(
__builtin_shufflevector(l.data_, l.data_, 1, 2, 0, 2) *
__builtin_shufflevector(r.data_, r.data_, 2, 0, 1, 2)
);
auto const t3(
__builtin_shufflevector(l.data_, l.data_, 3, 3, 3, 1) *
__builtin_shufflevector(r.data_, r.data_, 0, 1, 2, 1)
);
auto const t4(
__builtin_shufflevector(l.data_, l.data_, 2, 0, 1, 0) *
__builtin_shufflevector(r.data_, r.data_, 1, 2, 0, 0)
);
#else
auto const t1(
l.data_ *
__builtin_shuffle(r.data_, int_vector_type{3, 3, 3, 3})
);
auto const t2(
__builtin_shuffle(l.data_, int_vector_type{1, 2, 0, 2}) *
__builtin_shuffle(r.data_, int_vector_type{2, 0, 1, 2})
);
auto const t3(
__builtin_shuffle(l.data_, int_vector_type{3, 3, 3, 1}) *
__builtin_shuffle(r.data_, int_vector_type{0, 1, 2, 1})
);
auto const t4(
__builtin_shuffle(l.data_, int_vector_type{2, 0, 1, 0}) *
__builtin_shuffle(r.data_, int_vector_type{1, 2, 0, 0})
);
#endif
return {
t1 +
decltype(t2)(int_vector_type(t2 + t3) ^
int_vector_type{
0, 0, 0, 1 << (8 * sizeof(int_value_type) - 1)
}
) -
t4
};
}
template <typename T>
inline constexpr auto& operator+=(quat<T>& a, quat<T> const& b) noexcept
{
return a.data_ += b.data_, a;
}
template <typename T>
inline constexpr auto& operator-=(quat<T>& a, quat<T> const& b) noexcept
{
return a.data_ -= b.data_, a;
}
// comparison
template <typename T>
inline bool operator==(quat<T> const& l, quat<T> const& r) noexcept
{
return detail::vector::all_zeros<T, 4>(l.data_ != r.data_,
std::make_index_sequence<detail::vector::log2(4)>()
);
}
template <typename T>
inline constexpr bool operator!=(quat<T> const& l, quat<T> const& r) noexcept
{
return !operator==(l, r);
}
// scalar part
template <typename T>
inline constexpr auto scalar(quat<T> const& x) noexcept
{
return x.data_[3];
}
namespace detail
{
namespace quat
{
template <typename T, unsigned N, std::size_t ...Is>
constexpr inline auto scalar_vector(vxl::quat<T> const& x,
std::index_sequence<Is...>) noexcept
{
#if defined(__clang__)
return __builtin_shufflevector(x.data_, x.data_, (3 + Is - Is)...);
#else
using int_vector_type = typename vector_traits<T, N>::int_vector_type;
return __builtin_shuffle(x.data_, int_vector_type{(3 + Is - Is)...});
#endif
}
}
}
template <typename T, unsigned N>
constexpr inline auto scalar_vector(quat<T> const& x) noexcept
{
return detail::quat::scalar_vector<T, N>(x,
std::make_index_sequence<4>()
);
}
// vector part
template <typename T>
constexpr inline auto vec(quat<T> const& x) noexcept
{
return vector<T, 3>{x.data_};
}
// conjugation
template <typename T>
inline constexpr void conjugate(quat<T>& x) noexcept
{
using int_vector_type = typename vector_traits<T, 4>::int_vector_type;
using vector_type = typename vector_traits<T, 4>::vector_type;
x.data_ = vector_type(
int_vector_type(x.data_) ^
int_vector_type(vector_type{T(-.0), T(-.0), T(-.0), T(.0)})
);
}
template <typename T>
inline constexpr quat<T> conjugated(quat<T> const& x) noexcept
{
using int_vector_type = typename vector_traits<T, 4>::int_vector_type;
using vector_type = typename vector_traits<T, 4>::vector_type;
return {
vector_type(
int_vector_type(x.data_) ^
int_vector_type(vector_type{T(-.0), T(-.0), T(-.0), T(.0)})
)
};
}
template <typename T>
inline constexpr auto norm2(quat<T> const& x) noexcept
{
vector<T, 4> const q{x.data_};
return dot(q, q);
}
}
// stream operators
template <typename T>
std::ostream& operator<<(std::ostream& os, vxl::quat<T> const& v)
{
os << '(';
for (unsigned i{}; i != 3; ++i)
{
os << v.data_[i] << ", ";
}
return os << v.data_[3] << ')';
}
#endif // VXL_QUAT_HPP
<|endoftext|> |
<commit_before>#if defined(TEMPEST_BUILD_DIRECTX12)
#include <Tempest/Log>
#include <iostream>
#include "guid.h"
#include "dxdevice.h"
#include "dxbuffer.h"
#include "dxtexture.h"
#include "dxshader.h"
#include "dxpipeline.h"
#include "builtin_shader.h"
using namespace Tempest;
using namespace Tempest::Detail;
DxDevice::DxDevice(IDXGIAdapter1& adapter, const ApiEntry& dllApi)
:dllApi(dllApi) {
dxAssert(dllApi.D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, uuid<ID3D12Device>(), reinterpret_cast<void**>(&device)));
ComPtr<ID3D12InfoQueue> pInfoQueue;
if(SUCCEEDED(device->QueryInterface(uuid<ID3D12InfoQueue>(),reinterpret_cast<void**>(&pInfoQueue)))) {
// Suppress messages based on their severity level
D3D12_MESSAGE_SEVERITY severities[] = {
D3D12_MESSAGE_SEVERITY_INFO
};
D3D12_MESSAGE_ID denyIds[] = {
// I'm really not sure how to avoid this message.
D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
// blit shader uses no vbo
D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_EMPTY_LAYOUT,
};
D3D12_INFO_QUEUE_FILTER filter = {};
filter.DenyList.NumSeverities = _countof(severities);
filter.DenyList.pSeverityList = severities;
filter.DenyList.NumIDs = _countof(denyIds);
filter.DenyList.pIDList = denyIds;
dxAssert(pInfoQueue->PushStorageFilter(&filter));
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, false);
}
DXGI_ADAPTER_DESC desc={};
adapter.GetDesc(&desc);
getProp(adapter,*device,props);
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
dxAssert(device->CreateCommandQueue(&queueDesc, uuid<ID3D12CommandQueue>(), reinterpret_cast<void**>(&cmdQueue)));
allocator.setDevice(*this);
dxAssert(device->CreateFence(DxFence::Waiting, D3D12_FENCE_FLAG_NONE,
uuid<ID3D12Fence>(),
reinterpret_cast<void**>(&idleFence)));
idleEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
static bool internalShaders = true;
if(internalShaders) {
{
RenderState st;
st.setZTestMode (RenderState::ZTestMode::Always);
st.setCullFaceMode(RenderState::CullMode::NoCull);
auto blitVs = DSharedPtr<DxShader*>(new DxShader(blit_vert_sprv,sizeof(blit_vert_sprv)));
auto blitFs = DSharedPtr<DxShader*>(new DxShader(blit_frag_sprv,sizeof(blit_frag_sprv)));
DxShader* blitSh[2] = {blitVs.handler, blitFs.handler};
blitLayout = DSharedPtr<DxPipelineLay*>(new DxPipelineLay(*this,&blitFs.handler->lay));
blit = DSharedPtr<DxPipeline*> (new DxPipeline (*this,st,0,Triangles,*blitLayout.handler,blitSh,2));
}
{
auto copyCs = DSharedPtr<DxShader*>(new DxShader(copy_comp_sprv,sizeof(copy_comp_sprv)));
copyLayout = DSharedPtr<DxPipelineLay*> (new DxPipelineLay(*this,©Cs.handler->lay));
copy = DSharedPtr<DxCompPipeline*>(new DxCompPipeline(*this,*copyLayout.handler,*copyCs.handler));
}
{
auto copyCs = DSharedPtr<DxShader*>(new DxShader(copy_s_comp_sprv,sizeof(copy_s_comp_sprv)));
copyS = DSharedPtr<DxCompPipeline*>(new DxCompPipeline(*this,*copyLayout.handler,*copyCs.handler));
}
}
data.reset(new DataMgr(*this));
}
DxDevice::~DxDevice() {
blit = DSharedPtr<DxPipeline*>();
blitLayout = DSharedPtr<DxPipelineLay*>();
data.reset();
CloseHandle(idleEvent);
}
void DxDevice::getProp(IDXGIAdapter1& adapter, ID3D12Device& dev, AbstractGraphicsApi::Props& prop) {
DXGI_ADAPTER_DESC1 desc={};
adapter.GetDesc1(&desc);
return getProp(desc,dev,prop);
}
void DxDevice::getProp(DXGI_ADAPTER_DESC1& desc, ID3D12Device& dev, AbstractGraphicsApi::Props& prop) {
for(size_t i=0;i<sizeof(prop.name);++i) {
WCHAR c = desc.Description[i];
if(c==0)
break;
if(('0'<=c && c<='9') || ('a'<=c && c<='z') || ('A'<=c && c<='Z') ||
c=='(' || c==')' || c=='_' || c=='[' || c==']' || c=='{' || c=='}' || c==' ')
prop.name[i] = char(c); else
prop.name[i] = '?';
}
prop.name[sizeof(prop.name)-1]='\0';
// https://docs.microsoft.com/en-us/windows/win32/direct3ddxgi/hardware-support-for-direct3d-12-0-formats
// NOTE: TextureFormat::RGB32F is not supported, because of mip-maps
static const TextureFormat smp[] = {TextureFormat::R8, TextureFormat::RG8, TextureFormat::RGBA8,
TextureFormat::R16, TextureFormat::RG16, TextureFormat::RGBA16,
TextureFormat::R32F, TextureFormat::RG32F, /*TextureFormat::RGB32F,*/ TextureFormat::RGBA32F,
TextureFormat::DXT1, TextureFormat::DXT3, TextureFormat::DXT5
};
static const TextureFormat att[] = {TextureFormat::R8, TextureFormat::RG8, TextureFormat::RGBA8,
TextureFormat::R16, TextureFormat::RG16, TextureFormat::RGBA16,
TextureFormat::R32F, TextureFormat::RG32F, TextureFormat::RGBA32F
};
static const TextureFormat sso[] = {TextureFormat::R8, TextureFormat::RG8, TextureFormat::RGBA8,
TextureFormat::R16, TextureFormat::RG16, TextureFormat::RGBA16,
TextureFormat::R32F, TextureFormat::RGBA32F
};
static const TextureFormat ds[] = {TextureFormat::Depth16, TextureFormat::Depth24x8, TextureFormat::Depth24S8};
uint64_t smpBit = 0, attBit = 0, dsBit = 0, storBit = 0;
for(auto& i:smp)
smpBit |= uint64_t(1) << uint64_t(i);
for(auto& i:att)
attBit |= uint64_t(1) << uint64_t(i);
for(auto& i:ds) {
dsBit |= uint64_t(1) << uint64_t(i);
smpBit |= uint64_t(1) << uint64_t(i);
}
for(auto& i:sso)
storBit |= uint64_t(1) << uint64_t(i);
prop.setSamplerFormats(smpBit);
prop.setAttachFormats (attBit);
prop.setDepthFormats (dsBit);
prop.setStorageFormats(storBit);
// TODO: buffer limits
//prop.vbo.maxRange = ;
prop.ssbo.offsetAlign = 256;
//prop.ssbo.maxRange = size_t(prop.limits.maxStorageBufferRange);
prop.ubo.maxRange = D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT*4;
prop.ubo.offsetAlign = 256;
prop.push.maxRange = 256;
prop.anisotropy = true;
prop.maxAnisotropy = 16;
prop.tesselationShader = false; // TODO: dxil compiller crashes
prop.storeAndAtomicVs = true;
prop.storeAndAtomicFs = true;
prop.mrt.maxColorAttachments = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT;
prop.compute.maxGroups.x = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
prop.compute.maxGroups.y = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
prop.compute.maxGroups.z = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
prop.compute.maxGroupSize.x = D3D12_CS_THREAD_GROUP_MAX_X;
prop.compute.maxGroupSize.y = D3D12_CS_THREAD_GROUP_MAX_Y;
prop.compute.maxGroupSize.z = D3D12_CS_THREAD_GROUP_MAX_Z;
if(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
prop.type = DeviceType::Cpu;
} else {
D3D12_FEATURE_DATA_ARCHITECTURE arch = {};
if(SUCCEEDED(dev.CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE, &arch, sizeof(arch))))
prop.type = arch.UMA ? DeviceType::Integrated : DeviceType::Discrete;
}
D3D12_FEATURE_DATA_D3D12_OPTIONS5 feature5 = {};
if(SUCCEEDED(dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &feature5, sizeof(feature5)))) {
prop.raytracing.rayQuery = (feature5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED);
//prop.raytracing.rayQuery = false; // TODO: dxil compiller
}
D3D12_FEATURE_DATA_D3D12_OPTIONS7 feature7 = {};
if(SUCCEEDED(dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &feature7, sizeof(feature7)))) {
// prop.meshlets.taskShader = feature7.MeshShaderTier!=D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
// prop.meshlets.meshShader = feature7.MeshShaderTier!=D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
// props.meshlets.maxMeshGroups = meshProperties.maxDrawMeshTasksCount;
// props.meshlets.maxMeshGroupSize = meshProperties.maxMeshWorkGroupSize[0];
}
prop.bindless.nonUniformIndexing = true; // SM5.1
}
void DxDevice::waitData() {
data->wait();
}
void Detail::DxDevice::waitIdle() {
std::lock_guard<SpinLock> guard(syncCmdQueue);
dxAssert(cmdQueue->Signal(idleFence.get(),DxFence::Ready));
dxAssert(idleFence->SetEventOnCompletion(DxFence::Ready,idleEvent));
WaitForSingleObjectEx(idleEvent, INFINITE, FALSE);
dxAssert(idleFence->Signal(DxFence::Waiting));
}
void DxDevice::submit(DxCommandBuffer& cmdBuffer, DxFence& sync) {
sync.reset();
std::lock_guard<SpinLock> guard(syncCmdQueue);
ID3D12CommandList* cmd[] = {cmdBuffer.get()};
cmdQueue->ExecuteCommandLists(1, cmd);
sync.signal(*cmdQueue);
}
#endif
<commit_msg>DX12: disable bindless for now<commit_after>#if defined(TEMPEST_BUILD_DIRECTX12)
#include <Tempest/Log>
#include <iostream>
#include "guid.h"
#include "dxdevice.h"
#include "dxbuffer.h"
#include "dxtexture.h"
#include "dxshader.h"
#include "dxpipeline.h"
#include "builtin_shader.h"
using namespace Tempest;
using namespace Tempest::Detail;
DxDevice::DxDevice(IDXGIAdapter1& adapter, const ApiEntry& dllApi)
:dllApi(dllApi) {
dxAssert(dllApi.D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, uuid<ID3D12Device>(), reinterpret_cast<void**>(&device)));
ComPtr<ID3D12InfoQueue> pInfoQueue;
if(SUCCEEDED(device->QueryInterface(uuid<ID3D12InfoQueue>(),reinterpret_cast<void**>(&pInfoQueue)))) {
// Suppress messages based on their severity level
D3D12_MESSAGE_SEVERITY severities[] = {
D3D12_MESSAGE_SEVERITY_INFO
};
D3D12_MESSAGE_ID denyIds[] = {
// I'm really not sure how to avoid this message.
D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
// blit shader uses no vbo
D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_EMPTY_LAYOUT,
};
D3D12_INFO_QUEUE_FILTER filter = {};
filter.DenyList.NumSeverities = _countof(severities);
filter.DenyList.pSeverityList = severities;
filter.DenyList.NumIDs = _countof(denyIds);
filter.DenyList.pIDList = denyIds;
dxAssert(pInfoQueue->PushStorageFilter(&filter));
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, false);
}
DXGI_ADAPTER_DESC desc={};
adapter.GetDesc(&desc);
getProp(adapter,*device,props);
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
dxAssert(device->CreateCommandQueue(&queueDesc, uuid<ID3D12CommandQueue>(), reinterpret_cast<void**>(&cmdQueue)));
allocator.setDevice(*this);
dxAssert(device->CreateFence(DxFence::Waiting, D3D12_FENCE_FLAG_NONE,
uuid<ID3D12Fence>(),
reinterpret_cast<void**>(&idleFence)));
idleEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
static bool internalShaders = true;
if(internalShaders) {
{
RenderState st;
st.setZTestMode (RenderState::ZTestMode::Always);
st.setCullFaceMode(RenderState::CullMode::NoCull);
auto blitVs = DSharedPtr<DxShader*>(new DxShader(blit_vert_sprv,sizeof(blit_vert_sprv)));
auto blitFs = DSharedPtr<DxShader*>(new DxShader(blit_frag_sprv,sizeof(blit_frag_sprv)));
DxShader* blitSh[2] = {blitVs.handler, blitFs.handler};
blitLayout = DSharedPtr<DxPipelineLay*>(new DxPipelineLay(*this,&blitFs.handler->lay));
blit = DSharedPtr<DxPipeline*> (new DxPipeline (*this,st,0,Triangles,*blitLayout.handler,blitSh,2));
}
{
auto copyCs = DSharedPtr<DxShader*>(new DxShader(copy_comp_sprv,sizeof(copy_comp_sprv)));
copyLayout = DSharedPtr<DxPipelineLay*> (new DxPipelineLay(*this,©Cs.handler->lay));
copy = DSharedPtr<DxCompPipeline*>(new DxCompPipeline(*this,*copyLayout.handler,*copyCs.handler));
}
{
auto copyCs = DSharedPtr<DxShader*>(new DxShader(copy_s_comp_sprv,sizeof(copy_s_comp_sprv)));
copyS = DSharedPtr<DxCompPipeline*>(new DxCompPipeline(*this,*copyLayout.handler,*copyCs.handler));
}
}
data.reset(new DataMgr(*this));
}
DxDevice::~DxDevice() {
blit = DSharedPtr<DxPipeline*>();
blitLayout = DSharedPtr<DxPipelineLay*>();
data.reset();
CloseHandle(idleEvent);
}
void DxDevice::getProp(IDXGIAdapter1& adapter, ID3D12Device& dev, AbstractGraphicsApi::Props& prop) {
DXGI_ADAPTER_DESC1 desc={};
adapter.GetDesc1(&desc);
return getProp(desc,dev,prop);
}
void DxDevice::getProp(DXGI_ADAPTER_DESC1& desc, ID3D12Device& dev, AbstractGraphicsApi::Props& prop) {
for(size_t i=0;i<sizeof(prop.name);++i) {
WCHAR c = desc.Description[i];
if(c==0)
break;
if(('0'<=c && c<='9') || ('a'<=c && c<='z') || ('A'<=c && c<='Z') ||
c=='(' || c==')' || c=='_' || c=='[' || c==']' || c=='{' || c=='}' || c==' ')
prop.name[i] = char(c); else
prop.name[i] = '?';
}
prop.name[sizeof(prop.name)-1]='\0';
// https://docs.microsoft.com/en-us/windows/win32/direct3ddxgi/hardware-support-for-direct3d-12-0-formats
// NOTE: TextureFormat::RGB32F is not supported, because of mip-maps
static const TextureFormat smp[] = {TextureFormat::R8, TextureFormat::RG8, TextureFormat::RGBA8,
TextureFormat::R16, TextureFormat::RG16, TextureFormat::RGBA16,
TextureFormat::R32F, TextureFormat::RG32F, /*TextureFormat::RGB32F,*/ TextureFormat::RGBA32F,
TextureFormat::DXT1, TextureFormat::DXT3, TextureFormat::DXT5
};
static const TextureFormat att[] = {TextureFormat::R8, TextureFormat::RG8, TextureFormat::RGBA8,
TextureFormat::R16, TextureFormat::RG16, TextureFormat::RGBA16,
TextureFormat::R32F, TextureFormat::RG32F, TextureFormat::RGBA32F
};
static const TextureFormat sso[] = {TextureFormat::R8, TextureFormat::RG8, TextureFormat::RGBA8,
TextureFormat::R16, TextureFormat::RG16, TextureFormat::RGBA16,
TextureFormat::R32F, TextureFormat::RGBA32F
};
static const TextureFormat ds[] = {TextureFormat::Depth16, TextureFormat::Depth24x8, TextureFormat::Depth24S8};
uint64_t smpBit = 0, attBit = 0, dsBit = 0, storBit = 0;
for(auto& i:smp)
smpBit |= uint64_t(1) << uint64_t(i);
for(auto& i:att)
attBit |= uint64_t(1) << uint64_t(i);
for(auto& i:ds) {
dsBit |= uint64_t(1) << uint64_t(i);
smpBit |= uint64_t(1) << uint64_t(i);
}
for(auto& i:sso)
storBit |= uint64_t(1) << uint64_t(i);
prop.setSamplerFormats(smpBit);
prop.setAttachFormats (attBit);
prop.setDepthFormats (dsBit);
prop.setStorageFormats(storBit);
// TODO: buffer limits
//prop.vbo.maxRange = ;
prop.ssbo.offsetAlign = 256;
//prop.ssbo.maxRange = size_t(prop.limits.maxStorageBufferRange);
prop.ubo.maxRange = D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT*4;
prop.ubo.offsetAlign = 256;
prop.push.maxRange = 256;
prop.anisotropy = true;
prop.maxAnisotropy = 16;
prop.tesselationShader = false; // TODO: dxil compiller crashes
prop.storeAndAtomicVs = true;
prop.storeAndAtomicFs = true;
prop.mrt.maxColorAttachments = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT;
prop.compute.maxGroups.x = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
prop.compute.maxGroups.y = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
prop.compute.maxGroups.z = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
prop.compute.maxGroupSize.x = D3D12_CS_THREAD_GROUP_MAX_X;
prop.compute.maxGroupSize.y = D3D12_CS_THREAD_GROUP_MAX_Y;
prop.compute.maxGroupSize.z = D3D12_CS_THREAD_GROUP_MAX_Z;
if(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
prop.type = DeviceType::Cpu;
} else {
D3D12_FEATURE_DATA_ARCHITECTURE arch = {};
if(SUCCEEDED(dev.CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE, &arch, sizeof(arch))))
prop.type = arch.UMA ? DeviceType::Integrated : DeviceType::Discrete;
}
D3D12_FEATURE_DATA_D3D12_OPTIONS5 feature5 = {};
if(SUCCEEDED(dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &feature5, sizeof(feature5)))) {
prop.raytracing.rayQuery = (feature5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED);
//prop.raytracing.rayQuery = false; // TODO: dxil compiller
}
D3D12_FEATURE_DATA_D3D12_OPTIONS7 feature7 = {};
if(SUCCEEDED(dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &feature7, sizeof(feature7)))) {
// prop.meshlets.taskShader = feature7.MeshShaderTier!=D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
// prop.meshlets.meshShader = feature7.MeshShaderTier!=D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
// props.meshlets.maxMeshGroups = meshProperties.maxDrawMeshTasksCount;
// props.meshlets.maxMeshGroupSize = meshProperties.maxMeshWorkGroupSize[0];
}
prop.bindless.nonUniformIndexing = true; // SM5.1
prop.bindless.nonUniformIndexing = false; // TEST: DirectX12.Bindless2
}
void DxDevice::waitData() {
data->wait();
}
void Detail::DxDevice::waitIdle() {
std::lock_guard<SpinLock> guard(syncCmdQueue);
dxAssert(cmdQueue->Signal(idleFence.get(),DxFence::Ready));
dxAssert(idleFence->SetEventOnCompletion(DxFence::Ready,idleEvent));
WaitForSingleObjectEx(idleEvent, INFINITE, FALSE);
dxAssert(idleFence->Signal(DxFence::Waiting));
}
void DxDevice::submit(DxCommandBuffer& cmdBuffer, DxFence& sync) {
sync.reset();
std::lock_guard<SpinLock> guard(syncCmdQueue);
ID3D12CommandList* cmd[] = {cmdBuffer.get()};
cmdQueue->ExecuteCommandLists(1, cmd);
sync.signal(*cmdQueue);
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_test.h"
#include "build/build_config.h"
class LocaleTestsBase : public UITest {
public:
LocaleTestsBase() : UITest(), old_lc_all_(NULL) {
}
protected:
void RestoreLcAllEnvironment() {
#if defined(OS_LINUX)
if (old_lc_all_) {
setenv("LC_ALL", old_lc_all_, 1);
} else {
unsetenv("LC_ALL");
}
#endif
};
const char* old_lc_all_;
};
class LocaleTestsDa : public LocaleTestsBase {
public:
LocaleTestsDa() : LocaleTestsBase() {
launch_arguments_.AppendSwitchWithValue("lang", "da");
// Linux doesn't use --lang, it only uses environment variables to set the
// language.
#if defined(OS_LINUX)
old_lc_all_ = getenv("LC_ALL");
setenv("LC_ALL", "da_DK.UTF-8", 1);
#endif
}
};
class LocaleTestsHe : public LocaleTestsBase {
public:
LocaleTestsHe() : LocaleTestsBase() {
launch_arguments_.AppendSwitchWithValue("lang", "he");
#if defined(OS_LINUX)
old_lc_all_ = getenv("LC_ALL");
setenv("LC_ALL", "he_IL.UTF-8", 1);
#endif
}
};
class LocaleTestsZhTw : public LocaleTestsBase {
public:
LocaleTestsZhTw() : LocaleTestsBase() {
launch_arguments_.AppendSwitchWithValue("lang", "zh-TW");
#if defined(OS_LINUX)
old_lc_all_ = getenv("LC_ALL");
setenv("LC_ALL", "zh_TW.UTF-8", 1);
#endif
}
};
#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
// Just making sure we can start/shutdown cleanly.
RestoreLcAllEnvironment();
}
TEST_F(LocaleTestsHe, TestStart) {
// Just making sure we can start/shutdown cleanly.
RestoreLcAllEnvironment();
}
TEST_F(LocaleTestsZhTw, TestStart) {
// Just making sure we can start/shutdown cleanly.
RestoreLcAllEnvironment();
}
#endif
<commit_msg>Re-enable locale tests on Mac. They work fine now.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_test.h"
#include "build/build_config.h"
class LocaleTestsBase : public UITest {
public:
LocaleTestsBase() : UITest(), old_lc_all_(NULL) {
}
protected:
void RestoreLcAllEnvironment() {
#if defined(OS_LINUX)
if (old_lc_all_) {
setenv("LC_ALL", old_lc_all_, 1);
} else {
unsetenv("LC_ALL");
}
#endif
};
const char* old_lc_all_;
};
class LocaleTestsDa : public LocaleTestsBase {
public:
LocaleTestsDa() : LocaleTestsBase() {
launch_arguments_.AppendSwitchWithValue("lang", "da");
// Linux doesn't use --lang, it only uses environment variables to set the
// language.
#if defined(OS_LINUX)
old_lc_all_ = getenv("LC_ALL");
setenv("LC_ALL", "da_DK.UTF-8", 1);
#endif
}
};
class LocaleTestsHe : public LocaleTestsBase {
public:
LocaleTestsHe() : LocaleTestsBase() {
launch_arguments_.AppendSwitchWithValue("lang", "he");
#if defined(OS_LINUX)
old_lc_all_ = getenv("LC_ALL");
setenv("LC_ALL", "he_IL.UTF-8", 1);
#endif
}
};
class LocaleTestsZhTw : public LocaleTestsBase {
public:
LocaleTestsZhTw() : LocaleTestsBase() {
launch_arguments_.AppendSwitchWithValue("lang", "zh-TW");
#if defined(OS_LINUX)
old_lc_all_ = getenv("LC_ALL");
setenv("LC_ALL", "zh_TW.UTF-8", 1);
#endif
}
};
TEST_F(LocaleTestsDa, TestStart) {
// Just making sure we can start/shutdown cleanly.
RestoreLcAllEnvironment();
}
TEST_F(LocaleTestsHe, TestStart) {
// Just making sure we can start/shutdown cleanly.
RestoreLcAllEnvironment();
}
TEST_F(LocaleTestsZhTw, TestStart) {
// Just making sure we can start/shutdown cleanly.
RestoreLcAllEnvironment();
}
<|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 "chrome/browser/low_memory_observer.h"
#include <fcntl.h>
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "base/timer.h"
#include "chrome/browser/oom_priority_manager.h"
#include "content/public/browser/browser_thread.h"
#include "chrome/browser/browser_process.h"
using content::BrowserThread;
namespace browser {
namespace {
// This is the file that will exist if low memory notification is available
// on the device. Whenever it becomes readable, it signals a low memory
// condition.
const char kLowMemFile[] = "/dev/chromeos-low-mem";
// This is the minimum amount of time in milliseconds between checks for
// low memory.
const int kLowMemoryCheckTimeoutMs = 750;
} // namespace
////////////////////////////////////////////////////////////////////////////////
// LowMemoryObserverImpl
//
// Does the actual work of observing. The observation work happens on the FILE
// thread, and the discarding of tabs happens on the UI thread.
// If low memory is detected, then we discard a tab, wait
// kLowMemoryCheckTimeoutMs milliseconds and then start watching again to see
// if we're still in a low memory state. This is to keep from discarding all
// tabs the first time we enter the state, because it takes time for the
// tabs to deallocate their memory. A timer isn't the perfect solution, but
// without any reliable indicator that a tab has had all its parts deallocated,
// it's the next best thing.
class LowMemoryObserverImpl
: public base::RefCountedThreadSafe<LowMemoryObserverImpl> {
public:
LowMemoryObserverImpl() : watcher_delegate_(this), file_descriptor_(-1) {}
~LowMemoryObserverImpl() {
StopObservingOnFileThread();
}
// Start watching the low memory file for readability.
// Calls to StartObserving should always be matched with calls to
// StopObserving. This method should only be called from the FILE thread.
void StartObservingOnFileThread();
// Stop watching the low memory file for readability.
// May be safely called if StartObserving has not been called.
// This method should only be called from the FILE thread.
void StopObservingOnFileThread();
private:
// Start a timer to resume watching the low memory file descriptor.
void ScheduleNextObservation();
// Actually start watching the file descriptor.
void StartWatchingDescriptor();
// Delegate to receive events from WatchFileDescriptor.
class FileWatcherDelegate : public MessageLoopForIO::Watcher {
public:
explicit FileWatcherDelegate(LowMemoryObserverImpl* owner)
: owner_(owner) {}
virtual ~FileWatcherDelegate() {}
// Overrides for MessageLoopForIO::Watcher
virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {}
virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
LOG(WARNING) << "Low memory condition detected. Discarding a tab.";
// We can only discard tabs on the UI thread.
base::Callback<void(void)> callback = base::Bind(&DiscardTab);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
owner_->ScheduleNextObservation();
}
// Sends off a discard request to the OomPriorityManager. Must be run on
// the UI thread.
static void DiscardTab() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (g_browser_process && g_browser_process->oom_priority_manager())
g_browser_process->oom_priority_manager()->DiscardTab();
}
private:
LowMemoryObserverImpl* owner_;
DISALLOW_COPY_AND_ASSIGN(FileWatcherDelegate);
};
scoped_ptr<MessageLoopForIO::FileDescriptorWatcher> watcher_;
FileWatcherDelegate watcher_delegate_;
int file_descriptor_;
base::OneShotTimer<LowMemoryObserverImpl> timer_;
DISALLOW_COPY_AND_ASSIGN(LowMemoryObserverImpl);
};
void LowMemoryObserverImpl::StartObservingOnFileThread() {
DCHECK_LE(file_descriptor_, 0)
<< "Attempted to start observation when it was already started.";
DCHECK(watcher_.get() == NULL);
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(MessageLoopForIO::current());
file_descriptor_ = ::open(kLowMemFile, O_RDONLY);
if (file_descriptor_ < 0) {
PLOG(ERROR) << "Unable to open " << kLowMemFile;
return;
}
watcher_.reset(new MessageLoopForIO::FileDescriptorWatcher);
StartWatchingDescriptor();
}
void LowMemoryObserverImpl::StopObservingOnFileThread() {
// If StartObserving failed, StopObserving will still get called.
timer_.Stop();
if (file_descriptor_ >= 0) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
watcher_.reset(NULL);
::close(file_descriptor_);
file_descriptor_ = -1;
}
}
void LowMemoryObserverImpl::ScheduleNextObservation() {
timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kLowMemoryCheckTimeoutMs),
this,
&LowMemoryObserverImpl::StartWatchingDescriptor);
}
void LowMemoryObserverImpl::StartWatchingDescriptor() {
DCHECK(watcher_.get());
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(MessageLoopForIO::current());
if (file_descriptor_ < 0)
return;
if (!MessageLoopForIO::current()->WatchFileDescriptor(
file_descriptor_,
false, // persistent=false: We want it to fire once and reschedule.
MessageLoopForIO::WATCH_READ,
watcher_.get(),
&watcher_delegate_)) {
LOG(ERROR) << "Unable to watch " << kLowMemFile;
}
}
////////////////////////////////////////////////////////////////////////////////
// LowMemoryObserver
LowMemoryObserver::LowMemoryObserver() : observer_(new LowMemoryObserverImpl) {}
LowMemoryObserver::~LowMemoryObserver() { Stop(); }
void LowMemoryObserver::Start() {
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&LowMemoryObserverImpl::StartObservingOnFileThread,
observer_.get()));
}
void LowMemoryObserver::Stop() {
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&LowMemoryObserverImpl::StopObservingOnFileThread,
observer_.get()));
}
} // namespace browser
<commit_msg>Removing some log spam from the low memory observer.<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 "chrome/browser/low_memory_observer.h"
#include <fcntl.h>
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "base/timer.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "chrome/browser/oom_priority_manager.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace browser {
namespace {
// This is the file that will exist if low memory notification is available
// on the device. Whenever it becomes readable, it signals a low memory
// condition.
const char kLowMemFile[] = "/dev/chromeos-low-mem";
// This is the minimum amount of time in milliseconds between checks for
// low memory.
const int kLowMemoryCheckTimeoutMs = 750;
} // namespace
////////////////////////////////////////////////////////////////////////////////
// LowMemoryObserverImpl
//
// Does the actual work of observing. The observation work happens on the FILE
// thread, and the discarding of tabs happens on the UI thread.
// If low memory is detected, then we discard a tab, wait
// kLowMemoryCheckTimeoutMs milliseconds and then start watching again to see
// if we're still in a low memory state. This is to keep from discarding all
// tabs the first time we enter the state, because it takes time for the
// tabs to deallocate their memory. A timer isn't the perfect solution, but
// without any reliable indicator that a tab has had all its parts deallocated,
// it's the next best thing.
class LowMemoryObserverImpl
: public base::RefCountedThreadSafe<LowMemoryObserverImpl> {
public:
LowMemoryObserverImpl() : watcher_delegate_(this), file_descriptor_(-1) {}
~LowMemoryObserverImpl() {
StopObservingOnFileThread();
}
// Start watching the low memory file for readability.
// Calls to StartObserving should always be matched with calls to
// StopObserving. This method should only be called from the FILE thread.
void StartObservingOnFileThread();
// Stop watching the low memory file for readability.
// May be safely called if StartObserving has not been called.
// This method should only be called from the FILE thread.
void StopObservingOnFileThread();
private:
// Start a timer to resume watching the low memory file descriptor.
void ScheduleNextObservation();
// Actually start watching the file descriptor.
void StartWatchingDescriptor();
// Delegate to receive events from WatchFileDescriptor.
class FileWatcherDelegate : public MessageLoopForIO::Watcher {
public:
explicit FileWatcherDelegate(LowMemoryObserverImpl* owner)
: owner_(owner) {}
virtual ~FileWatcherDelegate() {}
// Overrides for MessageLoopForIO::Watcher
virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {}
virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
LOG(WARNING) << "Low memory condition detected. Discarding a tab.";
// We can only discard tabs on the UI thread.
base::Callback<void(void)> callback = base::Bind(&DiscardTab);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
owner_->ScheduleNextObservation();
}
// Sends off a discard request to the OomPriorityManager. Must be run on
// the UI thread.
static void DiscardTab() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (g_browser_process && g_browser_process->oom_priority_manager())
g_browser_process->oom_priority_manager()->DiscardTab();
}
private:
LowMemoryObserverImpl* owner_;
DISALLOW_COPY_AND_ASSIGN(FileWatcherDelegate);
};
scoped_ptr<MessageLoopForIO::FileDescriptorWatcher> watcher_;
FileWatcherDelegate watcher_delegate_;
int file_descriptor_;
base::OneShotTimer<LowMemoryObserverImpl> timer_;
DISALLOW_COPY_AND_ASSIGN(LowMemoryObserverImpl);
};
void LowMemoryObserverImpl::StartObservingOnFileThread() {
DCHECK_LE(file_descriptor_, 0)
<< "Attempted to start observation when it was already started.";
DCHECK(watcher_.get() == NULL);
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(MessageLoopForIO::current());
file_descriptor_ = ::open(kLowMemFile, O_RDONLY);
// Don't report this error unless we're really running on ChromeOS
// to avoid testing spam.
if (file_descriptor_ < 0 &&
chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
PLOG(ERROR) << "Unable to open " << kLowMemFile;
return;
}
watcher_.reset(new MessageLoopForIO::FileDescriptorWatcher);
StartWatchingDescriptor();
}
void LowMemoryObserverImpl::StopObservingOnFileThread() {
// If StartObserving failed, StopObserving will still get called.
timer_.Stop();
if (file_descriptor_ >= 0) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
watcher_.reset(NULL);
::close(file_descriptor_);
file_descriptor_ = -1;
}
}
void LowMemoryObserverImpl::ScheduleNextObservation() {
timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kLowMemoryCheckTimeoutMs),
this,
&LowMemoryObserverImpl::StartWatchingDescriptor);
}
void LowMemoryObserverImpl::StartWatchingDescriptor() {
DCHECK(watcher_.get());
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(MessageLoopForIO::current());
if (file_descriptor_ < 0)
return;
if (!MessageLoopForIO::current()->WatchFileDescriptor(
file_descriptor_,
false, // persistent=false: We want it to fire once and reschedule.
MessageLoopForIO::WATCH_READ,
watcher_.get(),
&watcher_delegate_)) {
LOG(ERROR) << "Unable to watch " << kLowMemFile;
}
}
////////////////////////////////////////////////////////////////////////////////
// LowMemoryObserver
LowMemoryObserver::LowMemoryObserver() : observer_(new LowMemoryObserverImpl) {}
LowMemoryObserver::~LowMemoryObserver() { Stop(); }
void LowMemoryObserver::Start() {
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&LowMemoryObserverImpl::StartObservingOnFileThread,
observer_.get()));
}
void LowMemoryObserver::Stop() {
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&LowMemoryObserverImpl::StopObservingOnFileThread,
observer_.get()));
}
} // namespace browser
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <vector>
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#endif
#define DEF_Server
#include "../Server.h"
const std::string btrfs_cmd="/sbin/btrfs";
CServer *Server;
#ifdef _WIN32
#include <Windows.h>
bool CopyFolder(std::wstring src, std::wstring dst)
{
if(!os_create_dir(dst))
return false;
std::vector<SFile> curr_files=getFiles(src);
for(size_t i=0;i<curr_files.size();++i)
{
if(curr_files[i].isdir)
{
bool b=CopyFolder(src+os_file_sep()+curr_files[i].name, dst+os_file_sep()+curr_files[i].name);
if(!b)
return false;
}
else
{
if(!os_create_hardlink(dst+os_file_sep()+curr_files[i].name, src+os_file_sep()+curr_files[i].name, false, NULL) )
{
BOOL b=CopyFileW( (src+os_file_sep()+curr_files[i].name).c_str(), (dst+os_file_sep()+curr_files[i].name).c_str(), FALSE);
if(!b)
{
return false;
}
}
}
}
return true;
}
#endif
std::string getBackupfolderPath(void)
{
std::string fn;
#ifdef _WIN32
fn=trim(getFile("backupfolder"));
#else
fn=trim(getFile("/etc/urbackup/backupfolder"));
#endif
if(fn.find("\n")!=std::string::npos)
fn=getuntil("\n", fn);
if(fn.find("\r")!=std::string::npos)
fn=getuntil("\r", fn);
return fn;
}
std::string handleFilename(std::string fn)
{
fn=conv_filename(fn);
if(fn=="..")
{
return "";
}
return fn;
}
#ifndef _WIN32
int exec_wait(const std::string& path, ...)
{
va_list vl;
va_start(vl, path);
std::vector<char*> args;
args.push_back(const_cast<char*>(path.c_str()));
while(true)
{
const char* p = va_arg(vl, const char*);
if(p==NULL) break;
args.push_back(const_cast<char*>(p));
}
va_end(vl);
args.push_back(NULL);
pid_t child_pid = fork();
if(child_pid==0)
{
int rc = execvpe(path.c_str(), args.data(), NULL);
exit(rc);
}
else
{
int status;
waitpid(child_pid, &status, 0);
if(WIFEXITED(status))
{
return WEXITSTATUS(status);
}
else
{
return -1;
}
}
}
bool chown_dir(const std::string& dir)
{
passwd* user_info = getpwnam("urbackup");
if(user_info)
{
int rc = chown(dir.c_str(), user_info->pw_uid, user_info->pw_gid);
return rc!=-1;
}
return false;
}
#endif
bool create_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
return os_create_dir(subvolume_folder);
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "create", subvolume_folder.c_str(), NULL);
chown_dir(subvolume_folder);
return rc==0;
#endif
}
bool create_snapshot(std::string snapshot_src, std::string snapshot_dst)
{
#ifdef _WIN32
return CopyFolder(widen(snapshot_src), widen(snapshot_dst));
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "snapshot", snapshot_src.c_str(), snapshot_dst.c_str(), NULL);
chown_dir(snapshot_dst);
return rc==0;
#endif
}
bool remove_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
return os_remove_nonempty_dir(widen(subvolume_folder));
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "delete", subvolume_folder.c_str(), NULL);
return rc==0;
#endif
}
bool is_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
return true;
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "list", subvolume_folder.c_str(), NULL);
return rc==0;
#endif
}
int main(int argc, char *argv[])
{
if(argc<2)
{
std::cout << "Not enough parameters" << std::endl;
return 1;
}
std::string cmd=argv[1];
std::string backupfolder=getBackupfolderPath();
if(backupfolder.empty())
{
std::cout << "Backupfolder not set" << std::endl;
return 1;
}
#ifndef _WIN32
if(seteuid(0)!=0)
{
std::cout << "Cannot become root user" << std::endl;
return 1;
}
#endif
if(cmd=="create")
{
if(argc<4)
{
std::cout << "Not enough parameters for create" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string name=handleFilename(argv[3]);
std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
return create_subvolume(subvolume_folder)?0:1;
}
else if(cmd=="snapshot")
{
if(argc<5)
{
std::cout << "Not enough parameters for snapshot" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string src_name=handleFilename(argv[3]);
std::string dst_name=handleFilename(argv[4]);
std::string subvolume_src_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+src_name;
std::string subvolume_dst_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+dst_name;
return create_snapshot(subvolume_src_folder, subvolume_dst_folder)?0:1;
}
else if(cmd=="remove")
{
if(argc<4)
{
std::cout << "Not enough parameters for remove" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string name=handleFilename(argv[3]);
std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
return remove_subvolume(subvolume_folder)?0:1;
}
else if(cmd=="test")
{
std::string clientdir=backupfolder+os_file_sepn()+"testA54hj5luZtlorr494";
bool create_dir_rc=os_create_dir(clientdir);
if(!create_dir_rc)
{
remove_subvolume(clientdir+os_file_sepn()+"A");
remove_subvolume(clientdir+os_file_sepn()+"B");
os_remove_dir(clientdir);
}
create_dir_rc = create_dir_rc || os_create_dir(clientdir);
if(create_dir_rc)
{
if(!create_subvolume(clientdir+os_file_sepn()+"A") )
{
std::cout << "TEST FAILED: Creating test subvolume failed" << std::endl;
os_remove_dir(clientdir);
return 1;
}
bool suc=true;
if(!create_snapshot(clientdir+os_file_sepn()+"A", clientdir+os_file_sepn()+"B") )
{
std::cout << "TEST FAILED: Creating test snapshot failed" << std::endl;
suc=false;
}
if(suc)
{
writestring("test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test");
if(!os_create_hardlink(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test", true, NULL))
{
std::cout << "TEST FAILED: Creating cross sub-volume reflink failed. Need Linux kernel >= 3.6." << std::endl;
suc=false;
}
else
{
if(getFile(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test")!="test")
{
std::cout << "TEST FAILED: Cannot read reflinked file" << std::endl;
suc=false;
}
}
}
if(!remove_subvolume(clientdir+os_file_sepn()+"A") )
{
std::cout << "TEST FAILED: Removing subvolume A failed" << std::endl;
suc=false;
}
if(!remove_subvolume(clientdir+os_file_sepn()+"B") )
{
std::cout << "TEST FAILED: Removing subvolume B failed" << std::endl;
suc=false;
}
if(!os_remove_dir(clientdir))
{
std::cout << "TEST FAILED: Removing test clientdir failed" << std::endl;
return 1;
}
if(!suc)
{
return 1;
}
}
else
{
std::cout << "TEST FAILED: Creating test clientdir \"" << clientdir << "\" failed" << std::endl;
return 1;
}
std::cout << "TEST OK" << std::endl;
return 0;
}
else if(cmd=="issubvolume")
{
if(argc<4)
{
std::cout << "Not enough parameters for issubvolume" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string name=handleFilename(argv[3]);
std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
return is_subvolume(subvolume_folder)?0:1;
}
else
{
std::cout << "Command not found" << std::endl;
return 1;
}
}
<commit_msg>Build fix for FreeBSD<commit_after>#include <string>
#include <iostream>
#include <vector>
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#endif
#ifdef __FreeBSD__
#define execvpe exect
#endif
#define DEF_Server
#include "../Server.h"
const std::string btrfs_cmd="/sbin/btrfs";
CServer *Server;
#ifdef _WIN32
#include <Windows.h>
bool CopyFolder(std::wstring src, std::wstring dst)
{
if(!os_create_dir(dst))
return false;
std::vector<SFile> curr_files=getFiles(src);
for(size_t i=0;i<curr_files.size();++i)
{
if(curr_files[i].isdir)
{
bool b=CopyFolder(src+os_file_sep()+curr_files[i].name, dst+os_file_sep()+curr_files[i].name);
if(!b)
return false;
}
else
{
if(!os_create_hardlink(dst+os_file_sep()+curr_files[i].name, src+os_file_sep()+curr_files[i].name, false, NULL) )
{
BOOL b=CopyFileW( (src+os_file_sep()+curr_files[i].name).c_str(), (dst+os_file_sep()+curr_files[i].name).c_str(), FALSE);
if(!b)
{
return false;
}
}
}
}
return true;
}
#endif
std::string getBackupfolderPath(void)
{
std::string fn;
#ifdef _WIN32
fn=trim(getFile("backupfolder"));
#else
fn=trim(getFile("/etc/urbackup/backupfolder"));
#endif
if(fn.find("\n")!=std::string::npos)
fn=getuntil("\n", fn);
if(fn.find("\r")!=std::string::npos)
fn=getuntil("\r", fn);
return fn;
}
std::string handleFilename(std::string fn)
{
fn=conv_filename(fn);
if(fn=="..")
{
return "";
}
return fn;
}
#ifndef _WIN32
int exec_wait(const std::string& path, ...)
{
va_list vl;
va_start(vl, path);
std::vector<char*> args;
args.push_back(const_cast<char*>(path.c_str()));
while(true)
{
const char* p = va_arg(vl, const char*);
if(p==NULL) break;
args.push_back(const_cast<char*>(p));
}
va_end(vl);
args.push_back(NULL);
pid_t child_pid = fork();
if(child_pid==0)
{
int rc = execvpe(path.c_str(), args.data(), NULL);
exit(rc);
}
else
{
int status;
waitpid(child_pid, &status, 0);
if(WIFEXITED(status))
{
return WEXITSTATUS(status);
}
else
{
return -1;
}
}
}
bool chown_dir(const std::string& dir)
{
passwd* user_info = getpwnam("urbackup");
if(user_info)
{
int rc = chown(dir.c_str(), user_info->pw_uid, user_info->pw_gid);
return rc!=-1;
}
return false;
}
#endif
bool create_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
return os_create_dir(subvolume_folder);
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "create", subvolume_folder.c_str(), NULL);
chown_dir(subvolume_folder);
return rc==0;
#endif
}
bool create_snapshot(std::string snapshot_src, std::string snapshot_dst)
{
#ifdef _WIN32
return CopyFolder(widen(snapshot_src), widen(snapshot_dst));
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "snapshot", snapshot_src.c_str(), snapshot_dst.c_str(), NULL);
chown_dir(snapshot_dst);
return rc==0;
#endif
}
bool remove_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
return os_remove_nonempty_dir(widen(subvolume_folder));
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "delete", subvolume_folder.c_str(), NULL);
return rc==0;
#endif
}
bool is_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
return true;
#else
int rc=exec_wait(btrfs_cmd, "subvolume", "list", subvolume_folder.c_str(), NULL);
return rc==0;
#endif
}
int main(int argc, char *argv[])
{
if(argc<2)
{
std::cout << "Not enough parameters" << std::endl;
return 1;
}
std::string cmd=argv[1];
std::string backupfolder=getBackupfolderPath();
if(backupfolder.empty())
{
std::cout << "Backupfolder not set" << std::endl;
return 1;
}
#ifndef _WIN32
if(seteuid(0)!=0)
{
std::cout << "Cannot become root user" << std::endl;
return 1;
}
#endif
if(cmd=="create")
{
if(argc<4)
{
std::cout << "Not enough parameters for create" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string name=handleFilename(argv[3]);
std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
return create_subvolume(subvolume_folder)?0:1;
}
else if(cmd=="snapshot")
{
if(argc<5)
{
std::cout << "Not enough parameters for snapshot" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string src_name=handleFilename(argv[3]);
std::string dst_name=handleFilename(argv[4]);
std::string subvolume_src_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+src_name;
std::string subvolume_dst_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+dst_name;
return create_snapshot(subvolume_src_folder, subvolume_dst_folder)?0:1;
}
else if(cmd=="remove")
{
if(argc<4)
{
std::cout << "Not enough parameters for remove" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string name=handleFilename(argv[3]);
std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
return remove_subvolume(subvolume_folder)?0:1;
}
else if(cmd=="test")
{
std::string clientdir=backupfolder+os_file_sepn()+"testA54hj5luZtlorr494";
bool create_dir_rc=os_create_dir(clientdir);
if(!create_dir_rc)
{
remove_subvolume(clientdir+os_file_sepn()+"A");
remove_subvolume(clientdir+os_file_sepn()+"B");
os_remove_dir(clientdir);
}
create_dir_rc = create_dir_rc || os_create_dir(clientdir);
if(create_dir_rc)
{
if(!create_subvolume(clientdir+os_file_sepn()+"A") )
{
std::cout << "TEST FAILED: Creating test subvolume failed" << std::endl;
os_remove_dir(clientdir);
return 1;
}
bool suc=true;
if(!create_snapshot(clientdir+os_file_sepn()+"A", clientdir+os_file_sepn()+"B") )
{
std::cout << "TEST FAILED: Creating test snapshot failed" << std::endl;
suc=false;
}
if(suc)
{
writestring("test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test");
if(!os_create_hardlink(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test", true, NULL))
{
std::cout << "TEST FAILED: Creating cross sub-volume reflink failed. Need Linux kernel >= 3.6." << std::endl;
suc=false;
}
else
{
if(getFile(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test")!="test")
{
std::cout << "TEST FAILED: Cannot read reflinked file" << std::endl;
suc=false;
}
}
}
if(!remove_subvolume(clientdir+os_file_sepn()+"A") )
{
std::cout << "TEST FAILED: Removing subvolume A failed" << std::endl;
suc=false;
}
if(!remove_subvolume(clientdir+os_file_sepn()+"B") )
{
std::cout << "TEST FAILED: Removing subvolume B failed" << std::endl;
suc=false;
}
if(!os_remove_dir(clientdir))
{
std::cout << "TEST FAILED: Removing test clientdir failed" << std::endl;
return 1;
}
if(!suc)
{
return 1;
}
}
else
{
std::cout << "TEST FAILED: Creating test clientdir \"" << clientdir << "\" failed" << std::endl;
return 1;
}
std::cout << "TEST OK" << std::endl;
return 0;
}
else if(cmd=="issubvolume")
{
if(argc<4)
{
std::cout << "Not enough parameters for issubvolume" << std::endl;
return 1;
}
std::string clientname=handleFilename(argv[2]);
std::string name=handleFilename(argv[3]);
std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
return is_subvolume(subvolume_folder)?0:1;
}
else
{
std::cout << "Command not found" << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before><commit_msg>bUseTarget is never read<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tplpitem.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:34:36 $
*
* 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
*
************************************************************************/
// INCLUDE ---------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif
#include "tplpitem.hxx"
#ifndef _COM_SUN_STAR_FRAME_STATUS_TEMPLATE_HPP_
#include <com/sun/star/frame/status/Template.hpp>
#endif
// STATIC DATA -----------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SfxTemplateItem, SfxFlagItem);
//=========================================================================
SfxTemplateItem::SfxTemplateItem() :
SfxFlagItem()
{
}
SfxTemplateItem::SfxTemplateItem
(
USHORT nWhich, // Slot-ID
const String& rStyle, // Name des aktuellen Styles
USHORT nValue // Flags f"ur das Filtern bei automatischer Anzeige
) :
SfxFlagItem( nWhich, nValue ),
aStyle( rStyle )
{
}
//-------------------------------------------------------------------------
// copy ctor
SfxTemplateItem::SfxTemplateItem( const SfxTemplateItem& rCopy ) :
SfxFlagItem( rCopy ),
aStyle( rCopy.aStyle )
{
}
//-------------------------------------------------------------------------
// op ==
int SfxTemplateItem::operator==( const SfxPoolItem& rCmp ) const
{
return ( SfxFlagItem::operator==( rCmp ) &&
aStyle == ( (const SfxTemplateItem&)rCmp ).aStyle );
}
//-------------------------------------------------------------------------
SfxPoolItem* SfxTemplateItem::Clone( SfxItemPool *) const
{
return new SfxTemplateItem(*this);
}
//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
::com::sun::star::frame::status::Template aTemplate;
aTemplate.Value = GetValue();
aTemplate.StyleName = aStyle;
rVal <<= aTemplate;
return sal_True;
}
//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
::com::sun::star::frame::status::Template aTemplate;
if ( rVal >>= aTemplate )
{
SetValue( aTemplate.Value );
aStyle = aTemplate.StyleName;
return sal_True;
}
return sal_False;
}
//-------------------------------------------------------------------------
BYTE SfxTemplateItem::GetFlagCount() const
{
return sizeof(USHORT) * 8;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.7.64); FILE MERGED 2005/11/28 16:16:12 cd 1.7.64.1: #i55991# Remove warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tplpitem.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-19 22:25:26 $
*
* 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
*
************************************************************************/
// INCLUDE ---------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif
#include "tplpitem.hxx"
#ifndef _COM_SUN_STAR_FRAME_STATUS_TEMPLATE_HPP_
#include <com/sun/star/frame/status/Template.hpp>
#endif
// STATIC DATA -----------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SfxTemplateItem, SfxFlagItem);
//=========================================================================
SfxTemplateItem::SfxTemplateItem() :
SfxFlagItem()
{
}
SfxTemplateItem::SfxTemplateItem
(
USHORT nWhichId, // Slot-ID
const String& rStyle, // Name des aktuellen Styles
USHORT nValue // Flags f"ur das Filtern bei automatischer Anzeige
) : SfxFlagItem( nWhichId, nValue ),
aStyle( rStyle )
{
}
//-------------------------------------------------------------------------
// copy ctor
SfxTemplateItem::SfxTemplateItem( const SfxTemplateItem& rCopy ) :
SfxFlagItem( rCopy ),
aStyle( rCopy.aStyle )
{
}
//-------------------------------------------------------------------------
// op ==
int SfxTemplateItem::operator==( const SfxPoolItem& rCmp ) const
{
return ( SfxFlagItem::operator==( rCmp ) &&
aStyle == ( (const SfxTemplateItem&)rCmp ).aStyle );
}
//-------------------------------------------------------------------------
SfxPoolItem* SfxTemplateItem::Clone( SfxItemPool *) const
{
return new SfxTemplateItem(*this);
}
//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
::com::sun::star::frame::status::Template aTemplate;
aTemplate.Value = GetValue();
aTemplate.StyleName = aStyle;
rVal <<= aTemplate;
return sal_True;
}
//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ )
{
::com::sun::star::frame::status::Template aTemplate;
if ( rVal >>= aTemplate )
{
SetValue( aTemplate.Value );
aStyle = aTemplate.StyleName;
return sal_True;
}
return sal_False;
}
//-------------------------------------------------------------------------
BYTE SfxTemplateItem::GetFlagCount() const
{
return sizeof(USHORT) * 8;
}
<|endoftext|> |
<commit_before><commit_msg>Open remote templates when double clicking in the thumbnail.<commit_after><|endoftext|> |
<commit_before>#include "RC.h"
#define ENDPOINT_BUFFER_SIZE 50
//#define DEBUG(s) Serial.print(s)
//#define DEBUGLN(s) Serial.println(s)
#define DEBUG(s)
#define DEBUGLN(s)
APIClient::APIClient(Client& c, String publicKey, String privateKey) : client(c) {
this->publicKey = publicKey;
this->privateKey = privateKey;
}
APIClient::~APIClient() {
}
boolean APIClient::user(int id, User& user) {
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "users/%u/", id);
if(!get(endpoint)) {
return false;
}
if(!readHeaders()) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
if(readKey(buffer, "\"id\"", user.id)) {
continue;
}
if(readKey(buffer, "\"username\"", user.username)) {
continue;
}
if(readKey(buffer, "\"first_name\"", user.first_name)) {
continue;
}
if(readKey(buffer, "\"last_name\"", user.last_name)) {
continue;
}
if(readKey(buffer, "\"magnetic\"", user.magnetic)) {
continue;
}
if(readKey(buffer, "\"rfid\"", user.rfid)) {
continue;
}
if(readKey(buffer, "\"balance\"", user.balance)) {
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::channel(int id, Channel& channel) {
DEBUGLN("Called channel");
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "channels/%u/?exclude=description,created", id);
DEBUGLN(endpoint);
if(!get(endpoint)) {
return false;
}
DEBUGLN("Get good");
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
DEBUGLN("Headers and responseCode okay");
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
if(readKey(buffer, "\"id\"", channel.id)) {
DEBUGLN("FOUND ID");
DEBUGLN(channel.id);
continue;
}
if(readKey(buffer, "\"name\"", channel.name)) {
DEBUGLN("FOUND NAME");
DEBUGLN(channel.name);
continue;
}
if(readKey(buffer, "\"value\"", channel.value)) {
//while(client.available()) {
// client.read();
//}
DEBUGLN("FOUND VALUE");
DEBUGLN(channel.value);
continue;
}
if(readKey(buffer, "\"updated\"", channel.updated)) {
DEBUGLN("FOUND UPDATED");
DEBUGLN(channel.updated);
continue;
}
}
}
DEBUGLN("Stopping client");
client.stop();
return true;
}
boolean APIClient::magnetic(String magneticID, String meta, UserLookup& userLookup) {
String body = "{\"magnetic\":\"";
body += magneticID;
body += "\",\"meta\":\"";
body += meta;
body += "\"}";
DEBUGLN(body);
if(!post("magnetic/", body)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
DEBUGLN(buffer);
if(readKey(buffer, "\"found\"", userLookup.found)) {
DEBUGLN("FOUND found");
continue;
}
if(readKey(buffer, "\"user\"", userLookup.user_id)) {
DEBUGLN("FOUND user");
continue;
}
if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
DEBUGLN("FOUND api_request");
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::rfid(String rfid, String meta, UserLookup& userLookup) {
String body = "{\"rfid\":\"";
body += rfid;
body += "\",\"meta\":\"";
body += meta;
body += "\"}";
DEBUG("rfid body: ");
DEBUGLN(body);
if(!post("rfid/", body)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
DEBUG("Bad response code: ");
DEBUGLN(responseCode);
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
DEBUGLN(buffer);
if(readKey(buffer, "\"found\"", userLookup.found)) {
DEBUGLN("FOUND found");
continue;
}
if(readKey(buffer, "\"user\"", userLookup.user_id)) {
DEBUGLN("FOUND user");
continue;
}
if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
DEBUGLN("FOUND api_request");
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::userRFID(int id, String rfid, String meta, int& apiRequestID) {
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "users/%u/rfid/", id);
String body = "{\"rfid\":\"";
body += rfid;
body += "\",\"meta\":\"";
body += meta;
body += "\"}";
if(!post(endpoint, body)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
if(readKey(buffer, "\"api_request\"", apiRequestID)) {
DEBUGLN("FOUND api_request");
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::channelWriteValue(int id, String value) {
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "channels/%u/", id);
String message = "{\"value\": \"" + value + "\"}";
if(!put(endpoint, message)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
// Need to clear out buffer
client.read();
}
}
client.stop();
return true;
}
boolean APIClient::datetime(String form, String& datetime){
DEBUGLN("Called datetime");
// url encode query parameter
form.replace(" ", "%20");
char temp[form.length() + 2];
form.toCharArray(temp, form.length() + 1);
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "datetime/?form=%s", temp);
DEBUGLN(endpoint);
if(!get(endpoint)) {
return false;
}
DEBUGLN("Get good");
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
DEBUGLN("Headers and responseCode okay");
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil('}');
if(readKey(buffer, "\"datetime\"", datetime)) {
DEBUGLN("FOUND datetime");
continue;
}
}
}
DEBUGLN("Stopping client");
client.stop();
return true;
}
int APIClient::lastResponseCode() {
return responseCode;
}
// TODO: make inline
boolean APIClient::get(char* endpoint) {
return request(endpoint, "", false);
}
boolean APIClient::post(char* endpoint, String body) {
return request(endpoint, body, false);
}
boolean APIClient::put(char* endpoint, String body) {
return request(endpoint, body, true);
}
boolean APIClient::request(char* endpoint, String buffer, boolean put) {
DEBUGLN("Before connect");
boolean c = client.connect("www.roboticsclub.org", 80);
DEBUG("Connected: ");
DEBUGLN(c);
if(!c) {
return false;
}
if(buffer.length()) {
if(put) {
client.print(F("PATCH"));
} else {
client.print(F("POST"));
}
} else {
client.print(F("GET"));
}
client.print(F(" /api/"));
client.print(endpoint);
client.println(F(" HTTP/1.1"));
client.println(F("Host: roboticsclub.org"));
client.print(F("PUBLIC_KEY: "));
client.println(publicKey);
client.print(F("PRIVATE_KEY: "));
client.println(privateKey);
client.print(F("API_CLIENT: "));
client.println(F("ArduinoRC 1.0"));
client.println(F("Accept: application/json"));
client.println(F("Connection: close"));
if(buffer.length()) {
client.println(F("Content-Type: application/json"));
client.print(F("Content-Length: "));
client.println(buffer.length());
}
client.println();
if(buffer.length()) {
client.println(buffer);
}
DEBUGLN("End of request");
return true;
}
boolean APIClient::readHeaders() {
// Seen status code
boolean seen_code = false;
//DEBUG("Client connected: ");
//DEBUGLN(client.connected());
//DEBUG("Client available: ");
//DEBUGLN(client.available());
while(client.connected() || client.available()) {
while(client.available()) {
String b = client.readStringUntil('\n');
//DEBUG("readHeaders buffer: ");
//DEBUGLN(b);
if(!seen_code) {
responseCode = b.substring(b.indexOf(' '), b.lastIndexOf(' ')).toInt();
seen_code = true;
}
// If not just a newline, not
// the response expected and should
// error after done reading
if(b.length() == 1) {
return true;
}
}
}
return false;
}
boolean APIClient::readKey(String buffer, char* key, String& value) {
int index = buffer.indexOf(key);
if(index < 0) {
return false;
} else {
// +1 ':'
value = buffer.substring(index + strlen(key) + 1);
value.replace("\"", "");
//TODO: uncomment this
//value.replace("}", "");
return true;
}
}
boolean APIClient::readKey(String buffer, char* key, int& value) {
String v;
boolean r = readKey(buffer, key, v);
if(!r) {
return false;
}
value = v.toInt();
return true;
}
boolean APIClient::readKey(String buffer, char* key, double& value) {
String v;
boolean r = readKey(buffer, key, v);
if(!r) {
return false;
}
char charBuffer[v.length()+1];
v.toCharArray(charBuffer, v.length()+1);
value = atof(charBuffer);
return true;
}
bool contains(String s, String search)
{
int max = s.length() - search.length(); // the searchstring has to fit in the other one
for (int i=0; i<= max; i++)
{
if (s.substring(i, i + search.length()) == search) {
return true;
}
}
return false; //or -1
}
boolean APIClient::readKey(String buffer, char* key, boolean& value) {
String v;
boolean r = readKey(buffer, key, v);
if(!r) {
return false;
}
//value = (v == "true") ? true : false;
value = contains(v, "true");
return true;
}
<commit_msg>Added '-' version of headers.<commit_after>#include "RC.h"
#define ENDPOINT_BUFFER_SIZE 50
//#define DEBUG(s) Serial.print(s)
//#define DEBUGLN(s) Serial.println(s)
#define DEBUG(s)
#define DEBUGLN(s)
APIClient::APIClient(Client& c, String publicKey, String privateKey) : client(c) {
this->publicKey = publicKey;
this->privateKey = privateKey;
}
APIClient::~APIClient() {
}
boolean APIClient::user(int id, User& user) {
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "users/%u/", id);
if(!get(endpoint)) {
return false;
}
if(!readHeaders()) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
if(readKey(buffer, "\"id\"", user.id)) {
continue;
}
if(readKey(buffer, "\"username\"", user.username)) {
continue;
}
if(readKey(buffer, "\"first_name\"", user.first_name)) {
continue;
}
if(readKey(buffer, "\"last_name\"", user.last_name)) {
continue;
}
if(readKey(buffer, "\"magnetic\"", user.magnetic)) {
continue;
}
if(readKey(buffer, "\"rfid\"", user.rfid)) {
continue;
}
if(readKey(buffer, "\"balance\"", user.balance)) {
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::channel(int id, Channel& channel) {
DEBUGLN("Called channel");
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "channels/%u/?exclude=description,created", id);
DEBUGLN(endpoint);
if(!get(endpoint)) {
return false;
}
DEBUGLN("Get good");
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
DEBUGLN("Headers and responseCode okay");
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
if(readKey(buffer, "\"id\"", channel.id)) {
DEBUGLN("FOUND ID");
DEBUGLN(channel.id);
continue;
}
if(readKey(buffer, "\"name\"", channel.name)) {
DEBUGLN("FOUND NAME");
DEBUGLN(channel.name);
continue;
}
if(readKey(buffer, "\"value\"", channel.value)) {
//while(client.available()) {
// client.read();
//}
DEBUGLN("FOUND VALUE");
DEBUGLN(channel.value);
continue;
}
if(readKey(buffer, "\"updated\"", channel.updated)) {
DEBUGLN("FOUND UPDATED");
DEBUGLN(channel.updated);
continue;
}
}
}
DEBUGLN("Stopping client");
client.stop();
return true;
}
boolean APIClient::magnetic(String magneticID, String meta, UserLookup& userLookup) {
String body = "{\"magnetic\":\"";
body += magneticID;
body += "\",\"meta\":\"";
body += meta;
body += "\"}";
DEBUGLN(body);
if(!post("magnetic/", body)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
DEBUGLN(buffer);
if(readKey(buffer, "\"found\"", userLookup.found)) {
DEBUGLN("FOUND found");
continue;
}
if(readKey(buffer, "\"user\"", userLookup.user_id)) {
DEBUGLN("FOUND user");
continue;
}
if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
DEBUGLN("FOUND api_request");
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::rfid(String rfid, String meta, UserLookup& userLookup) {
String body = "{\"rfid\":\"";
body += rfid;
body += "\",\"meta\":\"";
body += meta;
body += "\"}";
DEBUG("rfid body: ");
DEBUGLN(body);
if(!post("rfid/", body)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
DEBUG("Bad response code: ");
DEBUGLN(responseCode);
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
DEBUGLN(buffer);
if(readKey(buffer, "\"found\"", userLookup.found)) {
DEBUGLN("FOUND found");
continue;
}
if(readKey(buffer, "\"user\"", userLookup.user_id)) {
DEBUGLN("FOUND user");
continue;
}
if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
DEBUGLN("FOUND api_request");
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::userRFID(int id, String rfid, String meta, int& apiRequestID) {
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "users/%u/rfid/", id);
String body = "{\"rfid\":\"";
body += rfid;
body += "\",\"meta\":\"";
body += meta;
body += "\"}";
if(!post(endpoint, body)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil(',');
if(readKey(buffer, "\"api_request\"", apiRequestID)) {
DEBUGLN("FOUND api_request");
continue;
}
}
}
client.stop();
return true;
}
boolean APIClient::channelWriteValue(int id, String value) {
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "channels/%u/", id);
String message = "{\"value\": \"" + value + "\"}";
if(!put(endpoint, message)) {
return false;
}
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
while(client.connected() || client.available()) {
while(client.available()) {
// Need to clear out buffer
client.read();
}
}
client.stop();
return true;
}
boolean APIClient::datetime(String form, String& datetime){
DEBUGLN("Called datetime");
// url encode query parameter
form.replace(" ", "%20");
char temp[form.length() + 2];
form.toCharArray(temp, form.length() + 1);
char endpoint[ENDPOINT_BUFFER_SIZE];
sprintf(endpoint, "datetime/?form=%s", temp);
DEBUGLN(endpoint);
if(!get(endpoint)) {
return false;
}
DEBUGLN("Get good");
if(!readHeaders() || responseCode != 200) {
client.stop();
return false;
}
DEBUGLN("Headers and responseCode okay");
while(client.connected() || client.available()) {
while(client.available()) {
String buffer = client.readStringUntil('}');
if(readKey(buffer, "\"datetime\"", datetime)) {
DEBUGLN("FOUND datetime");
continue;
}
}
}
DEBUGLN("Stopping client");
client.stop();
return true;
}
int APIClient::lastResponseCode() {
return responseCode;
}
// TODO: make inline
boolean APIClient::get(char* endpoint) {
return request(endpoint, "", false);
}
boolean APIClient::post(char* endpoint, String body) {
return request(endpoint, body, false);
}
boolean APIClient::put(char* endpoint, String body) {
return request(endpoint, body, true);
}
boolean APIClient::request(char* endpoint, String buffer, boolean put) {
DEBUGLN("Before connect");
boolean c = client.connect("www.roboticsclub.org", 80);
DEBUG("Connected: ");
DEBUGLN(c);
if(!c) {
return false;
}
if(buffer.length()) {
if(put) {
client.print(F("PATCH"));
} else {
client.print(F("POST"));
}
} else {
client.print(F("GET"));
}
client.print(F(" /api/"));
client.print(endpoint);
client.println(F(" HTTP/1.1"));
client.println(F("Host: roboticsclub.org"));
client.print(F("PUBLIC_KEY: "));
client.println(publicKey);
client.print(F("PRIVATE_KEY: "));
client.println(privateKey);
client.print(F("API_CLIENT: "));
client.println(F("ArduinoRC 1.0"));
client.print(F("PUBLIC-KEY: "));
client.println(publicKey);
client.print(F("PRIVATE-KEY: "));
client.println(privateKey);
client.print(F("API-CLIENT: "));
client.println(F("ArduinoRC 1.0"));
client.println(F("Accept: application/json"));
client.println(F("Connection: close"));
if(buffer.length()) {
client.println(F("Content-Type: application/json"));
client.print(F("Content-Length: "));
client.println(buffer.length());
}
client.println();
if(buffer.length()) {
client.println(buffer);
}
DEBUGLN("End of request");
return true;
}
boolean APIClient::readHeaders() {
// Seen status code
boolean seen_code = false;
//DEBUG("Client connected: ");
//DEBUGLN(client.connected());
//DEBUG("Client available: ");
//DEBUGLN(client.available());
while(client.connected() || client.available()) {
while(client.available()) {
String b = client.readStringUntil('\n');
//DEBUG("readHeaders buffer: ");
//DEBUGLN(b);
if(!seen_code) {
responseCode = b.substring(b.indexOf(' '), b.lastIndexOf(' ')).toInt();
seen_code = true;
}
// If not just a newline, not
// the response expected and should
// error after done reading
if(b.length() == 1) {
return true;
}
}
}
return false;
}
boolean APIClient::readKey(String buffer, char* key, String& value) {
int index = buffer.indexOf(key);
if(index < 0) {
return false;
} else {
// +1 ':'
value = buffer.substring(index + strlen(key) + 1);
value.replace("\"", "");
//TODO: uncomment this
//value.replace("}", "");
return true;
}
}
boolean APIClient::readKey(String buffer, char* key, int& value) {
String v;
boolean r = readKey(buffer, key, v);
if(!r) {
return false;
}
value = v.toInt();
return true;
}
boolean APIClient::readKey(String buffer, char* key, double& value) {
String v;
boolean r = readKey(buffer, key, v);
if(!r) {
return false;
}
char charBuffer[v.length()+1];
v.toCharArray(charBuffer, v.length()+1);
value = atof(charBuffer);
return true;
}
bool contains(String s, String search)
{
int max = s.length() - search.length(); // the searchstring has to fit in the other one
for (int i=0; i<= max; i++)
{
if (s.substring(i, i + search.length()) == search) {
return true;
}
}
return false; //or -1
}
boolean APIClient::readKey(String buffer, char* key, boolean& value) {
String v;
boolean r = readKey(buffer, key, v);
if(!r) {
return false;
}
//value = (v == "true") ? true : false;
value = contains(v, "true");
return true;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2019 Asylo authors
*
* 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 "asylo/identity/sgx/pce_util.h"
#include <openssl/base.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <cstdint>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/base/macros.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/escaping.h"
#include "absl/types/optional.h"
#include "asylo/crypto/algorithms.pb.h"
#include "asylo/crypto/util/bssl_util.h"
#include "asylo/test/util/status_matchers.h"
#include "QuoteGeneration/psw/pce_wrapper/inc/sgx_pce.h"
namespace asylo {
namespace sgx {
namespace {
constexpr char kSecretMessage[] = "secret message";
// Hex-encoded RSA_F4 in big-endian format.
constexpr char kExponentBigEndianHex[] = "00010001";
// A hex-encoded RSA-3072 key modulus in big-endian format.
constexpr char kModulusBigEndianHex[] =
"ecb62879f45c3880514bd2ee7bf1c2373c0de9184a641c250bfe59a3702e0a6632cc5e9e96"
"ef16c04ca2844b1fa14ca0cdda7fa953fd69e5cb3f2368cab778fcf3e42db4c3b57f6b8a17"
"c1fa58bc9fb99486668bdb4ddde725762c9f06d488463ece26aa5b57de5200785622d9b485"
"95ef9523de581c50d98dc40e2605d907f057a66a13b6725b07b60f344cabf6255568a73267"
"8d2fa9a8ed2c482e23aedf47d4ce2c77a73b622c2712176386cd6ecddff1dc200ede191918"
"c63a74197d505f264349fdafbc44595e22b3cca2b428b5098c53e360cff8fd0d7053d3a868"
"855c17dc9e7bf376b077ee4abcea326e46799d983962939a0bd51a6291cf494d8cb61f402f"
"cfcec220f43ac2df50923e242f7ee0d2a91d2511cd5aa4cfa83d5e651d397f77806fb93ef3"
"f9d04103097079a2b65d6041f339cf589bd8452dfc7683d7c1d5f7bfacc0039dd263f4a447"
"af1909db1c1f6f0196218754dfeb2cd9b63f5268c6b51f39124765aed40af4e5dd78626aed"
"43b51ae86688da36864bb063cab5";
using ::testing::Eq;
using ::testing::Optional;
// All encryption schemes supported by the PCE.
constexpr AsymmetricEncryptionScheme kSupportedEncryptionSchemes[] = {
RSA3072_OAEP};
// The crypto suite corresponding to each scheme in kSupportedEncryptionSchemes.
constexpr uint8_t kTranslatedEncryptionSchemes[] = {PCE_ALG_RSA_OAEP_3072};
// All signature schemes supported by the PCE.
constexpr SignatureScheme kSupportedSignatureSchemes[] = {ECDSA_P256_SHA256};
// The signature scheme corresponding to each scheme in
// kSupportedSignatureSchemes.
constexpr uint8_t kTranslatedSignatureSchemes[] = {PCE_NIST_P256_ECDSA_SHA256};
class PceUtilTest : public ::testing::Test {
public:
void SetUp() override {
supported_encryption_schemes_.reserve(
ABSL_ARRAYSIZE(kSupportedEncryptionSchemes));
for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedEncryptionSchemes); ++i) {
ASSERT_TRUE(supported_encryption_schemes_
.emplace(kSupportedEncryptionSchemes[i],
kTranslatedEncryptionSchemes[i])
.second);
}
for (int i = 0; i < AsymmetricEncryptionScheme_ARRAYSIZE; ++i) {
if (AsymmetricEncryptionScheme_IsValid(i)) {
AsymmetricEncryptionScheme scheme =
static_cast<AsymmetricEncryptionScheme>(i);
if (!supported_encryption_schemes_.contains(scheme)) {
unsupported_encryption_schemes_.push_back(scheme);
}
}
}
supported_signature_schemes_.reserve(
ABSL_ARRAYSIZE(kSupportedSignatureSchemes));
for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedSignatureSchemes); ++i) {
ASSERT_TRUE(supported_signature_schemes_
.emplace(kSupportedSignatureSchemes[i],
kTranslatedSignatureSchemes[i])
.second);
}
for (int i = 0; i < SignatureScheme_ARRAYSIZE; ++i) {
if (SignatureScheme_IsValid(i)) {
SignatureScheme scheme = static_cast<SignatureScheme>(i);
if (!supported_signature_schemes_.contains(scheme)) {
unsupported_signature_schemes_.push_back(scheme);
}
}
}
plaintext_ =
std::vector<uint8_t>(reinterpret_cast<const uint8_t *>(kSecretMessage),
reinterpret_cast<const uint8_t *>(kSecretMessage) +
sizeof(kSecretMessage));
}
absl::flat_hash_map<AsymmetricEncryptionScheme, uint8_t>
supported_encryption_schemes_;
absl::flat_hash_map<SignatureScheme, uint8_t> supported_signature_schemes_;
std::vector<AsymmetricEncryptionScheme> unsupported_encryption_schemes_;
std::vector<SignatureScheme> unsupported_signature_schemes_;
std::vector<uint8_t> plaintext_;
};
TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteSupported) {
for (const auto &pair : supported_encryption_schemes_) {
EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(pair.first),
Optional(pair.second));
}
}
TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteUnsupported) {
for (AsymmetricEncryptionScheme scheme : unsupported_encryption_schemes_) {
EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(scheme),
Eq(absl::nullopt));
}
}
TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeSupported) {
for (const auto &pair : supported_signature_schemes_) {
EXPECT_THAT(SignatureSchemeToPceSignatureScheme(pair.first),
Optional(pair.second));
}
}
TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeUnsupported) {
for (SignatureScheme scheme : unsupported_signature_schemes_) {
EXPECT_THAT(SignatureSchemeToPceSignatureScheme(scheme), Eq(absl::nullopt));
}
}
TEST_F(PceUtilTest, ParseRsa3072PublicKeyInvalidSize) {
std::vector<uint8_t> public_key(0);
ASSERT_THAT(ParseRsa3072PublicKey(absl::MakeSpan(public_key)).status(),
StatusIs(error::INVALID_ARGUMENT));
}
// Verify that an RSA public key serialized according to what is expected by the
// PCE can be parsed and restored to an RSA key, and that its exponent and
// modulus are as expected.
TEST_F(PceUtilTest, ParseRsa3072PublicKeySuccess) {
std::string modulus = absl::HexStringToBytes(kModulusBigEndianHex);
std::string exponent = absl::HexStringToBytes(kExponentBigEndianHex);
std::vector<uint8_t> public_key;
public_key.insert(public_key.end(), modulus.cbegin(), modulus.cend());
public_key.insert(public_key.end(), exponent.cbegin(), exponent.cend());
auto result = ParseRsa3072PublicKey(absl::MakeSpan(public_key));
ASYLO_ASSERT_OK(result.status());
bssl::UniquePtr<RSA> rsa = std::move(result).ValueOrDie();
EXPECT_THAT(RSA_size(rsa.get()), modulus.size());
const BIGNUM *n;
const BIGNUM *e;
// The private exponent, d, is not set for a public key.
RSA_get0_key(rsa.get(), &n, &e, /*out_d=*/nullptr);
// Compare against expected public exponent.
EXPECT_EQ(BN_is_word(e, RSA_F4), 1);
bssl::UniquePtr<BIGNUM> expected_n(BN_new());
BN_bin2bn(reinterpret_cast<const uint8_t *>(modulus.data()), modulus.size(),
expected_n.get());
// Compare against expected modulus.
EXPECT_EQ(BN_cmp(n, expected_n.get()), 0);
}
TEST_F(PceUtilTest, DISABLED_ParseRsa3072PublicKeyRestoreFromSerializedKey) {
bssl::UniquePtr<RSA> rsa1(RSA_new());
bssl::UniquePtr<BIGNUM> e(BN_new());
ASSERT_EQ(BN_set_word(e.get(), RSA_F4), 1) << BsslLastErrorString();
ASSERT_EQ(
RSA_generate_key_ex(rsa1.get(), /*bits=*/3072, e.get(), /*cb=*/nullptr),
1)
<< BsslLastErrorString();
auto result1 = SerializeRsa3072PublicKey(rsa1.get());
ASYLO_ASSERT_OK(result1);
std::vector<uint8_t> serialized_key = std::move(result1).ValueOrDie();
auto result2 = ParseRsa3072PublicKey(absl::MakeSpan(serialized_key));
ASYLO_ASSERT_OK(result2);
bssl::UniquePtr<RSA> rsa2(std::move(result2).ValueOrDie());
// Verify that both keys have the same modulus size.
EXPECT_THAT(RSA_size(rsa2.get()), Eq(RSA_size(rsa1.get())));
// Verify that the restored key can decrypt a message encrypted by the
// original key.
std::vector<uint8_t> ciphertext(RSA_size(rsa1.get()));
size_t out_len;
ASSERT_EQ(
RSA_encrypt(rsa1.get(), &out_len, ciphertext.data(), ciphertext.size(),
plaintext_.data(), plaintext_.size(), RSA_PKCS1_OAEP_PADDING),
1)
<< BsslLastErrorString();
ciphertext.resize(out_len);
std::vector<uint8_t> decrypted(RSA_size(rsa2.get()));
ASSERT_EQ(
RSA_decrypt(rsa2.get(), &out_len, decrypted.data(), decrypted.size(),
ciphertext.data(), ciphertext.size(), RSA_PKCS1_OAEP_PADDING),
1)
<< BsslLastErrorString();
decrypted.resize(out_len);
EXPECT_THAT(decrypted, Eq(plaintext_));
}
} // namespace
} // namespace sgx
} // namespace asylo
<commit_msg>Fix bug in pce_util_test<commit_after>/*
*
* Copyright 2019 Asylo authors
*
* 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 "asylo/identity/sgx/pce_util.h"
#include <openssl/base.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <cstdint>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/base/macros.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/escaping.h"
#include "absl/types/optional.h"
#include "asylo/crypto/algorithms.pb.h"
#include "asylo/crypto/util/bssl_util.h"
#include "asylo/test/util/status_matchers.h"
#include "QuoteGeneration/psw/pce_wrapper/inc/sgx_pce.h"
namespace asylo {
namespace sgx {
namespace {
constexpr char kSecretMessage[] = "secret message";
// Hex-encoded RSA_F4 in big-endian format.
constexpr char kExponentBigEndianHex[] = "00010001";
// A hex-encoded RSA-3072 key modulus in big-endian format.
constexpr char kModulusBigEndianHex[] =
"ecb62879f45c3880514bd2ee7bf1c2373c0de9184a641c250bfe59a3702e0a6632cc5e9e96"
"ef16c04ca2844b1fa14ca0cdda7fa953fd69e5cb3f2368cab778fcf3e42db4c3b57f6b8a17"
"c1fa58bc9fb99486668bdb4ddde725762c9f06d488463ece26aa5b57de5200785622d9b485"
"95ef9523de581c50d98dc40e2605d907f057a66a13b6725b07b60f344cabf6255568a73267"
"8d2fa9a8ed2c482e23aedf47d4ce2c77a73b622c2712176386cd6ecddff1dc200ede191918"
"c63a74197d505f264349fdafbc44595e22b3cca2b428b5098c53e360cff8fd0d7053d3a868"
"855c17dc9e7bf376b077ee4abcea326e46799d983962939a0bd51a6291cf494d8cb61f402f"
"cfcec220f43ac2df50923e242f7ee0d2a91d2511cd5aa4cfa83d5e651d397f77806fb93ef3"
"f9d04103097079a2b65d6041f339cf589bd8452dfc7683d7c1d5f7bfacc0039dd263f4a447"
"af1909db1c1f6f0196218754dfeb2cd9b63f5268c6b51f39124765aed40af4e5dd78626aed"
"43b51ae86688da36864bb063cab5";
using ::testing::Eq;
using ::testing::Optional;
// All encryption schemes supported by the PCE.
constexpr AsymmetricEncryptionScheme kSupportedEncryptionSchemes[] = {
RSA3072_OAEP};
// The crypto suite corresponding to each scheme in kSupportedEncryptionSchemes.
constexpr uint8_t kTranslatedEncryptionSchemes[] = {PCE_ALG_RSA_OAEP_3072};
// All signature schemes supported by the PCE.
constexpr SignatureScheme kSupportedSignatureSchemes[] = {ECDSA_P256_SHA256};
// The signature scheme corresponding to each scheme in
// kSupportedSignatureSchemes.
constexpr uint8_t kTranslatedSignatureSchemes[] = {PCE_NIST_P256_ECDSA_SHA256};
class PceUtilTest : public ::testing::Test {
public:
void SetUp() override {
supported_encryption_schemes_.reserve(
ABSL_ARRAYSIZE(kSupportedEncryptionSchemes));
for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedEncryptionSchemes); ++i) {
ASSERT_TRUE(supported_encryption_schemes_
.emplace(kSupportedEncryptionSchemes[i],
kTranslatedEncryptionSchemes[i])
.second);
}
for (int i = 0; i < AsymmetricEncryptionScheme_ARRAYSIZE; ++i) {
if (AsymmetricEncryptionScheme_IsValid(i)) {
AsymmetricEncryptionScheme scheme =
static_cast<AsymmetricEncryptionScheme>(i);
if (!supported_encryption_schemes_.contains(scheme)) {
unsupported_encryption_schemes_.push_back(scheme);
}
}
}
supported_signature_schemes_.reserve(
ABSL_ARRAYSIZE(kSupportedSignatureSchemes));
for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedSignatureSchemes); ++i) {
ASSERT_TRUE(supported_signature_schemes_
.emplace(kSupportedSignatureSchemes[i],
kTranslatedSignatureSchemes[i])
.second);
}
for (int i = 0; i < SignatureScheme_ARRAYSIZE; ++i) {
if (SignatureScheme_IsValid(i)) {
SignatureScheme scheme = static_cast<SignatureScheme>(i);
if (!supported_signature_schemes_.contains(scheme)) {
unsupported_signature_schemes_.push_back(scheme);
}
}
}
plaintext_ =
std::vector<uint8_t>(reinterpret_cast<const uint8_t *>(kSecretMessage),
reinterpret_cast<const uint8_t *>(kSecretMessage) +
sizeof(kSecretMessage));
}
absl::flat_hash_map<AsymmetricEncryptionScheme, uint8_t>
supported_encryption_schemes_;
absl::flat_hash_map<SignatureScheme, uint8_t> supported_signature_schemes_;
std::vector<AsymmetricEncryptionScheme> unsupported_encryption_schemes_;
std::vector<SignatureScheme> unsupported_signature_schemes_;
std::vector<uint8_t> plaintext_;
};
TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteSupported) {
for (const auto &pair : supported_encryption_schemes_) {
EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(pair.first),
Optional(pair.second));
}
}
TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteUnsupported) {
for (AsymmetricEncryptionScheme scheme : unsupported_encryption_schemes_) {
EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(scheme),
Eq(absl::nullopt));
}
}
TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeSupported) {
for (const auto &pair : supported_signature_schemes_) {
EXPECT_THAT(SignatureSchemeToPceSignatureScheme(pair.first),
Optional(pair.second));
}
}
TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeUnsupported) {
for (SignatureScheme scheme : unsupported_signature_schemes_) {
EXPECT_THAT(SignatureSchemeToPceSignatureScheme(scheme), Eq(absl::nullopt));
}
}
TEST_F(PceUtilTest, ParseRsa3072PublicKeyInvalidSize) {
std::vector<uint8_t> public_key(0);
ASSERT_THAT(ParseRsa3072PublicKey(absl::MakeSpan(public_key)).status(),
StatusIs(error::INVALID_ARGUMENT));
}
// Verify that an RSA public key serialized according to what is expected by the
// PCE can be parsed and restored to an RSA key, and that its exponent and
// modulus are as expected.
TEST_F(PceUtilTest, ParseRsa3072PublicKeySuccess) {
std::string modulus = absl::HexStringToBytes(kModulusBigEndianHex);
std::string exponent = absl::HexStringToBytes(kExponentBigEndianHex);
std::vector<uint8_t> public_key;
public_key.insert(public_key.end(), modulus.cbegin(), modulus.cend());
public_key.insert(public_key.end(), exponent.cbegin(), exponent.cend());
auto result = ParseRsa3072PublicKey(absl::MakeSpan(public_key));
ASYLO_ASSERT_OK(result.status());
bssl::UniquePtr<RSA> rsa = std::move(result).ValueOrDie();
EXPECT_THAT(RSA_size(rsa.get()), modulus.size());
const BIGNUM *n;
const BIGNUM *e;
// The private exponent, d, is not set for a public key.
RSA_get0_key(rsa.get(), &n, &e, /*out_d=*/nullptr);
// Compare against expected public exponent.
EXPECT_EQ(BN_is_word(e, RSA_F4), 1);
bssl::UniquePtr<BIGNUM> expected_n(BN_new());
BN_bin2bn(reinterpret_cast<const uint8_t *>(modulus.data()), modulus.size(),
expected_n.get());
// Compare against expected modulus.
EXPECT_EQ(BN_cmp(n, expected_n.get()), 0);
}
TEST_F(PceUtilTest, DISABLED_ParseRsa3072PublicKeyRestoreFromSerializedKey) {
bssl::UniquePtr<RSA> rsa1(RSA_new());
bssl::UniquePtr<BIGNUM> e(BN_new());
ASSERT_EQ(BN_set_word(e.get(), RSA_F4), 1) << BsslLastErrorString();
ASSERT_EQ(
RSA_generate_key_ex(rsa1.get(), /*bits=*/3072, e.get(), /*cb=*/nullptr),
1)
<< BsslLastErrorString();
auto result1 = SerializeRsa3072PublicKey(rsa1.get());
ASYLO_ASSERT_OK(result1);
std::vector<uint8_t> serialized_key = std::move(result1).ValueOrDie();
auto result2 = ParseRsa3072PublicKey(absl::MakeSpan(serialized_key));
ASYLO_ASSERT_OK(result2);
bssl::UniquePtr<RSA> rsa2(std::move(result2).ValueOrDie());
// Verify that both keys have the same modulus size.
EXPECT_THAT(RSA_size(rsa2.get()), Eq(RSA_size(rsa1.get())));
// Verify that the original key can decrypt a message encrypted by the
// restored key.
std::vector<uint8_t> ciphertext(RSA_size(rsa1.get()));
size_t out_len;
ASSERT_EQ(
RSA_encrypt(rsa2.get(), &out_len, ciphertext.data(), ciphertext.size(),
plaintext_.data(), plaintext_.size(), RSA_PKCS1_OAEP_PADDING),
1)
<< BsslLastErrorString();
ciphertext.resize(out_len);
std::vector<uint8_t> decrypted(RSA_size(rsa2.get()));
ASSERT_EQ(
RSA_decrypt(rsa1.get(), &out_len, decrypted.data(), decrypted.size(),
ciphertext.data(), ciphertext.size(), RSA_PKCS1_OAEP_PADDING),
1)
<< BsslLastErrorString();
decrypted.resize(out_len);
EXPECT_THAT(decrypted, Eq(plaintext_));
}
} // namespace
} // namespace sgx
} // namespace asylo
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include <utility>
#include <vector>
#include "atom/browser/api/atom_api_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace mate {
template<>
struct Converter<file_dialog::Filter> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
file_dialog::Filter* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("name", &(out->first)))
return false;
if (!dict.Get("extensions", &(out->second)))
return false;
return true;
}
};
template<>
struct Converter<file_dialog::DialogSettings> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
file_dialog::DialogSettings* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("window", &(out->parent_window));
dict.Get("title", &(out->title));
dict.Get("message", &(out->message));
dict.Get("buttonLabel", &(out->button_label));
dict.Get("nameFieldLabel", &(out->name_field_label));
dict.Get("defaultPath", &(out->default_path));
dict.Get("filters", &(out->filters));
dict.Get("properties", &(out->properties));
dict.Get("showsTagField", &(out->shows_tag_field));
return true;
}
};
} // namespace mate
namespace {
void ShowMessageBox(int type,
const std::vector<std::string>& buttons,
int default_id,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const std::string& checkbox_label,
bool checkbox_checked,
const gfx::ImageSkia& icon,
atom::NativeWindow* window,
mate::Arguments* args) {
v8::Local<v8::Value> peek = args->PeekNext();
atom::MessageBoxCallback callback;
if (mate::Converter<atom::MessageBoxCallback>::FromV8(args->isolate(),
peek,
&callback)) {
atom::ShowMessageBox(window, (atom::MessageBoxType)type, buttons,
default_id, cancel_id, options, title, message, detail,
checkbox_label, checkbox_checked, icon, callback);
} else {
int chosen = atom::ShowMessageBox(window, (atom::MessageBoxType)type,
buttons, default_id, cancel_id,
options, title, message, detail, icon);
args->Return(chosen);
}
}
void ShowOpenDialog(const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
v8::Local<v8::Value> peek = args->PeekNext();
file_dialog::OpenDialogCallback callback;
if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
peek,
&callback)) {
file_dialog::ShowOpenDialog(settings, callback);
} else {
std::vector<base::FilePath> paths;
if (file_dialog::ShowOpenDialog(settings, &paths))
args->Return(paths);
}
}
void ShowSaveDialog(const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
v8::Local<v8::Value> peek = args->PeekNext();
file_dialog::SaveDialogCallback callback;
if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
peek,
&callback)) {
file_dialog::ShowSaveDialog(settings, callback);
} else {
base::FilePath path;
if (file_dialog::ShowSaveDialog(settings, &path))
args->Return(path);
}
}
// #if defined(OS_MACOSX)
void ShowCertificateTrust(atom::NativeWindow* parent_window,
const scoped_refptr<net::X509Certificate>& cert,
std::string message,
const certificate_trust::ShowTrustCallback& callback,
mate::Arguments* args) {
certificate_trust::ShowCertificateTrust(parent_window, cert, message, callback);
}
// #endif
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("showMessageBox", &ShowMessageBox);
dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
dict.SetMethod("showOpenDialog", &ShowOpenDialog);
dict.SetMethod("showSaveDialog", &ShowSaveDialog);
// #if defined(OS_MACOSX)
dict.SetMethod("showCertificateTrustDialog", &ShowCertificateTrust);
// #endif
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_dialog, Initialize)
<commit_msg>Fix indentation<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include <utility>
#include <vector>
#include "atom/browser/api/atom_api_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace mate {
template<>
struct Converter<file_dialog::Filter> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
file_dialog::Filter* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("name", &(out->first)))
return false;
if (!dict.Get("extensions", &(out->second)))
return false;
return true;
}
};
template<>
struct Converter<file_dialog::DialogSettings> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
file_dialog::DialogSettings* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("window", &(out->parent_window));
dict.Get("title", &(out->title));
dict.Get("message", &(out->message));
dict.Get("buttonLabel", &(out->button_label));
dict.Get("nameFieldLabel", &(out->name_field_label));
dict.Get("defaultPath", &(out->default_path));
dict.Get("filters", &(out->filters));
dict.Get("properties", &(out->properties));
dict.Get("showsTagField", &(out->shows_tag_field));
return true;
}
};
} // namespace mate
namespace {
void ShowMessageBox(int type,
const std::vector<std::string>& buttons,
int default_id,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const std::string& checkbox_label,
bool checkbox_checked,
const gfx::ImageSkia& icon,
atom::NativeWindow* window,
mate::Arguments* args) {
v8::Local<v8::Value> peek = args->PeekNext();
atom::MessageBoxCallback callback;
if (mate::Converter<atom::MessageBoxCallback>::FromV8(args->isolate(),
peek,
&callback)) {
atom::ShowMessageBox(window, (atom::MessageBoxType)type, buttons,
default_id, cancel_id, options, title, message, detail,
checkbox_label, checkbox_checked, icon, callback);
} else {
int chosen = atom::ShowMessageBox(window, (atom::MessageBoxType)type,
buttons, default_id, cancel_id,
options, title, message, detail, icon);
args->Return(chosen);
}
}
void ShowOpenDialog(const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
v8::Local<v8::Value> peek = args->PeekNext();
file_dialog::OpenDialogCallback callback;
if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
peek,
&callback)) {
file_dialog::ShowOpenDialog(settings, callback);
} else {
std::vector<base::FilePath> paths;
if (file_dialog::ShowOpenDialog(settings, &paths))
args->Return(paths);
}
}
void ShowSaveDialog(const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
v8::Local<v8::Value> peek = args->PeekNext();
file_dialog::SaveDialogCallback callback;
if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
peek,
&callback)) {
file_dialog::ShowSaveDialog(settings, callback);
} else {
base::FilePath path;
if (file_dialog::ShowSaveDialog(settings, &path))
args->Return(path);
}
}
// #if defined(OS_MACOSX)
void ShowCertificateTrust(atom::NativeWindow* parent_window,
const scoped_refptr<net::X509Certificate>& cert,
std::string message,
const certificate_trust::ShowTrustCallback& callback,
mate::Arguments* args) {
certificate_trust::ShowCertificateTrust(parent_window, cert, message, callback);
}
// #endif
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("showMessageBox", &ShowMessageBox);
dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
dict.SetMethod("showOpenDialog", &ShowOpenDialog);
dict.SetMethod("showSaveDialog", &ShowSaveDialog);
// #if defined(OS_MACOSX)
dict.SetMethod("showCertificateTrustDialog", &ShowCertificateTrust);
// #endif
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_dialog, Initialize)
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/api/object_life_monitor.h"
#include "atom/common/v8/native_type_conversions.h"
#include "v8/include/v8-profiler.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
namespace {
void CreateObjectWithName(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
t->SetClassName(args[0]->ToString());
args.GetReturnValue().Set(t->GetFunction()->NewInstance());
}
void GetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(
args[0]->ToObject()->GetHiddenValue(args[1]->ToString()));
}
void SetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]);
}
void GetObjectHash(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(args[0]->ToObject()->GetIdentityHash());
}
void SetDestructor(const v8::FunctionCallbackInfo<v8::Value>& args) {
ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]);
}
void TakeHeapSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args) {
node::node_isolate->GetHeapProfiler()->TakeHeapSnapshot(
v8::String::New("test"));
}
} // namespace
void InitializeV8Util(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "createObjectWithName", CreateObjectWithName);
NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue);
NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue);
NODE_SET_METHOD(target, "getObjectHash", GetObjectHash);
NODE_SET_METHOD(target, "setDestructor", SetDestructor);
NODE_SET_METHOD(target, "takeHeapSnapshot", TakeHeapSnapshot);
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_common_v8_util, atom::api::InitializeV8Util)
<commit_msg>Remove unneeded include.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/api/object_life_monitor.h"
#include "v8/include/v8-profiler.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
namespace {
void CreateObjectWithName(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
t->SetClassName(args[0]->ToString());
args.GetReturnValue().Set(t->GetFunction()->NewInstance());
}
void GetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(
args[0]->ToObject()->GetHiddenValue(args[1]->ToString()));
}
void SetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]);
}
void GetObjectHash(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(args[0]->ToObject()->GetIdentityHash());
}
void SetDestructor(const v8::FunctionCallbackInfo<v8::Value>& args) {
ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]);
}
void TakeHeapSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args) {
node::node_isolate->GetHeapProfiler()->TakeHeapSnapshot(
v8::String::New("test"));
}
} // namespace
void InitializeV8Util(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "createObjectWithName", CreateObjectWithName);
NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue);
NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue);
NODE_SET_METHOD(target, "getObjectHash", GetObjectHash);
NODE_SET_METHOD(target, "setDestructor", SetDestructor);
NODE_SET_METHOD(target, "takeHeapSnapshot", TakeHeapSnapshot);
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_common_v8_util, atom::api::InitializeV8Util)
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2009 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
QXmppPresence::QXmppPresence(QXmppPresence::Type type,
const QXmppPresence::Status& status)
: QXmppStanza(), m_type(type), m_status(status)
{
}
QXmppPresence::~QXmppPresence()
{
}
QXmppPresence::Type QXmppPresence::type() const
{
return m_type;
}
void QXmppPresence::setType(QXmppPresence::Type type)
{
m_type = type;
}
const QXmppPresence::Status& QXmppPresence::status() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::status()
{
return m_status;
}
void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
m_status = status;
}
void QXmppPresence::parse(const QDomElement &element)
{
QXmppStanza::parse(element);
setTypeFromStr(element.attribute("type"));
m_status.parse(element);
QDomElement xElement = element.firstChildElement("x");
if(!xElement.isNull())
setExtensions(QXmppElement(xElement));
}
void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
xmlWriter->writeStartElement("presence");
helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
helperToXmlAddAttribute(xmlWriter,"id", id());
helperToXmlAddAttribute(xmlWriter,"to", to());
helperToXmlAddAttribute(xmlWriter,"from", from());
helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
m_status.toXml(xmlWriter);
error().toXml(xmlWriter);
foreach (const QXmppElement &extension, extensions())
extension.toXml(xmlWriter);
xmlWriter->writeEndElement();
}
QString QXmppPresence::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Error:
text = "error";
break;
case QXmppPresence::Available:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Unavailable:
text = "unavailable";
break;
case QXmppPresence::Subscribe:
text = "subscribe";
break;
case QXmppPresence::Subscribed:
text = "subscribed";
break;
case QXmppPresence::Unsubscribe:
text = "unsubscribe";
break;
case QXmppPresence::Unsubscribed:
text = "unsubscribed";
break;
case QXmppPresence::Probe:
text = "probe";
break;
default:
qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
break;
}
return text;
}
void QXmppPresence::setTypeFromStr(const QString& str)
{
QXmppPresence::Type type;
if(str == "error")
{
type = QXmppPresence::Error;
setType(type);
return;
}
else if(str == "unavailable")
{
type = QXmppPresence::Unavailable;
setType(type);
return;
}
else if(str == "subscribe")
{
type = QXmppPresence::Subscribe;
setType(type);
return;
}
else if(str == "subscribed")
{
type = QXmppPresence::Subscribed;
setType(type);
return;
}
else if(str == "unsubscribe")
{
type = QXmppPresence::Unsubscribe;
setType(type);
return;
}
else if(str == "unsubscribed")
{
type = QXmppPresence::Unsubscribed;
setType(type);
return;
}
else if(str == "probe")
{
type = QXmppPresence::Probe;
setType(type);
return;
}
else if(str == "")
{
type = QXmppPresence::Available;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Type>(-1);
qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
qPrintable(str));
setType(type);
return;
}
}
QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
const QString statusText, int priority) :
m_type(type),
m_statusText(statusText), m_priority(priority)
{
}
QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
return m_type;
}
void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
m_type = type;
}
void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
// there is no keyword for Offline
QXmppPresence::Status::Type type;
if(str == "") // not type-attribute means online
{
type = QXmppPresence::Status::Online;
setType(type);
return;
}
else if(str == "away")
{
type = QXmppPresence::Status::Away;
setType(type);
return;
}
else if(str == "xa")
{
type = QXmppPresence::Status::XA;
setType(type);
return;
}
else if(str == "dnd")
{
type = QXmppPresence::Status::DND;
setType(type);
return;
}
else if(str == "chat")
{
type = QXmppPresence::Status::Chat;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Status::Type>(-1);
qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
qPrintable(str));
setType(type);
}
}
QString QXmppPresence::Status::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Status::Online:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Status::Offline:
text = "";
break;
case QXmppPresence::Status::Away:
text = "away";
break;
case QXmppPresence::Status::XA:
text = "xa";
break;
case QXmppPresence::Status::DND:
text = "dnd";
break;
case QXmppPresence::Status::Chat:
text = "chat";
break;
default:
qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
(int)m_type);
break;
}
return text;
}
QString QXmppPresence::Status::statusText() const
{
return m_statusText;
}
void QXmppPresence::Status::setStatusText(const QString& str)
{
m_statusText = str;
}
int QXmppPresence::Status::priority() const
{
return m_priority;
}
void QXmppPresence::Status::setPriority(int priority)
{
m_priority = priority;
}
void QXmppPresence::Status::parse(const QDomElement &element)
{
setTypeFromStr(element.firstChildElement("show").text());
m_statusText = element.firstChildElement("status").text();
m_priority = element.firstChildElement("priority").text().toInt();
}
void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
if (m_priority != 0)
helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}
// obsolete start
QXmppPresence::Type QXmppPresence::getType() const
{
return m_type;
}
const QXmppPresence::Status& QXmppPresence::getStatus() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::getStatus()
{
return m_status;
}
QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
return m_type;
}
QString QXmppPresence::Status::getStatusText() const
{
return m_statusText;
}
int QXmppPresence::Status::getPriority() const
{
return m_priority;
}
// obsolete end
<commit_msg>don't add "show" and "status" to presence if empty<commit_after>/*
* Copyright (C) 2008-2009 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
QXmppPresence::QXmppPresence(QXmppPresence::Type type,
const QXmppPresence::Status& status)
: QXmppStanza(), m_type(type), m_status(status)
{
}
QXmppPresence::~QXmppPresence()
{
}
QXmppPresence::Type QXmppPresence::type() const
{
return m_type;
}
void QXmppPresence::setType(QXmppPresence::Type type)
{
m_type = type;
}
const QXmppPresence::Status& QXmppPresence::status() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::status()
{
return m_status;
}
void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
m_status = status;
}
void QXmppPresence::parse(const QDomElement &element)
{
QXmppStanza::parse(element);
setTypeFromStr(element.attribute("type"));
m_status.parse(element);
QDomElement xElement = element.firstChildElement("x");
if(!xElement.isNull())
setExtensions(QXmppElement(xElement));
}
void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
xmlWriter->writeStartElement("presence");
helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
helperToXmlAddAttribute(xmlWriter,"id", id());
helperToXmlAddAttribute(xmlWriter,"to", to());
helperToXmlAddAttribute(xmlWriter,"from", from());
helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
m_status.toXml(xmlWriter);
error().toXml(xmlWriter);
foreach (const QXmppElement &extension, extensions())
extension.toXml(xmlWriter);
xmlWriter->writeEndElement();
}
QString QXmppPresence::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Error:
text = "error";
break;
case QXmppPresence::Available:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Unavailable:
text = "unavailable";
break;
case QXmppPresence::Subscribe:
text = "subscribe";
break;
case QXmppPresence::Subscribed:
text = "subscribed";
break;
case QXmppPresence::Unsubscribe:
text = "unsubscribe";
break;
case QXmppPresence::Unsubscribed:
text = "unsubscribed";
break;
case QXmppPresence::Probe:
text = "probe";
break;
default:
qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
break;
}
return text;
}
void QXmppPresence::setTypeFromStr(const QString& str)
{
QXmppPresence::Type type;
if(str == "error")
{
type = QXmppPresence::Error;
setType(type);
return;
}
else if(str == "unavailable")
{
type = QXmppPresence::Unavailable;
setType(type);
return;
}
else if(str == "subscribe")
{
type = QXmppPresence::Subscribe;
setType(type);
return;
}
else if(str == "subscribed")
{
type = QXmppPresence::Subscribed;
setType(type);
return;
}
else if(str == "unsubscribe")
{
type = QXmppPresence::Unsubscribe;
setType(type);
return;
}
else if(str == "unsubscribed")
{
type = QXmppPresence::Unsubscribed;
setType(type);
return;
}
else if(str == "probe")
{
type = QXmppPresence::Probe;
setType(type);
return;
}
else if(str == "")
{
type = QXmppPresence::Available;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Type>(-1);
qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
qPrintable(str));
setType(type);
return;
}
}
QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
const QString statusText, int priority) :
m_type(type),
m_statusText(statusText), m_priority(priority)
{
}
QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
return m_type;
}
void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
m_type = type;
}
void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
// there is no keyword for Offline
QXmppPresence::Status::Type type;
if(str == "") // not type-attribute means online
{
type = QXmppPresence::Status::Online;
setType(type);
return;
}
else if(str == "away")
{
type = QXmppPresence::Status::Away;
setType(type);
return;
}
else if(str == "xa")
{
type = QXmppPresence::Status::XA;
setType(type);
return;
}
else if(str == "dnd")
{
type = QXmppPresence::Status::DND;
setType(type);
return;
}
else if(str == "chat")
{
type = QXmppPresence::Status::Chat;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Status::Type>(-1);
qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
qPrintable(str));
setType(type);
}
}
QString QXmppPresence::Status::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Status::Online:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Status::Offline:
text = "";
break;
case QXmppPresence::Status::Away:
text = "away";
break;
case QXmppPresence::Status::XA:
text = "xa";
break;
case QXmppPresence::Status::DND:
text = "dnd";
break;
case QXmppPresence::Status::Chat:
text = "chat";
break;
default:
qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
(int)m_type);
break;
}
return text;
}
QString QXmppPresence::Status::statusText() const
{
return m_statusText;
}
void QXmppPresence::Status::setStatusText(const QString& str)
{
m_statusText = str;
}
int QXmppPresence::Status::priority() const
{
return m_priority;
}
void QXmppPresence::Status::setPriority(int priority)
{
m_priority = priority;
}
void QXmppPresence::Status::parse(const QDomElement &element)
{
setTypeFromStr(element.firstChildElement("show").text());
m_statusText = element.firstChildElement("status").text();
m_priority = element.firstChildElement("priority").text().toInt();
}
void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
const QString show = getTypeStr();
if (!show.isEmpty())
helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
if (!m_statusText.isEmpty())
helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
if (m_priority != 0)
helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}
// obsolete start
QXmppPresence::Type QXmppPresence::getType() const
{
return m_type;
}
const QXmppPresence::Status& QXmppPresence::getStatus() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::getStatus()
{
return m_status;
}
QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
return m_type;
}
QString QXmppPresence::Status::getStatusText() const
{
return m_statusText;
}
int QXmppPresence::Status::getPriority() const
{
return m_priority;
}
// obsolete end
<|endoftext|> |
<commit_before>// $Id: Line3_test.C,v 1.8 2000/07/26 16:49:47 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
# include <BALL/MATHS/vector3.h>
# include <BALL/MATHS/line3.h>
///////////////////////////
START_TEST(class_name, "$Id: Line3_test.C,v 1.8 2000/07/26 16:49:47 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
Vector3 v1, v2, v3, v4;
String filename;
using std::ofstream;
using std::ios;
CHECK(TLine3::BALL_CREATE(TLine3<T>))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
Line3 v(v1, v2);
Line3* v_ptr = (Line3*)v.create(false, true);
TEST_EQUAL(v_ptr->p, v3)
TEST_EQUAL(v_ptr->d, v3)
delete v_ptr;
v_ptr = (Line3*)v.create();
TEST_EQUAL(v_ptr->p, v1)
TEST_EQUAL(v_ptr->d, v2)
delete v_ptr;
RESULT
CHECK(TLine3::TLine3())
Line3* line;
line = new Line3();
TEST_NOT_EQUAL(line, 0)
RESULT
CHECK(TLine3::~TLine3())
Line3* line;
line = new Line3();
delete line;
RESULT
Line3 line, line1, line2, line3;
CHECK(TLine3(const TVector3<T>& point, const TVector3<T>& vector,
Form form = FORM__PARAMETER))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line.get(v3, v4, Line3::FORM__PARAMETER);
TEST_EQUAL(v1, v3)
TEST_EQUAL(v2, v4)
line = Line3(v1, v2, Line3::FORM__TWO_POINTS);
line.get(v1, v2);
v3.set(0, 1, 2);
v4.set(3, 3, 3);
TEST_EQUAL(v1, v3)
TEST_EQUAL(v2, v4)
RESULT
CHECK(bool operator ==(const TLine3& line) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(0, 4, 2);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line == line2, true)
v2 = Vector3(0, 1, 2);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line == line2, false)
RESULT
CHECK(TLine3::swap(TLine3& line))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
v3 = Vector3(6, 7, 8);
v4 = Vector3(9, 10, 11);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line1 = Line3(v1, v2, Line3::FORM__PARAMETER);
line2 = Line3(v3, v4, Line3::FORM__PARAMETER);
line3 = Line3(v3, v4, Line3::FORM__PARAMETER);
line.swap(line2);
TEST_EQUAL(line1, line2)
TEST_EQUAL(line, line3)
RESULT
CHECK(TLine3::set(const TVector3<T>& point, const TVector3<T>& vector, Form form = FORM__PARAMETER))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line2.set(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line, line2)
line = Line3(v1, v2, Line3::FORM__TWO_POINTS);
line2.set(v1, v2, Line3::FORM__TWO_POINTS);
TEST_EQUAL(line, line2)
RESULT
CHECK(TLine3::get(TLine3& line, bool /* deep */ = true) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line2.get(line);
TEST_EQUAL(line, line2)
RESULT
CHECK(normalize())
v1 = Vector3(0, 0, 0);
v2 = Vector3(4, 9, 16);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line.normalize();
v2.normalize();
line.get(v3, v4, Line3::FORM__PARAMETER);
TEST_EQUAL(v2, v4)
RESULT
CHECK(bool operator != (const TLine3& line) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(0, 3, 2);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line != line2, false)
v2 = Vector3(9, 1, 2);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line != line2, true)
RESULT
CHECK(has(const TVector3<T>& point) const )
v1 = Vector3(0, 0, 0);
v2 = Vector3(4, 4, 4);
line = Line3(v1, v2, Line3::FORM__TWO_POINTS);
v1 = Vector3(2, 2, 2);
TEST_EQUAL(line.has(v1), true)
v1 = Vector3(2, 2, 3);
TEST_EQUAL(line.has(v1), false)
RESULT
CHECK(isValid() const)
TEST_EQUAL(line.isValid(), true)
RESULT
CHECK(std::istream& operator >> (std::istream& s, TLine3<T>& line))
std::ifstream instr("data/Line_test2.txt");
line = Line3();
instr >> line;
instr.close();
v3 = Vector3(0, 1, 2);
v4 = Vector3(3, 4, 5);
line2 = Line3(v3, v4, Line3::FORM__PARAMETER);
TEST_EQUAL(line, line2)
RESULT
NEW_TMP_FILE(filename)
CHECK(std::ostream& operator << (std::ostream& s, const TLine3<T>& line))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
std::ofstream outstr(filename.c_str(), File::OUT);
outstr << line;
outstr.close();
TEST_FILE(filename.c_str(), "data/Line_test2.txt", false)
RESULT
CHECK(TAngle::dump(std::ostream& s = std::cout, Size depth = 0) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
String filename;
NEW_TMP_FILE(filename)
std::ofstream outfile(filename.c_str(), File::OUT);
line.dump(outfile);
outfile.close();
TEST_FILE(filename.c_str(), "data/Line_test.txt", true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>removed: redundant using directives for some members of namespace std<commit_after>// $Id: Line3_test.C,v 1.9 2000/08/29 15:53:39 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
# include <BALL/MATHS/vector3.h>
# include <BALL/MATHS/line3.h>
///////////////////////////
START_TEST(class_name, "$Id: Line3_test.C,v 1.9 2000/08/29 15:53:39 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
Vector3 v1, v2, v3, v4;
String filename;
CHECK(TLine3::BALL_CREATE(TLine3<T>))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
Line3 v(v1, v2);
Line3* v_ptr = (Line3*)v.create(false, true);
TEST_EQUAL(v_ptr->p, v3)
TEST_EQUAL(v_ptr->d, v3)
delete v_ptr;
v_ptr = (Line3*)v.create();
TEST_EQUAL(v_ptr->p, v1)
TEST_EQUAL(v_ptr->d, v2)
delete v_ptr;
RESULT
CHECK(TLine3::TLine3())
Line3* line;
line = new Line3();
TEST_NOT_EQUAL(line, 0)
RESULT
CHECK(TLine3::~TLine3())
Line3* line;
line = new Line3();
delete line;
RESULT
Line3 line, line1, line2, line3;
CHECK(TLine3(const TVector3<T>& point, const TVector3<T>& vector,
Form form = FORM__PARAMETER))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line.get(v3, v4, Line3::FORM__PARAMETER);
TEST_EQUAL(v1, v3)
TEST_EQUAL(v2, v4)
line = Line3(v1, v2, Line3::FORM__TWO_POINTS);
line.get(v1, v2);
v3.set(0, 1, 2);
v4.set(3, 3, 3);
TEST_EQUAL(v1, v3)
TEST_EQUAL(v2, v4)
RESULT
CHECK(bool operator ==(const TLine3& line) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(0, 4, 2);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line == line2, true)
v2 = Vector3(0, 1, 2);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line == line2, false)
RESULT
CHECK(TLine3::swap(TLine3& line))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
v3 = Vector3(6, 7, 8);
v4 = Vector3(9, 10, 11);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line1 = Line3(v1, v2, Line3::FORM__PARAMETER);
line2 = Line3(v3, v4, Line3::FORM__PARAMETER);
line3 = Line3(v3, v4, Line3::FORM__PARAMETER);
line.swap(line2);
TEST_EQUAL(line1, line2)
TEST_EQUAL(line, line3)
RESULT
CHECK(TLine3::set(const TVector3<T>& point, const TVector3<T>& vector, Form form = FORM__PARAMETER))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line2.set(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line, line2)
line = Line3(v1, v2, Line3::FORM__TWO_POINTS);
line2.set(v1, v2, Line3::FORM__TWO_POINTS);
TEST_EQUAL(line, line2)
RESULT
CHECK(TLine3::get(TLine3& line, bool /* deep */ = true) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line2.get(line);
TEST_EQUAL(line, line2)
RESULT
CHECK(normalize())
v1 = Vector3(0, 0, 0);
v2 = Vector3(4, 9, 16);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line.normalize();
v2.normalize();
line.get(v3, v4, Line3::FORM__PARAMETER);
TEST_EQUAL(v2, v4)
RESULT
CHECK(bool operator != (const TLine3& line) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(0, 3, 2);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line != line2, false)
v2 = Vector3(9, 1, 2);
line2 = Line3(v1, v2, Line3::FORM__PARAMETER);
TEST_EQUAL(line != line2, true)
RESULT
CHECK(has(const TVector3<T>& point) const )
v1 = Vector3(0, 0, 0);
v2 = Vector3(4, 4, 4);
line = Line3(v1, v2, Line3::FORM__TWO_POINTS);
v1 = Vector3(2, 2, 2);
TEST_EQUAL(line.has(v1), true)
v1 = Vector3(2, 2, 3);
TEST_EQUAL(line.has(v1), false)
RESULT
CHECK(isValid() const)
TEST_EQUAL(line.isValid(), true)
RESULT
CHECK(std::istream& operator >> (std::istream& s, TLine3<T>& line))
std::ifstream instr("data/Line_test2.txt");
line = Line3();
instr >> line;
instr.close();
v3 = Vector3(0, 1, 2);
v4 = Vector3(3, 4, 5);
line2 = Line3(v3, v4, Line3::FORM__PARAMETER);
TEST_EQUAL(line, line2)
RESULT
NEW_TMP_FILE(filename)
CHECK(std::ostream& operator << (std::ostream& s, const TLine3<T>& line))
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
std::ofstream outstr(filename.c_str(), File::OUT);
outstr << line;
outstr.close();
TEST_FILE(filename.c_str(), "data/Line_test2.txt", false)
RESULT
CHECK(TAngle::dump(std::ostream& s = std::cout, Size depth = 0) const )
v1 = Vector3(0, 1, 2);
v2 = Vector3(3, 4, 5);
line = Line3(v1, v2, Line3::FORM__PARAMETER);
String filename;
NEW_TMP_FILE(filename)
std::ofstream outfile(filename.c_str(), File::OUT);
line.dump(outfile);
outfile.close();
TEST_FILE(filename.c_str(), "data/Line_test.txt", true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2021 musikcube team
//
// 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 author nor the names of other 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 <stdafx.h>
#include <cursespp/Screen.h>
#include <cursespp/Colors.h>
#include <cursespp/ToastOverlay.h>
#include <musikcore/runtime/Message.h>
#include <musikcore/support/Auddio.h>
#include <musikcore/library/RemoteLibrary.h>
#include <musikcore/version.h>
#include <app/util/Messages.h>
#include <app/util/PreferenceKeys.h>
#include <app/layout/ConsoleLayout.h>
#include <app/layout/LyricsLayout.h>
#include <app/layout/LibraryLayout.h>
#include <app/layout/LibraryNotConnectedLayout.h>
#include <app/layout/SettingsLayout.h>
#include <app/layout/HotkeysLayout.h>
#include <app/util/Hotkeys.h>
#include <map>
#include "SettingsLayout.h"
#include "MainLayout.h"
using namespace musik;
using namespace musik::cube;
using namespace musik::core;
using namespace musik::core::library;
using namespace musik::core::runtime;
using namespace cursespp;
using MasterLibraryPtr = MainLayout::MasterLibraryPtr;
static inline void updateSyncingText(TextLabel* label, int updates) {
try {
if (updates <= 0) {
label->SetText(
_TSTR("main_syncing_banner_start"),
cursespp::text::AlignCenter);
}
else {
label->SetText(u8fmt(
_TSTR("main_syncing_banner"), updates),
cursespp::text::AlignCenter);
}
}
catch (...) {
/* swallow. incomplete locale. don't crash. */
}
}
static inline void updateRemoteLibraryConnectedText(TextLabel* label, MasterLibraryPtr library) {
RemoteLibrary* remoteLibrary = dynamic_cast<RemoteLibrary*>(library->Wrapped().get());
if (remoteLibrary) {
std::string host = remoteLibrary->WebSocketClient().Uri();
if (host.find("ws://") == 0) { host = host.substr(5); }
auto value = u8fmt(_TSTR("library_remote_connected_banner"), host.c_str());
label->SetText(value, cursespp::text::AlignCenter);
}
}
MainLayout::MainLayout(
cursespp::App& app,
musik::cube::ConsoleLogger* logger,
musik::core::audio::PlaybackService& playback,
MasterLibraryPtr library)
: shortcutsFocused(false)
, syncUpdateCount(0)
, library(library)
, playback(playback)
, AppLayout(app) {
this->prefs = Preferences::ForComponent("settings");
library->ConnectionStateChanged.connect(this, &MainLayout::OnLibraryConnectionStateChanged);
library->LibraryChanged.connect(this, &MainLayout::OnLibraryChanged);
playback.TrackChanged.connect(this, &MainLayout::OnTrackChanged);
this->RebindIndexerEventHandlers(ILibraryPtr(), this->library);
/* note we don't create `libraryLayout` here; instead we do it lazily once we're sure
it has been connected. see SwitchToLibraryLayout() */
this->libraryNotConnectedLayout = std::make_shared<LibraryNotConnectedLayout>(library);
this->lyricsLayout = std::make_shared<LyricsLayout>(playback, library);
this->consoleLayout = std::make_shared<ConsoleLayout>(logger);
this->settingsLayout = std::make_shared<SettingsLayout>(app, library, playback);
this->hotkeysLayout = std::make_shared<HotkeysLayout>();
this->topBanner = std::make_shared<TextLabel>();
this->topBanner->SetContentColor(Color::Header);
this->topBanner->Hide();
this->AddWindow(this->topBanner);
/* take user to settings if they don't have a valid configuration. otherwise,
switch to the library view immediately */
this->SetInitialLayout();
this->SetAutoHideCommandBar(this->prefs->GetBool(prefs::keys::AutoHideCommandBar, false));
this->RunUpdateCheck();
}
MainLayout::~MainLayout() {
updateCheck.Cancel();
}
bool MainLayout::ShowTopBanner() {
const auto libraryType = this->library->GetType();
if (libraryType == ILibrary::Type::Local) {
return this->library->Indexer()->GetState() == IIndexer::StateIndexing;
}
else if (libraryType == ILibrary::Type::Remote) {
return this->library->GetConnectionState() == ILibrary::ConnectionState::Connected;
}
return false;
}
void MainLayout::UpdateTopBannerText() {
const auto libraryType = this->library->GetType();
if (libraryType == ILibrary::Type::Local) {
updateSyncingText(this->topBanner.get(), this->syncUpdateCount);
}
else if (libraryType == ILibrary::Type::Remote) {
updateRemoteLibraryConnectedText(this->topBanner.get(), this->library);
}
}
void MainLayout::OnLayout() {
if (this->ShowTopBanner()) {
const int cx = this->GetContentWidth();
this->SetPadding(1, 0, 0, 0);
this->topBanner->MoveAndResize(0, 0, cx, 1);
this->topBanner->Show();
this->UpdateTopBannerText();
}
else {
this->SetPadding(0, 0, 0, 0);
this->topBanner->Hide();
}
AppLayout::OnLayout();
}
bool MainLayout::KeyPress(const std::string& key) {
/* deal with top-level view switching first. */
if (Hotkeys::Is(Hotkeys::NavigateConsole, key)) {
this->SetLayout(consoleLayout);
return true;
}
else if (auddio::Available() && Hotkeys::Is(Hotkeys::NavigateLyrics, key)) {
this->Broadcast(message::JumpToLyrics);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateHotkeys, key)) {
this->SetLayout(hotkeysLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateLibrary, key)) {
this->SwitchToLibraryLayout();
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateSettings, key)) {
this->SetLayout(settingsLayout);
return true;
}
else if (key == "M-`") {
std::string version = u8fmt("%s %s", VERSION, VERSION_COMMIT_HASH);
ToastOverlay::Show(u8fmt(_TSTR("console_version"), version.c_str()), -1);
return true;
}
else if (this->GetLayout()->KeyPress(key)) {
return true;
}
return AppLayout::KeyPress(key);
}
void MainLayout::Start() {
MessageQueue().RegisterForBroadcasts(this->shared_from_this());
}
void MainLayout::Stop() {
MessageQueue().UnregisterForBroadcasts(this);
}
void MainLayout::ProcessMessage(musik::core::runtime::IMessage &message) {
const int type = message.Type();
if (type == message::JumpToConsole) {
this->SetLayout(consoleLayout);
}
else if (type == message::JumpToSettings) {
this->SetLayout(settingsLayout);
}
else if (type == message::JumpToLyrics) {
this->SetLayout(lyricsLayout);
}
else if (type == message::JumpToHotkeys) {
this->SetLayout(hotkeysLayout);
}
else if (type == message::JumpToLibrary) {
this->SwitchToLibraryLayout();
}
else if (type == message::JumpToPlayQueue) {
this->SwitchToPlayQueue();
}
else if (type == message::IndexerStarted) {
this->syncUpdateCount = 0;
this->Layout();
}
else if (type == message::IndexerFinished) {
this->Layout();
}
else if (type == message::IndexerProgress) {
this->syncUpdateCount = narrow_cast<int>(message.UserData1());
this->UpdateTopBannerText();
if (!topBanner->IsVisible()) {
this->Layout();
}
}
else {
LayoutBase::ProcessMessage(message);
}
}
bool MainLayout::IsLibraryConnected() {
using State = ILibrary::ConnectionState;
return library->GetConnectionState() == State::Connected;
}
void MainLayout::SetInitialLayout() {
if (library->IsConfigured()) {
this->SwitchToLibraryLayout();
}
else {
this->SetLayout(settingsLayout);
}
}
void MainLayout::SwitchToPlayQueue() {
if (IsLibraryConnected()) {
this->SetLayout(libraryLayout);
libraryLayout->KeyPress(Hotkeys::Get(Hotkeys::NavigateLibraryPlayQueue));
}
}
void MainLayout::SwitchToLibraryLayout() {
if (IsLibraryConnected()) {
if (!this->libraryLayout) {
this->libraryLayout = std::make_shared<LibraryLayout>(playback, library);
}
this->SetLayout(libraryLayout);
}
else {
this->libraryLayout.reset();
this->SetLayout(this->libraryNotConnectedLayout);
}
}
void MainLayout::OnLibraryConnectionStateChanged(ILibrary::ConnectionState state) {
auto currentLayout = this->GetLayout();
if (currentLayout == this->libraryLayout ||
currentLayout == this->libraryNotConnectedLayout)
{
this->SwitchToLibraryLayout();
}
}
void MainLayout::OnLibraryChanged(musik::core::ILibraryPtr prev, musik::core::ILibraryPtr curr) {
this->playback.Stop();
this->libraryLayout = std::make_shared<LibraryLayout>(playback, library);
this->RebindIndexerEventHandlers(prev, curr);
this->Layout();
}
void MainLayout::RebindIndexerEventHandlers(musik::core::ILibraryPtr prev, musik::core::ILibraryPtr curr) {
if (prev) {
prev->Indexer()->Started.disconnect(this);
prev->Indexer()->Finished.disconnect(this);
prev->Indexer()->Progress.disconnect(this);
}
if (curr) {
curr->Indexer()->Started.connect(this, &MainLayout::OnIndexerStarted);
curr->Indexer()->Finished.connect(this, &MainLayout::OnIndexerFinished);
curr->Indexer()->Progress.connect(this, &MainLayout::OnIndexerProgress);
}
}
void MainLayout::OnIndexerStarted() {
this->Post(message::IndexerStarted);
}
void MainLayout::OnIndexerProgress(int count) {
this->Post(message::IndexerProgress, count);
}
void MainLayout::OnIndexerFinished(int count) {
this->Post(message::IndexerFinished);
}
void MainLayout::OnTrackChanged(size_t index, musik::core::TrackPtr track) {
if (prefs->GetBool(
cube::prefs::keys::DisableWindowTitleUpdates,
cube::prefs::defaults::DisableWindowTitleUpdates))
{
return;
}
if (!track) {
App::Instance().SetTitle("musikcube");
}
else {
App::Instance().SetTitle(u8fmt(
"musikcube [%s - %s]",
track->GetString("artist").c_str(),
track->GetString("title").c_str()));
}
}
void MainLayout::RunUpdateCheck() {
if (!prefs->GetBool(cube::prefs::keys::AutoUpdateCheck, true)) {
return;
}
updateCheck.Run([this](bool updateRequired, std::string version, std::string url) {
if (updateRequired) {
UpdateCheck::ShowUpgradeAvailableOverlay(version, url);
}
});
}
<commit_msg>Fix bug where user may not be able to navigate to lyrics layout.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2021 musikcube team
//
// 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 author nor the names of other 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 <stdafx.h>
#include <cursespp/Screen.h>
#include <cursespp/Colors.h>
#include <cursespp/ToastOverlay.h>
#include <musikcore/runtime/Message.h>
#include <musikcore/support/Auddio.h>
#include <musikcore/library/RemoteLibrary.h>
#include <musikcore/version.h>
#include <app/util/Messages.h>
#include <app/util/PreferenceKeys.h>
#include <app/layout/ConsoleLayout.h>
#include <app/layout/LyricsLayout.h>
#include <app/layout/LibraryLayout.h>
#include <app/layout/LibraryNotConnectedLayout.h>
#include <app/layout/SettingsLayout.h>
#include <app/layout/HotkeysLayout.h>
#include <app/util/Hotkeys.h>
#include <map>
#include "SettingsLayout.h"
#include "MainLayout.h"
using namespace musik;
using namespace musik::cube;
using namespace musik::core;
using namespace musik::core::library;
using namespace musik::core::runtime;
using namespace cursespp;
using MasterLibraryPtr = MainLayout::MasterLibraryPtr;
static inline void updateSyncingText(TextLabel* label, int updates) {
try {
if (updates <= 0) {
label->SetText(
_TSTR("main_syncing_banner_start"),
cursespp::text::AlignCenter);
}
else {
label->SetText(u8fmt(
_TSTR("main_syncing_banner"), updates),
cursespp::text::AlignCenter);
}
}
catch (...) {
/* swallow. incomplete locale. don't crash. */
}
}
static inline void updateRemoteLibraryConnectedText(TextLabel* label, MasterLibraryPtr library) {
RemoteLibrary* remoteLibrary = dynamic_cast<RemoteLibrary*>(library->Wrapped().get());
if (remoteLibrary) {
std::string host = remoteLibrary->WebSocketClient().Uri();
if (host.find("ws://") == 0) { host = host.substr(5); }
auto value = u8fmt(_TSTR("library_remote_connected_banner"), host.c_str());
label->SetText(value, cursespp::text::AlignCenter);
}
}
MainLayout::MainLayout(
cursespp::App& app,
musik::cube::ConsoleLogger* logger,
musik::core::audio::PlaybackService& playback,
MasterLibraryPtr library)
: shortcutsFocused(false)
, syncUpdateCount(0)
, library(library)
, playback(playback)
, AppLayout(app) {
this->prefs = Preferences::ForComponent("settings");
library->ConnectionStateChanged.connect(this, &MainLayout::OnLibraryConnectionStateChanged);
library->LibraryChanged.connect(this, &MainLayout::OnLibraryChanged);
playback.TrackChanged.connect(this, &MainLayout::OnTrackChanged);
this->RebindIndexerEventHandlers(ILibraryPtr(), this->library);
/* note we don't create `libraryLayout` here; instead we do it lazily once we're sure
it has been connected. see SwitchToLibraryLayout() */
this->libraryNotConnectedLayout = std::make_shared<LibraryNotConnectedLayout>(library);
this->lyricsLayout = std::make_shared<LyricsLayout>(playback, library);
this->consoleLayout = std::make_shared<ConsoleLayout>(logger);
this->settingsLayout = std::make_shared<SettingsLayout>(app, library, playback);
this->hotkeysLayout = std::make_shared<HotkeysLayout>();
this->topBanner = std::make_shared<TextLabel>();
this->topBanner->SetContentColor(Color::Header);
this->topBanner->Hide();
this->AddWindow(this->topBanner);
/* take user to settings if they don't have a valid configuration. otherwise,
switch to the library view immediately */
this->SetInitialLayout();
this->SetAutoHideCommandBar(this->prefs->GetBool(prefs::keys::AutoHideCommandBar, false));
this->RunUpdateCheck();
}
MainLayout::~MainLayout() {
updateCheck.Cancel();
}
bool MainLayout::ShowTopBanner() {
const auto libraryType = this->library->GetType();
if (libraryType == ILibrary::Type::Local) {
return this->library->Indexer()->GetState() == IIndexer::StateIndexing;
}
else if (libraryType == ILibrary::Type::Remote) {
return this->library->GetConnectionState() == ILibrary::ConnectionState::Connected;
}
return false;
}
void MainLayout::UpdateTopBannerText() {
const auto libraryType = this->library->GetType();
if (libraryType == ILibrary::Type::Local) {
updateSyncingText(this->topBanner.get(), this->syncUpdateCount);
}
else if (libraryType == ILibrary::Type::Remote) {
updateRemoteLibraryConnectedText(this->topBanner.get(), this->library);
}
}
void MainLayout::OnLayout() {
if (this->ShowTopBanner()) {
const int cx = this->GetContentWidth();
this->SetPadding(1, 0, 0, 0);
this->topBanner->MoveAndResize(0, 0, cx, 1);
this->topBanner->Show();
this->UpdateTopBannerText();
}
else {
this->SetPadding(0, 0, 0, 0);
this->topBanner->Hide();
}
AppLayout::OnLayout();
}
bool MainLayout::KeyPress(const std::string& key) {
/* deal with top-level view switching first. */
if (Hotkeys::Is(Hotkeys::NavigateConsole, key)) {
this->SetLayout(consoleLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateLyrics, key)) {
this->Broadcast(message::JumpToLyrics);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateHotkeys, key)) {
this->SetLayout(hotkeysLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateLibrary, key)) {
this->SwitchToLibraryLayout();
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateSettings, key)) {
this->SetLayout(settingsLayout);
return true;
}
else if (key == "M-`") {
std::string version = u8fmt("%s %s", VERSION, VERSION_COMMIT_HASH);
ToastOverlay::Show(u8fmt(_TSTR("console_version"), version.c_str()), -1);
return true;
}
else if (this->GetLayout()->KeyPress(key)) {
return true;
}
return AppLayout::KeyPress(key);
}
void MainLayout::Start() {
MessageQueue().RegisterForBroadcasts(this->shared_from_this());
}
void MainLayout::Stop() {
MessageQueue().UnregisterForBroadcasts(this);
}
void MainLayout::ProcessMessage(musik::core::runtime::IMessage &message) {
const int type = message.Type();
if (type == message::JumpToConsole) {
this->SetLayout(consoleLayout);
}
else if (type == message::JumpToSettings) {
this->SetLayout(settingsLayout);
}
else if (type == message::JumpToLyrics) {
this->SetLayout(lyricsLayout);
}
else if (type == message::JumpToHotkeys) {
this->SetLayout(hotkeysLayout);
}
else if (type == message::JumpToLibrary) {
this->SwitchToLibraryLayout();
}
else if (type == message::JumpToPlayQueue) {
this->SwitchToPlayQueue();
}
else if (type == message::IndexerStarted) {
this->syncUpdateCount = 0;
this->Layout();
}
else if (type == message::IndexerFinished) {
this->Layout();
}
else if (type == message::IndexerProgress) {
this->syncUpdateCount = narrow_cast<int>(message.UserData1());
this->UpdateTopBannerText();
if (!topBanner->IsVisible()) {
this->Layout();
}
}
else {
LayoutBase::ProcessMessage(message);
}
}
bool MainLayout::IsLibraryConnected() {
using State = ILibrary::ConnectionState;
return library->GetConnectionState() == State::Connected;
}
void MainLayout::SetInitialLayout() {
if (library->IsConfigured()) {
this->SwitchToLibraryLayout();
}
else {
this->SetLayout(settingsLayout);
}
}
void MainLayout::SwitchToPlayQueue() {
if (IsLibraryConnected()) {
this->SetLayout(libraryLayout);
libraryLayout->KeyPress(Hotkeys::Get(Hotkeys::NavigateLibraryPlayQueue));
}
}
void MainLayout::SwitchToLibraryLayout() {
if (IsLibraryConnected()) {
if (!this->libraryLayout) {
this->libraryLayout = std::make_shared<LibraryLayout>(playback, library);
}
this->SetLayout(libraryLayout);
}
else {
this->libraryLayout.reset();
this->SetLayout(this->libraryNotConnectedLayout);
}
}
void MainLayout::OnLibraryConnectionStateChanged(ILibrary::ConnectionState state) {
auto currentLayout = this->GetLayout();
if (currentLayout == this->libraryLayout ||
currentLayout == this->libraryNotConnectedLayout)
{
this->SwitchToLibraryLayout();
}
}
void MainLayout::OnLibraryChanged(musik::core::ILibraryPtr prev, musik::core::ILibraryPtr curr) {
this->playback.Stop();
this->libraryLayout = std::make_shared<LibraryLayout>(playback, library);
this->RebindIndexerEventHandlers(prev, curr);
this->Layout();
}
void MainLayout::RebindIndexerEventHandlers(musik::core::ILibraryPtr prev, musik::core::ILibraryPtr curr) {
if (prev) {
prev->Indexer()->Started.disconnect(this);
prev->Indexer()->Finished.disconnect(this);
prev->Indexer()->Progress.disconnect(this);
}
if (curr) {
curr->Indexer()->Started.connect(this, &MainLayout::OnIndexerStarted);
curr->Indexer()->Finished.connect(this, &MainLayout::OnIndexerFinished);
curr->Indexer()->Progress.connect(this, &MainLayout::OnIndexerProgress);
}
}
void MainLayout::OnIndexerStarted() {
this->Post(message::IndexerStarted);
}
void MainLayout::OnIndexerProgress(int count) {
this->Post(message::IndexerProgress, count);
}
void MainLayout::OnIndexerFinished(int count) {
this->Post(message::IndexerFinished);
}
void MainLayout::OnTrackChanged(size_t index, musik::core::TrackPtr track) {
if (prefs->GetBool(
cube::prefs::keys::DisableWindowTitleUpdates,
cube::prefs::defaults::DisableWindowTitleUpdates))
{
return;
}
if (!track) {
App::Instance().SetTitle("musikcube");
}
else {
App::Instance().SetTitle(u8fmt(
"musikcube [%s - %s]",
track->GetString("artist").c_str(),
track->GetString("title").c_str()));
}
}
void MainLayout::RunUpdateCheck() {
if (!prefs->GetBool(cube::prefs::keys::AutoUpdateCheck, true)) {
return;
}
updateCheck.Run([this](bool updateRequired, std::string version, std::string url) {
if (updateRequired) {
UpdateCheck::ShowUpgradeAvailableOverlay(version, url);
}
});
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/security_filter_peer.h"
#include "app/gfx/codec/png_codec.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/gfx/size.h"
#include "base/string_util.h"
#include "grit/generated_resources.h"
#include "grit/renderer_resources.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkDevice.h"
#include "webkit/glue/webkit_glue.h"
SecurityFilterPeer::SecurityFilterPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer)
: original_peer_(peer),
resource_loader_bridge_(resource_loader_bridge) {
}
SecurityFilterPeer::~SecurityFilterPeer() {
}
// static
SecurityFilterPeer* SecurityFilterPeer::CreateSecurityFilterPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer,
ResourceType::Type resource_type,
const std::string& mime_type,
FilterPolicy::Type filter_policy,
int os_error) {
if (filter_policy == FilterPolicy::DONT_FILTER) {
NOTREACHED();
return NULL;
}
if (StartsWithASCII(mime_type, "image/", false)) {
// What we do with images depends on details of the |filter_policy|.
if (filter_policy == FilterPolicy::FILTER_ALL_EXCEPT_IMAGES)
return new ImageFilterPeer(resource_loader_bridge, peer);
// Otherwise, fall through to blocking images hard.
}
// Regardless of what a frame contents replace it with our error message,
// so it is visible it's been filtered-out.
if (ResourceType::IsFrame(resource_type))
return CreateSecurityFilterPeerForFrame(peer, os_error);
// Any other content is entirely filtered-out.
return new ReplaceContentPeer(resource_loader_bridge, peer,
std::string(), std::string());
}
// static
SecurityFilterPeer*
SecurityFilterPeer::CreateSecurityFilterPeerForDeniedRequest(
ResourceType::Type resource_type,
webkit_glue::ResourceLoaderBridge::Peer* peer,
int os_error) {
// Create a filter for SSL and CERT errors.
switch (os_error) {
case net::ERR_SSL_PROTOCOL_ERROR:
case net::ERR_CERT_COMMON_NAME_INVALID:
case net::ERR_CERT_DATE_INVALID:
case net::ERR_CERT_AUTHORITY_INVALID:
case net::ERR_CERT_CONTAINS_ERRORS:
case net::ERR_CERT_NO_REVOCATION_MECHANISM:
case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION:
case net::ERR_CERT_REVOKED:
case net::ERR_CERT_INVALID:
case net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM:
case net::ERR_INSECURE_RESPONSE:
if (ResourceType::IsFrame(resource_type))
return CreateSecurityFilterPeerForFrame(peer, os_error);
// Any other content is entirely filtered-out.
return new ReplaceContentPeer(NULL, peer, std::string(), std::string());
default:
// For other errors, we use our normal error handling.
return NULL;
}
}
// static
SecurityFilterPeer* SecurityFilterPeer::CreateSecurityFilterPeerForFrame(
webkit_glue::ResourceLoaderBridge::Peer* peer, int os_error) {
// TODO(jcampan): use a different message when getting a phishing/malware
// error.
std::wstring error_msg = l10n_util::GetString(IDS_UNSAFE_FRAME_MESSAGE);
std::string html = StringPrintf(
"<html><body style='background-color:#990000;color:white;'>"
"%s</body></html>",
WideToUTF8(error_msg).c_str());
return new ReplaceContentPeer(NULL, peer, "text/html", html);
}
void SecurityFilterPeer::OnUploadProgress(uint64 position, uint64 size) {
original_peer_->OnUploadProgress(position, size);
}
bool SecurityFilterPeer::OnReceivedRedirect(
const GURL& new_url,
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info) {
NOTREACHED();
return false;
}
void SecurityFilterPeer::OnReceivedResponse(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,
bool content_filtered) {
NOTREACHED();
}
void SecurityFilterPeer::OnReceivedData(const char* data, int len) {
NOTREACHED();
}
void SecurityFilterPeer::OnCompletedRequest(const URLRequestStatus& status,
const std::string& security_info) {
NOTREACHED();
}
GURL SecurityFilterPeer::GetURLForDebugging() const {
return original_peer_->GetURLForDebugging();
}
// static
void ProcessResponseInfo(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info_in,
webkit_glue::ResourceLoaderBridge::ResponseInfo* info_out,
const std::string& mime_type) {
DCHECK(info_out);
*info_out = info_in;
info_out->mime_type = mime_type;
// Let's create our own HTTP headers.
std::string raw_headers;
raw_headers.append("HTTP/1.1 200 OK");
raw_headers.push_back('\0');
// Don't cache the data we are serving, it is not the real data for that URL
// (if the filtered resource were to make it into the WebCore cache, then the
// same URL loaded in a safe scenario would still return the filtered
// resource).
raw_headers.append("cache-control: no-cache");
raw_headers.push_back('\0');
if (!mime_type.empty()) {
raw_headers.append("content-type: ");
raw_headers.append(mime_type);
raw_headers.push_back('\0');
}
raw_headers.push_back('\0');
net::HttpResponseHeaders* new_headers =
new net::HttpResponseHeaders(raw_headers);
info_out->headers = new_headers;
}
////////////////////////////////////////////////////////////////////////////////
// BufferedPeer
BufferedPeer::BufferedPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer,
const std::string& mime_type)
: SecurityFilterPeer(resource_loader_bridge, peer),
mime_type_(mime_type) {
}
BufferedPeer::~BufferedPeer() {
}
void BufferedPeer::OnReceivedResponse(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,
bool response_filtered) {
ProcessResponseInfo(info, &response_info_, mime_type_);
}
void BufferedPeer::OnReceivedData(const char* data, int len) {
data_.append(data, len);
}
void BufferedPeer::OnCompletedRequest(const URLRequestStatus& status,
const std::string& security_info) {
// Make sure we delete ourselves at the end of this call.
scoped_ptr<BufferedPeer> this_deleter(this);
// Give sub-classes a chance at altering the data.
if (status.status() != URLRequestStatus::SUCCESS || !DataReady()) {
// Pretend we failed to load the resource.
original_peer_->OnReceivedResponse(response_info_, true);
URLRequestStatus status(URLRequestStatus::CANCELED, net::ERR_ABORTED);
original_peer_->OnCompletedRequest(status, security_info);
return;
}
original_peer_->OnReceivedResponse(response_info_, true);
if (!data_.empty())
original_peer_->OnReceivedData(data_.data(),
static_cast<int>(data_.size()));
original_peer_->OnCompletedRequest(status, security_info);
}
////////////////////////////////////////////////////////////////////////////////
// ReplaceContentPeer
ReplaceContentPeer::ReplaceContentPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer,
const std::string& mime_type,
const std::string& data)
: SecurityFilterPeer(resource_loader_bridge, peer),
mime_type_(mime_type),
data_(data) {
}
ReplaceContentPeer::~ReplaceContentPeer() {
}
void ReplaceContentPeer::OnReceivedResponse(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,
bool content_filtered) {
// Ignore this, we'll serve some alternate content in OnCompletedRequest.
}
void ReplaceContentPeer::OnReceivedData(const char* data, int len) {
// Ignore this, we'll serve some alternate content in OnCompletedRequest.
}
void ReplaceContentPeer::OnCompletedRequest(const URLRequestStatus& status,
const std::string& security_info) {
webkit_glue::ResourceLoaderBridge::ResponseInfo info;
ProcessResponseInfo(info, &info, mime_type_);
info.security_info = security_info;
info.content_length = static_cast<int>(data_.size());
original_peer_->OnReceivedResponse(info, true);
if (!data_.empty())
original_peer_->OnReceivedData(data_.data(),
static_cast<int>(data_.size()));
original_peer_->OnCompletedRequest(URLRequestStatus(), security_info);
// The request processing is complete, we must delete ourselves.
delete this;
}
////////////////////////////////////////////////////////////////////////////////
// ImageFilterPeer
ImageFilterPeer::ImageFilterPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer)
: BufferedPeer(resource_loader_bridge, peer, "image/png") {
}
ImageFilterPeer::~ImageFilterPeer() {
}
bool ImageFilterPeer::DataReady() {
static SkBitmap* stamp_bitmap = NULL;
if (!stamp_bitmap) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
stamp_bitmap = rb.GetBitmapNamed(IDR_INSECURE_CONTENT_STAMP);
if (!stamp_bitmap) {
NOTREACHED();
return false;
}
}
// Let's decode the image we have been given.
SkBitmap image;
if (!webkit_glue::DecodeImage(data_, &image))
return false; // We could not decode that image.
// Let's create a new canvas to modify the image.
SkBitmap canvas_bitmap;
canvas_bitmap.setConfig(SkBitmap::kARGB_8888_Config,
image.width(), image.height());
canvas_bitmap.allocPixels();
SkCanvas canvas(canvas_bitmap);
// Let's paint the actual image with an alpha.
SkRect rect;
rect.fLeft = 0;
rect.fTop = 0;
rect.fRight = SkIntToScalar(image.width());
rect.fBottom = SkIntToScalar(image.height());
SkPaint paint;
paint.setAlpha(80);
canvas.drawBitmapRect(image, NULL, rect, &paint);
// Then stamp-it.
paint.setAlpha(150);
int visible_row_count = image.height() / stamp_bitmap->height();
if (image.height() % stamp_bitmap->height() != 0)
visible_row_count++;
for (int row = 0; row < visible_row_count; row++) {
for (int x = (row % 2 == 0) ? 0 : stamp_bitmap->width(); x < image.width();
x += stamp_bitmap->width() * 2) {
canvas.drawBitmap(*stamp_bitmap,
SkIntToScalar(x),
SkIntToScalar(row * stamp_bitmap->height()),
&paint);
}
}
// Now encode it to a PNG.
std::vector<unsigned char> output;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(
canvas.getDevice()->accessBitmap(false), false, &output)) {
return false;
}
// Copy the vector content to data_ which is a string.
data_.clear();
data_.resize(output.size());
std::copy(output.begin(), output.end(), data_.begin());
return true;
}
<commit_msg>Add 'meta charset=UTF-8' to the html of an iframe interstitial to prevent non-ASCII characters from being garbled. <commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/security_filter_peer.h"
#include "app/gfx/codec/png_codec.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/gfx/size.h"
#include "base/string_util.h"
#include "grit/generated_resources.h"
#include "grit/renderer_resources.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkDevice.h"
#include "webkit/glue/webkit_glue.h"
SecurityFilterPeer::SecurityFilterPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer)
: original_peer_(peer),
resource_loader_bridge_(resource_loader_bridge) {
}
SecurityFilterPeer::~SecurityFilterPeer() {
}
// static
SecurityFilterPeer* SecurityFilterPeer::CreateSecurityFilterPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer,
ResourceType::Type resource_type,
const std::string& mime_type,
FilterPolicy::Type filter_policy,
int os_error) {
if (filter_policy == FilterPolicy::DONT_FILTER) {
NOTREACHED();
return NULL;
}
if (StartsWithASCII(mime_type, "image/", false)) {
// What we do with images depends on details of the |filter_policy|.
if (filter_policy == FilterPolicy::FILTER_ALL_EXCEPT_IMAGES)
return new ImageFilterPeer(resource_loader_bridge, peer);
// Otherwise, fall through to blocking images hard.
}
// Regardless of what a frame contents replace it with our error message,
// so it is visible it's been filtered-out.
if (ResourceType::IsFrame(resource_type))
return CreateSecurityFilterPeerForFrame(peer, os_error);
// Any other content is entirely filtered-out.
return new ReplaceContentPeer(resource_loader_bridge, peer,
std::string(), std::string());
}
// static
SecurityFilterPeer*
SecurityFilterPeer::CreateSecurityFilterPeerForDeniedRequest(
ResourceType::Type resource_type,
webkit_glue::ResourceLoaderBridge::Peer* peer,
int os_error) {
// Create a filter for SSL and CERT errors.
switch (os_error) {
case net::ERR_SSL_PROTOCOL_ERROR:
case net::ERR_CERT_COMMON_NAME_INVALID:
case net::ERR_CERT_DATE_INVALID:
case net::ERR_CERT_AUTHORITY_INVALID:
case net::ERR_CERT_CONTAINS_ERRORS:
case net::ERR_CERT_NO_REVOCATION_MECHANISM:
case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION:
case net::ERR_CERT_REVOKED:
case net::ERR_CERT_INVALID:
case net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM:
case net::ERR_INSECURE_RESPONSE:
if (ResourceType::IsFrame(resource_type))
return CreateSecurityFilterPeerForFrame(peer, os_error);
// Any other content is entirely filtered-out.
return new ReplaceContentPeer(NULL, peer, std::string(), std::string());
default:
// For other errors, we use our normal error handling.
return NULL;
}
}
// static
SecurityFilterPeer* SecurityFilterPeer::CreateSecurityFilterPeerForFrame(
webkit_glue::ResourceLoaderBridge::Peer* peer, int os_error) {
// TODO(jcampan): use a different message when getting a phishing/malware
// error.
std::string html = StringPrintf(
"<html><meta charset='UTF-8'>"
"<body style='background-color:#990000;color:white;'>"
"%s</body></html>",
l10n_util::GetStringUTF8(IDS_UNSAFE_FRAME_MESSAGE).c_str());
return new ReplaceContentPeer(NULL, peer, "text/html", html);
}
void SecurityFilterPeer::OnUploadProgress(uint64 position, uint64 size) {
original_peer_->OnUploadProgress(position, size);
}
bool SecurityFilterPeer::OnReceivedRedirect(
const GURL& new_url,
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info) {
NOTREACHED();
return false;
}
void SecurityFilterPeer::OnReceivedResponse(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,
bool content_filtered) {
NOTREACHED();
}
void SecurityFilterPeer::OnReceivedData(const char* data, int len) {
NOTREACHED();
}
void SecurityFilterPeer::OnCompletedRequest(const URLRequestStatus& status,
const std::string& security_info) {
NOTREACHED();
}
GURL SecurityFilterPeer::GetURLForDebugging() const {
return original_peer_->GetURLForDebugging();
}
// static
void ProcessResponseInfo(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info_in,
webkit_glue::ResourceLoaderBridge::ResponseInfo* info_out,
const std::string& mime_type) {
DCHECK(info_out);
*info_out = info_in;
info_out->mime_type = mime_type;
// Let's create our own HTTP headers.
std::string raw_headers;
raw_headers.append("HTTP/1.1 200 OK");
raw_headers.push_back('\0');
// Don't cache the data we are serving, it is not the real data for that URL
// (if the filtered resource were to make it into the WebCore cache, then the
// same URL loaded in a safe scenario would still return the filtered
// resource).
raw_headers.append("cache-control: no-cache");
raw_headers.push_back('\0');
if (!mime_type.empty()) {
raw_headers.append("content-type: ");
raw_headers.append(mime_type);
raw_headers.push_back('\0');
}
raw_headers.push_back('\0');
net::HttpResponseHeaders* new_headers =
new net::HttpResponseHeaders(raw_headers);
info_out->headers = new_headers;
}
////////////////////////////////////////////////////////////////////////////////
// BufferedPeer
BufferedPeer::BufferedPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer,
const std::string& mime_type)
: SecurityFilterPeer(resource_loader_bridge, peer),
mime_type_(mime_type) {
}
BufferedPeer::~BufferedPeer() {
}
void BufferedPeer::OnReceivedResponse(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,
bool response_filtered) {
ProcessResponseInfo(info, &response_info_, mime_type_);
}
void BufferedPeer::OnReceivedData(const char* data, int len) {
data_.append(data, len);
}
void BufferedPeer::OnCompletedRequest(const URLRequestStatus& status,
const std::string& security_info) {
// Make sure we delete ourselves at the end of this call.
scoped_ptr<BufferedPeer> this_deleter(this);
// Give sub-classes a chance at altering the data.
if (status.status() != URLRequestStatus::SUCCESS || !DataReady()) {
// Pretend we failed to load the resource.
original_peer_->OnReceivedResponse(response_info_, true);
URLRequestStatus status(URLRequestStatus::CANCELED, net::ERR_ABORTED);
original_peer_->OnCompletedRequest(status, security_info);
return;
}
original_peer_->OnReceivedResponse(response_info_, true);
if (!data_.empty())
original_peer_->OnReceivedData(data_.data(),
static_cast<int>(data_.size()));
original_peer_->OnCompletedRequest(status, security_info);
}
////////////////////////////////////////////////////////////////////////////////
// ReplaceContentPeer
ReplaceContentPeer::ReplaceContentPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer,
const std::string& mime_type,
const std::string& data)
: SecurityFilterPeer(resource_loader_bridge, peer),
mime_type_(mime_type),
data_(data) {
}
ReplaceContentPeer::~ReplaceContentPeer() {
}
void ReplaceContentPeer::OnReceivedResponse(
const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,
bool content_filtered) {
// Ignore this, we'll serve some alternate content in OnCompletedRequest.
}
void ReplaceContentPeer::OnReceivedData(const char* data, int len) {
// Ignore this, we'll serve some alternate content in OnCompletedRequest.
}
void ReplaceContentPeer::OnCompletedRequest(const URLRequestStatus& status,
const std::string& security_info) {
webkit_glue::ResourceLoaderBridge::ResponseInfo info;
ProcessResponseInfo(info, &info, mime_type_);
info.security_info = security_info;
info.content_length = static_cast<int>(data_.size());
original_peer_->OnReceivedResponse(info, true);
if (!data_.empty())
original_peer_->OnReceivedData(data_.data(),
static_cast<int>(data_.size()));
original_peer_->OnCompletedRequest(URLRequestStatus(), security_info);
// The request processing is complete, we must delete ourselves.
delete this;
}
////////////////////////////////////////////////////////////////////////////////
// ImageFilterPeer
ImageFilterPeer::ImageFilterPeer(
webkit_glue::ResourceLoaderBridge* resource_loader_bridge,
webkit_glue::ResourceLoaderBridge::Peer* peer)
: BufferedPeer(resource_loader_bridge, peer, "image/png") {
}
ImageFilterPeer::~ImageFilterPeer() {
}
bool ImageFilterPeer::DataReady() {
static SkBitmap* stamp_bitmap = NULL;
if (!stamp_bitmap) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
stamp_bitmap = rb.GetBitmapNamed(IDR_INSECURE_CONTENT_STAMP);
if (!stamp_bitmap) {
NOTREACHED();
return false;
}
}
// Let's decode the image we have been given.
SkBitmap image;
if (!webkit_glue::DecodeImage(data_, &image))
return false; // We could not decode that image.
// Let's create a new canvas to modify the image.
SkBitmap canvas_bitmap;
canvas_bitmap.setConfig(SkBitmap::kARGB_8888_Config,
image.width(), image.height());
canvas_bitmap.allocPixels();
SkCanvas canvas(canvas_bitmap);
// Let's paint the actual image with an alpha.
SkRect rect;
rect.fLeft = 0;
rect.fTop = 0;
rect.fRight = SkIntToScalar(image.width());
rect.fBottom = SkIntToScalar(image.height());
SkPaint paint;
paint.setAlpha(80);
canvas.drawBitmapRect(image, NULL, rect, &paint);
// Then stamp-it.
paint.setAlpha(150);
int visible_row_count = image.height() / stamp_bitmap->height();
if (image.height() % stamp_bitmap->height() != 0)
visible_row_count++;
for (int row = 0; row < visible_row_count; row++) {
for (int x = (row % 2 == 0) ? 0 : stamp_bitmap->width(); x < image.width();
x += stamp_bitmap->width() * 2) {
canvas.drawBitmap(*stamp_bitmap,
SkIntToScalar(x),
SkIntToScalar(row * stamp_bitmap->height()),
&paint);
}
}
// Now encode it to a PNG.
std::vector<unsigned char> output;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(
canvas.getDevice()->accessBitmap(false), false, &output)) {
return false;
}
// Copy the vector content to data_ which is a string.
data_.clear();
data_.resize(output.size());
std::copy(output.begin(), output.end(), data_.begin());
return true;
}
<|endoftext|> |
<commit_before>//
// THIS CONTAINS THE IMPLEMENTATION FOR PUBLISHING ON-BOARD CAMERA IMAGES
// ON CRAZYFLIE USING THE CAMERA PUBLISHER CLASS
//
// COPYRIGHT BELONGS TO THE AUTHOR OF THIS CODE
//
// AUTHOR : LAKSHMAN KUMAR
// AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER
// EMAIL : LKUMAR93@UMD.EDU
// LINKEDIN : WWW.LINKEDIN.COM/IN/LAKSHMANKUMAR1993
//
// THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THE MIT LICENSE
// THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF
// THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
//
// BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO
// BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS
// CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
// CONDITIONS.
//
///////////////////////////////////////////
//
// LIBRARIES
//
///////////////////////////////////////////
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <string>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <sensor_msgs/image_encodings.h>
#include <image_transport/image_transport.h>
#include <camera_info_manager/camera_info_manager.h>
#include <deep_learning_crazyflie/camera_parameters.h>
using namespace cv;
using namespace std;
///////////////////////////////////////////
//
// CLASSES
//
///////////////////////////////////////////
class CameraPublisher
{
//Declare all the necessary variables
string camera_position;
int camera_input_id ;
VideoCapture cap;
Mat InputImage;
image_transport::CameraPublisher camera_pub;
string prefix = "crazyflie/cameras/";
string postfix = "/image" ;
string camera_topic_name ;
sensor_msgs::CameraInfo* camera_info;
sensor_msgs::CameraInfoPtr camera_info_ptr;
public:
//Use the constructor to initialize variables
CameraPublisher(string position, int id, image_transport::ImageTransport ImageTransporter, double FL_X ,double PP_X ,double FL_Y, double PP_Y, double* DistArray)
{
camera_position = position ;
camera_input_id = id ;
camera_topic_name = prefix + camera_position + postfix ;
camera_pub = ImageTransporter.advertiseCamera(camera_topic_name, 1);
camera_info = new sensor_msgs::CameraInfo ();
camera_info_ptr = sensor_msgs::CameraInfoPtr (camera_info);
camera_info_ptr->header.frame_id = camera_position+"_camera";
camera_info->header.frame_id = camera_position+"_camera";
camera_info->width = 640;
camera_info->height = 480;
camera_info->K.at(0) = FL_X;
camera_info->K.at(2) = PP_X;
camera_info->K.at(4) = FL_Y;
camera_info->K.at(5) = PP_Y;
camera_info->K.at(8) = 1;
camera_info->P.at(0) = camera_info->K.at(0);
camera_info->P.at(1) = 0;
camera_info->P.at(2) = camera_info->K.at(2);
camera_info->P.at(3) = 0;
camera_info->P.at(4) = 0;
camera_info->P.at(5) = camera_info->K.at(4);
camera_info->P.at(6) = camera_info->K.at(5);
camera_info->P.at(7) = 0;
camera_info->P.at(8) = 0;
camera_info->P.at(9) = 0;
camera_info->P.at(10) = 1;
camera_info->P.at(11) = 0;
camera_info->distortion_model = "plumb_bob";
// Make Rotation Matrix an identity matrix
camera_info->R.at(0) = (double) 1;
camera_info->R.at(1) = (double) 0;
camera_info->R.at(2) = (double) 0;
camera_info->R.at(3) = (double) 0;
camera_info->R.at(4) = (double) 1;
camera_info->R.at(5) = (double) 0;
camera_info->R.at(6) = (double) 0;
camera_info->R.at(7) = (double) 0;
camera_info->R.at(8) = (double) 1;
for (int i = 0; i < 5; i++)
camera_info->D.push_back (DistArray[i]);
}
// Initialize the camera
bool Initialize()
{
cap.open(camera_input_id);
if( !cap.isOpened() )
{
ROS_ERROR("Could not initialize camera with id : %d ",camera_input_id);
return false;
}
return true;
}
// Publish the image from the camera to the corresponding topic
void Publish()
{
cap >> InputImage;
if( InputImage.empty() )
{
ROS_INFO("Empty image from camera with id : %d ",camera_input_id);
}
else
{
sensor_msgs::ImagePtr msg;
msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", InputImage).toImageMsg();
msg->header.stamp = ros::Time::now() ;
msg->header.frame_id = camera_position+"_camera";
camera_info->header.stamp = ros::Time::now();
camera_pub.publish(msg, camera_info_ptr) ;
}
}
};
///////////////////////////////////////////
//
// MAIN FUNCTION
//
///////////////////////////////////////////
int main( int argc, char** argv )
{
//Initialize the Crazyflie Camera Publisher Node
ros::init(argc, argv, "crazyflie_camera_node");
ros::NodeHandle nh;
image_transport::ImageTransport it(nh);
int camera_id;
nh.param<int>("/crazyflie/crazyflie_camera_node/cameras/bottom/id", camera_id, 0);
//Create a publisher for the bottom facing camera
CameraPublisher bottom_camera_pub("bottom", camera_id, it, FocalLength_X, FocalLength_Y, PrincipalPoint_X, PrincipalPoint_Y, Distortion);
//Initialize the camera and check for errors
bool Initialized = bottom_camera_pub.Initialize();
//If the camera has been initialized and everything is ok , publish the images from the camera
while(nh.ok() && Initialized)
{
bottom_camera_pub.Publish() ;
}
return 0;
}
<commit_msg>Change param id argument<commit_after>//
// THIS CONTAINS THE IMPLEMENTATION FOR PUBLISHING ON-BOARD CAMERA IMAGES
// ON CRAZYFLIE USING THE CAMERA PUBLISHER CLASS
//
// COPYRIGHT BELONGS TO THE AUTHOR OF THIS CODE
//
// AUTHOR : LAKSHMAN KUMAR
// AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER
// EMAIL : LKUMAR93@UMD.EDU
// LINKEDIN : WWW.LINKEDIN.COM/IN/LAKSHMANKUMAR1993
//
// THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THE MIT LICENSE
// THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF
// THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
//
// BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO
// BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS
// CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
// CONDITIONS.
//
///////////////////////////////////////////
//
// LIBRARIES
//
///////////////////////////////////////////
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <string>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <sensor_msgs/image_encodings.h>
#include <image_transport/image_transport.h>
#include <camera_info_manager/camera_info_manager.h>
#include <deep_learning_crazyflie/camera_parameters.h>
using namespace cv;
using namespace std;
///////////////////////////////////////////
//
// CLASSES
//
///////////////////////////////////////////
class CameraPublisher
{
//Declare all the necessary variables
string camera_position;
int camera_input_id ;
VideoCapture cap;
Mat InputImage;
image_transport::CameraPublisher camera_pub;
string prefix = "crazyflie/cameras/";
string postfix = "/image" ;
string camera_topic_name ;
sensor_msgs::CameraInfo* camera_info;
sensor_msgs::CameraInfoPtr camera_info_ptr;
public:
//Use the constructor to initialize variables
CameraPublisher(string position, int id, image_transport::ImageTransport ImageTransporter, double FL_X ,double PP_X ,double FL_Y, double PP_Y, double* DistArray)
{
camera_position = position ;
camera_input_id = id ;
camera_topic_name = prefix + camera_position + postfix ;
camera_pub = ImageTransporter.advertiseCamera(camera_topic_name, 1);
camera_info = new sensor_msgs::CameraInfo ();
camera_info_ptr = sensor_msgs::CameraInfoPtr (camera_info);
camera_info_ptr->header.frame_id = camera_position+"_camera";
camera_info->header.frame_id = camera_position+"_camera";
camera_info->width = 640;
camera_info->height = 480;
camera_info->K.at(0) = FL_X;
camera_info->K.at(2) = PP_X;
camera_info->K.at(4) = FL_Y;
camera_info->K.at(5) = PP_Y;
camera_info->K.at(8) = 1;
camera_info->P.at(0) = camera_info->K.at(0);
camera_info->P.at(1) = 0;
camera_info->P.at(2) = camera_info->K.at(2);
camera_info->P.at(3) = 0;
camera_info->P.at(4) = 0;
camera_info->P.at(5) = camera_info->K.at(4);
camera_info->P.at(6) = camera_info->K.at(5);
camera_info->P.at(7) = 0;
camera_info->P.at(8) = 0;
camera_info->P.at(9) = 0;
camera_info->P.at(10) = 1;
camera_info->P.at(11) = 0;
camera_info->distortion_model = "plumb_bob";
// Make Rotation Matrix an identity matrix
camera_info->R.at(0) = (double) 1;
camera_info->R.at(1) = (double) 0;
camera_info->R.at(2) = (double) 0;
camera_info->R.at(3) = (double) 0;
camera_info->R.at(4) = (double) 1;
camera_info->R.at(5) = (double) 0;
camera_info->R.at(6) = (double) 0;
camera_info->R.at(7) = (double) 0;
camera_info->R.at(8) = (double) 1;
for (int i = 0; i < 5; i++)
camera_info->D.push_back (DistArray[i]);
}
// Initialize the camera
bool Initialize()
{
cap.open(camera_input_id);
if( !cap.isOpened() )
{
ROS_ERROR("Could not initialize camera with id : %d ",camera_input_id);
return false;
}
return true;
}
// Publish the image from the camera to the corresponding topic
void Publish()
{
cap >> InputImage;
if( InputImage.empty() )
{
ROS_INFO("Empty image from camera with id : %d ",camera_input_id);
}
else
{
sensor_msgs::ImagePtr msg;
msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", InputImage).toImageMsg();
msg->header.stamp = ros::Time::now() ;
msg->header.frame_id = camera_position+"_camera";
camera_info->header.stamp = ros::Time::now();
camera_pub.publish(msg, camera_info_ptr) ;
}
}
};
///////////////////////////////////////////
//
// MAIN FUNCTION
//
///////////////////////////////////////////
int main( int argc, char** argv )
{
//Initialize the Crazyflie Camera Publisher Node
ros::init(argc, argv, "crazyflie_camera_node");
ros::NodeHandle nh;
image_transport::ImageTransport it(nh);
int camera_id;
nh.param<int>("crazyflie_camera_node/cameras/bottom/id", camera_id, 0);
//Create a publisher for the bottom facing camera
CameraPublisher bottom_camera_pub("bottom", camera_id, it, FocalLength_X, FocalLength_Y, PrincipalPoint_X, PrincipalPoint_Y, Distortion);
//Initialize the camera and check for errors
bool Initialized = bottom_camera_pub.Initialize();
//If the camera has been initialized and everything is ok , publish the images from the camera
while(nh.ok() && Initialized)
{
bottom_camera_pub.Publish() ;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "trikQtsGeneratorPlugin.h"
#include <QtWidgets/QApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <trikGeneratorBase/trikGeneratorPluginBase.h>
#include <utils/tcpRobotCommunicator.h>
#include "trikQtsMasterGenerator.h"
using namespace trik::qts;
using namespace qReal;
TrikQtsGeneratorPlugin::TrikQtsGeneratorPlugin()
: mGenerateCodeAction(new QAction(nullptr))
, mUploadProgramAction(new QAction(nullptr))
, mRunProgramAction(new QAction(nullptr))
, mStopRobotAction(new QAction(nullptr))
, mCommunicator(nullptr)
{
}
TrikQtsGeneratorPlugin::~TrikQtsGeneratorPlugin()
{
delete mCommunicator;
}
void TrikQtsGeneratorPlugin::init(qReal::PluginConfigurator const &configurator
, interpreterBase::robotModel::RobotModelManagerInterface const &robotModelManager
, qrtext::LanguageToolboxInterface &textLanguage)
{
RobotsGeneratorPluginBase::init(configurator, robotModelManager, textLanguage);
mCommunicator = new utils::TcpRobotCommunicator("TrikTcpServer");
mCommunicator->setErrorReporter(configurator.mainWindowInterpretersInterface().errorReporter());
}
QList<ActionInfo> TrikQtsGeneratorPlugin::actions()
{
QAction *separator = new QAction(this);
separator->setSeparator(true);
qReal::ActionInfo separatorInfo(separator, "generators", "tools");
mGenerateCodeAction->setText(tr("Generate TRIK code"));
mGenerateCodeAction->setIcon(QIcon(":/images/generateQtsCode.svg"));
ActionInfo generateCodeActionInfo(mGenerateCodeAction, "generators", "tools");
connect(mGenerateCodeAction, SIGNAL(triggered()), this, SLOT(generateCode()), Qt::UniqueConnection);
mUploadProgramAction->setText(tr("Upload program"));
mUploadProgramAction->setIcon(QIcon(":/images/uploadProgram.svg"));
ActionInfo uploadProgramActionInfo(mUploadProgramAction, "generators", "tools");
connect(mUploadProgramAction, SIGNAL(triggered()), this, SLOT(uploadProgram()), Qt::UniqueConnection);
mRunProgramAction->setText(tr("Run program"));
mRunProgramAction->setIcon(QIcon(":/images/uploadAndExecuteProgram.svg"));
ActionInfo runProgramActionInfo(mRunProgramAction, "generators", "tools");
connect(mRunProgramAction, SIGNAL(triggered()), this, SLOT(runProgram()), Qt::UniqueConnection);
mStopRobotAction->setText(tr("Stop robot"));
mStopRobotAction->setIcon(QIcon(":/images/stopRobot.svg"));
ActionInfo stopRobotActionInfo(mStopRobotAction, "generators", "tools");
connect(mStopRobotAction, SIGNAL(triggered()), this, SLOT(stopRobot()), Qt::UniqueConnection);
return {generateCodeActionInfo, uploadProgramActionInfo, runProgramActionInfo, stopRobotActionInfo, separatorInfo};
}
QList<HotKeyActionInfo> TrikQtsGeneratorPlugin::hotKeyActions()
{
mGenerateCodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_G));
mUploadProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
mRunProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F5));
mStopRobotAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F5));
HotKeyActionInfo generateCodeInfo("Generator.GenerateTrik", tr("Generate TRIK Code"), mGenerateCodeAction);
HotKeyActionInfo uploadProgramInfo("Generator.UploadTrik", tr("Upload TRIK Program"), mUploadProgramAction);
HotKeyActionInfo runProgramInfo("Generator.RunTrik", tr("Run TRIK Program"), mRunProgramAction);
HotKeyActionInfo stopRobotInfo("Generator.StopTrik", tr("Stop TRIK Robot"), mStopRobotAction);
return { generateCodeInfo, uploadProgramInfo, runProgramInfo, stopRobotInfo };
}
generatorBase::MasterGeneratorBase *TrikQtsGeneratorPlugin::masterGenerator()
{
return new TrikQtsMasterGenerator(*mRepo
, *mMainWindowInterface->errorReporter()
, *mRobotModelManager
, *mTextLanguage
, mMainWindowInterface->activeDiagram()
, generatorName());
}
QString TrikQtsGeneratorPlugin::defaultFilePath(QString const &projectName) const
{
return QString("trik/%1/%1.qts").arg(projectName);
}
text::LanguageInfo TrikQtsGeneratorPlugin::language() const
{
return qReal::text::Languages::qtScript({ "brick" });
}
QString TrikQtsGeneratorPlugin::generatorName() const
{
return "trikQts";
}
bool TrikQtsGeneratorPlugin::uploadProgram()
{
QFileInfo const fileInfo = generateCodeForProcessing();
if (fileInfo != QFileInfo() && !fileInfo.absoluteFilePath().isEmpty()) {
bool const result = mCommunicator->uploadProgram(fileInfo.absoluteFilePath());
if (!result) {
mMainWindowInterface->errorReporter()->addError(tr("No connection to robot"));
}
return result;
} else {
qDebug() << "Code generation failed, aborting";
return false;
}
}
void TrikQtsGeneratorPlugin::runProgram()
{
if (uploadProgram()) {
QFileInfo const fileInfo = generateCodeForProcessing();
mCommunicator->runProgram(fileInfo.fileName());
} else {
qDebug() << "Program upload failed, aborting";
}
}
void TrikQtsGeneratorPlugin::stopRobot()
{
if (!mCommunicator->stopRobot()) {
mMainWindowInterface->errorReporter()->addError(tr("No connection to robot"));
}
mCommunicator->runDirectCommand(
"brick.system(\"killall aplay\"); \n"
"brick.system(\"killall vlc\"); \n"
"brick.system(\"killall rover-cv\");"
, true
);
}
<commit_msg>rover-cv removed<commit_after>#include "trikQtsGeneratorPlugin.h"
#include <QtWidgets/QApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <trikGeneratorBase/trikGeneratorPluginBase.h>
#include <utils/tcpRobotCommunicator.h>
#include "trikQtsMasterGenerator.h"
using namespace trik::qts;
using namespace qReal;
TrikQtsGeneratorPlugin::TrikQtsGeneratorPlugin()
: mGenerateCodeAction(new QAction(nullptr))
, mUploadProgramAction(new QAction(nullptr))
, mRunProgramAction(new QAction(nullptr))
, mStopRobotAction(new QAction(nullptr))
, mCommunicator(nullptr)
{
}
TrikQtsGeneratorPlugin::~TrikQtsGeneratorPlugin()
{
delete mCommunicator;
}
void TrikQtsGeneratorPlugin::init(qReal::PluginConfigurator const &configurator
, interpreterBase::robotModel::RobotModelManagerInterface const &robotModelManager
, qrtext::LanguageToolboxInterface &textLanguage)
{
RobotsGeneratorPluginBase::init(configurator, robotModelManager, textLanguage);
mCommunicator = new utils::TcpRobotCommunicator("TrikTcpServer");
mCommunicator->setErrorReporter(configurator.mainWindowInterpretersInterface().errorReporter());
}
QList<ActionInfo> TrikQtsGeneratorPlugin::actions()
{
QAction *separator = new QAction(this);
separator->setSeparator(true);
qReal::ActionInfo separatorInfo(separator, "generators", "tools");
mGenerateCodeAction->setText(tr("Generate TRIK code"));
mGenerateCodeAction->setIcon(QIcon(":/images/generateQtsCode.svg"));
ActionInfo generateCodeActionInfo(mGenerateCodeAction, "generators", "tools");
connect(mGenerateCodeAction, SIGNAL(triggered()), this, SLOT(generateCode()), Qt::UniqueConnection);
mUploadProgramAction->setText(tr("Upload program"));
mUploadProgramAction->setIcon(QIcon(":/images/uploadProgram.svg"));
ActionInfo uploadProgramActionInfo(mUploadProgramAction, "generators", "tools");
connect(mUploadProgramAction, SIGNAL(triggered()), this, SLOT(uploadProgram()), Qt::UniqueConnection);
mRunProgramAction->setText(tr("Run program"));
mRunProgramAction->setIcon(QIcon(":/images/uploadAndExecuteProgram.svg"));
ActionInfo runProgramActionInfo(mRunProgramAction, "generators", "tools");
connect(mRunProgramAction, SIGNAL(triggered()), this, SLOT(runProgram()), Qt::UniqueConnection);
mStopRobotAction->setText(tr("Stop robot"));
mStopRobotAction->setIcon(QIcon(":/images/stopRobot.svg"));
ActionInfo stopRobotActionInfo(mStopRobotAction, "generators", "tools");
connect(mStopRobotAction, SIGNAL(triggered()), this, SLOT(stopRobot()), Qt::UniqueConnection);
return {generateCodeActionInfo, uploadProgramActionInfo, runProgramActionInfo, stopRobotActionInfo, separatorInfo};
}
QList<HotKeyActionInfo> TrikQtsGeneratorPlugin::hotKeyActions()
{
mGenerateCodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_G));
mUploadProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
mRunProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F5));
mStopRobotAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F5));
HotKeyActionInfo generateCodeInfo("Generator.GenerateTrik", tr("Generate TRIK Code"), mGenerateCodeAction);
HotKeyActionInfo uploadProgramInfo("Generator.UploadTrik", tr("Upload TRIK Program"), mUploadProgramAction);
HotKeyActionInfo runProgramInfo("Generator.RunTrik", tr("Run TRIK Program"), mRunProgramAction);
HotKeyActionInfo stopRobotInfo("Generator.StopTrik", tr("Stop TRIK Robot"), mStopRobotAction);
return { generateCodeInfo, uploadProgramInfo, runProgramInfo, stopRobotInfo };
}
generatorBase::MasterGeneratorBase *TrikQtsGeneratorPlugin::masterGenerator()
{
return new TrikQtsMasterGenerator(*mRepo
, *mMainWindowInterface->errorReporter()
, *mRobotModelManager
, *mTextLanguage
, mMainWindowInterface->activeDiagram()
, generatorName());
}
QString TrikQtsGeneratorPlugin::defaultFilePath(QString const &projectName) const
{
return QString("trik/%1/%1.qts").arg(projectName);
}
text::LanguageInfo TrikQtsGeneratorPlugin::language() const
{
return qReal::text::Languages::qtScript({ "brick" });
}
QString TrikQtsGeneratorPlugin::generatorName() const
{
return "trikQts";
}
bool TrikQtsGeneratorPlugin::uploadProgram()
{
QFileInfo const fileInfo = generateCodeForProcessing();
if (fileInfo != QFileInfo() && !fileInfo.absoluteFilePath().isEmpty()) {
bool const result = mCommunicator->uploadProgram(fileInfo.absoluteFilePath());
if (!result) {
mMainWindowInterface->errorReporter()->addError(tr("No connection to robot"));
}
return result;
} else {
qDebug() << "Code generation failed, aborting";
return false;
}
}
void TrikQtsGeneratorPlugin::runProgram()
{
if (uploadProgram()) {
QFileInfo const fileInfo = generateCodeForProcessing();
mCommunicator->runProgram(fileInfo.fileName());
} else {
qDebug() << "Program upload failed, aborting";
}
}
void TrikQtsGeneratorPlugin::stopRobot()
{
if (!mCommunicator->stopRobot()) {
mMainWindowInterface->errorReporter()->addError(tr("No connection to robot"));
}
mCommunicator->runDirectCommand(
"brick.system(\"killall aplay\"); \n"
"brick.system(\"killall vlc\");"
, true
);
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* 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 Willow Garage, Inc. 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.
*
* $Id$
*/
#ifndef PCL_PCA_IMPL_HPP
#define PCL_PCA_IMPL_HPP
#include <Eigen/Eigenvalues>
#include "pcl/point_types.h"
#include "pcl/common/centroid.h"
#include "pcl/common/transforms.h"
#include "pcl/exceptions.h"
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT>
pcl::PCA<PointT>::PCA (const pcl::PointCloud<PointT>& X, bool basis_only)
{
Base ();
basis_only_ = basis_only;
setInputCloud (X.makeShared ());
compute_done_ = initCompute ();
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> bool
pcl::PCA<PointT>::initCompute ()
{
if(!Base::initCompute ())
{
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] failed");
return (false);
}
if(indices_->size () < 3)
{
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] number of points < 3");
return (false);
}
// Compute mean
mean_ = Eigen::Vector4f::Zero ();
compute3DCentroid (*input_, *indices_, mean_);
// Compute demeanished cloud
Eigen::MatrixXf cloud_demean;
demeanPointCloud (*input_, *indices_, mean_, cloud_demean);
assert (cloud_demean.cols () == int (indices_->size ()));
// Compute the product cloud_demean * cloud_demean^T
Eigen::Matrix3f alpha = cloud_demean.topRows<3> () * cloud_demean.topRows<3> ().transpose ();
// Compute eigen vectors and values
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> evd (alpha);
// Organize eigenvectors and eigenvalues in ascendent order
for (int i = 0; i < 3; ++i)
{
eigenvalues_[i] = evd.eigenvalues () [2-i];
eigenvectors_.col (i) = evd.eigenvectors ().col (2-i);
}
// If not basis only then compute the coefficients
if (!basis_only_)
// 3x3 = 3x3 * 3x3
coefficients_ = eigenvectors_.transpose() * (cloud_demean.topRows<3>()).leftCols<3> ();
compute_done_ = true;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::update (const PointT& input_point, FLAG flag)
{
if (!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::update] PCA initCompute failed");
Eigen::Vector3f input (input_point.x, input_point.y, input_point.z);
const size_t n = eigenvectors_.cols ();// number of eigen vectors
Eigen::VectorXf meanp = (float(n) * (mean_.head<3>() + input)) / float(n + 1);
Eigen::VectorXf a = eigenvectors_.transpose() * (input - mean_.head<3>());
Eigen::VectorXf y = (eigenvectors_ * a) + mean_.head<3>();
Eigen::VectorXf h = y - input;
if (h.norm() > 0)
h.normalize ();
else
h.setZero ();
float gamma = h.dot(input - mean_.head<3>());
Eigen::MatrixXf D = Eigen::MatrixXf::Zero (a.size() + 1, a.size() + 1);
D.block(0,0,n,n) = a * a.transpose();
D /= float(n)/float((n+1) * (n+1));
for(std::size_t i=0; i < a.size(); i++) {
D(i,i)+= float(n)/float(n+1)*eigenvalues_(i);
D(D.rows()-1,i) = float(n) / float((n+1) * (n+1)) * gamma * a(i);
D(i,D.cols()-1) = D(D.rows()-1,i);
D(D.rows()-1,D.cols()-1) = float(n)/float((n+1) * (n+1)) * gamma * gamma;
}
Eigen::MatrixXf R(D.rows(), D.cols());
Eigen::EigenSolver<Eigen::MatrixXf> D_evd (D, false);
Eigen::VectorXf alphap = D_evd.eigenvalues().real();
eigenvalues_.resize(eigenvalues_.size() +1);
for(std::size_t i=0;i<eigenvalues_.size();i++) {
eigenvalues_(i) = alphap(eigenvalues_.size()-i-1);
R.col(i) = D.col(D.cols()-i-1);
}
Eigen::MatrixXf Up = Eigen::MatrixXf::Zero(eigenvectors_.rows(), eigenvectors_.cols()+1);
Up.topLeftCorner(eigenvectors_.rows(),eigenvectors_.cols()) = eigenvectors_;
Up.rightCols<1>() = h;
eigenvectors_ = Up*R;
if (!basis_only_) {
Eigen::Vector3f etha = Up.transpose() * (mean_.head<3>() - meanp);
coefficients_.resize(coefficients_.rows()+1,coefficients_.cols()+1);
for(std::size_t i=0; i < (coefficients_.cols() - 1); i++) {
coefficients_(coefficients_.rows()-1,i) = 0;
coefficients_.col(i) = (R.transpose() * coefficients_.col(i)) + etha;
}
a.resize(a.size()+1);
a(a.size()-1) = 0;
coefficients_.col(coefficients_.cols()-1) = (R.transpose() * a) + etha;
}
mean_.head<3>() = meanp;
switch (flag)
{
case increase:
if (eigenvectors_.rows() >= eigenvectors_.cols())
break;
case preserve:
if (!basis_only_)
coefficients_ = coefficients_.topRows(coefficients_.rows() - 1);
eigenvectors_ = eigenvectors_.leftCols(eigenvectors_.cols() - 1);
eigenvalues_.resize(eigenvalues_.size()-1);
break;
default:
PCL_ERROR("[pcl::PCA] unknown flag\n");
}
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::project (const PointT& input, PointT& projection)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed");
Eigen::Vector3f demean_input = input.getVector3fMap () - mean_.head<3> ();
projection.getVector3fMap () = eigenvectors_.transpose() * demean_input;
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::project (const PointCloud& input, PointCloud& projection)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed");
if (input.is_dense)
{
projection.resize (input.size ());
for (size_t i = 0; i < input.size (); ++i)
project (input[i], projection[i]);
}
else
{
PointT p;
for (size_t i = 0; i < input.size (); ++i)
{
if (!pcl_isfinite (input[i].x) ||
!pcl_isfinite (input[i].y) ||
!pcl_isfinite (input[i].z))
continue;
project (input[i], p);
projection.push_back (p);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::reconstruct (const PointT& projection, PointT& input)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed");
input.getVector3fMap ()= eigenvectors_ * projection.getVector3fMap ();
input.getVector3fMap ()+= mean_.head<3> ();
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::reconstruct (const PointCloud& projection, PointCloud& input)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed");
if (input.is_dense)
{
input.resize (projection.size ());
for (size_t i = 0; i < projection.size (); ++i)
reconstruct (projection[i], input[i]);
}
else
{
PointT p;
for (size_t i = 0; i < input.size (); ++i)
{
if (!pcl_isfinite (input[i].x) ||
!pcl_isfinite (input[i].y) ||
!pcl_isfinite (input[i].z))
continue;
reconstruct (projection[i], p);
input.push_back (p);
}
}
}
#endif
<commit_msg>Correct coeffcients formula<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* 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 Willow Garage, Inc. 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.
*
* $Id$
*/
#ifndef PCL_PCA_IMPL_HPP
#define PCL_PCA_IMPL_HPP
#include <Eigen/Eigenvalues>
#include "pcl/point_types.h"
#include "pcl/common/centroid.h"
#include "pcl/common/transforms.h"
#include "pcl/exceptions.h"
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT>
pcl::PCA<PointT>::PCA (const pcl::PointCloud<PointT>& X, bool basis_only)
{
Base ();
basis_only_ = basis_only;
setInputCloud (X.makeShared ());
compute_done_ = initCompute ();
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> bool
pcl::PCA<PointT>::initCompute ()
{
if(!Base::initCompute ())
{
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] failed");
return (false);
}
if(indices_->size () < 3)
{
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] number of points < 3");
return (false);
}
// Compute mean
mean_ = Eigen::Vector4f::Zero ();
compute3DCentroid (*input_, *indices_, mean_);
// Compute demeanished cloud
Eigen::MatrixXf cloud_demean;
demeanPointCloud (*input_, *indices_, mean_, cloud_demean);
assert (cloud_demean.cols () == int (indices_->size ()));
// Compute the product cloud_demean * cloud_demean^T
Eigen::Matrix3f alpha = cloud_demean.topRows<3> () * cloud_demean.topRows<3> ().transpose ();
// Compute eigen vectors and values
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> evd (alpha);
// Organize eigenvectors and eigenvalues in ascendent order
for (int i = 0; i < 3; ++i)
{
eigenvalues_[i] = evd.eigenvalues () [2-i];
eigenvectors_.col (i) = evd.eigenvectors ().col (2-i);
}
// If not basis only then compute the coefficients
if (!basis_only_)
coefficients_ = eigenvectors_.transpose() * cloud_demean.topRows<3> ();
compute_done_ = true;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::update (const PointT& input_point, FLAG flag)
{
if (!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::update] PCA initCompute failed");
Eigen::Vector3f input (input_point.x, input_point.y, input_point.z);
const size_t n = eigenvectors_.cols ();// number of eigen vectors
Eigen::VectorXf meanp = (float(n) * (mean_.head<3>() + input)) / float(n + 1);
Eigen::VectorXf a = eigenvectors_.transpose() * (input - mean_.head<3>());
Eigen::VectorXf y = (eigenvectors_ * a) + mean_.head<3>();
Eigen::VectorXf h = y - input;
if (h.norm() > 0)
h.normalize ();
else
h.setZero ();
float gamma = h.dot(input - mean_.head<3>());
Eigen::MatrixXf D = Eigen::MatrixXf::Zero (a.size() + 1, a.size() + 1);
D.block(0,0,n,n) = a * a.transpose();
D /= float(n)/float((n+1) * (n+1));
for(std::size_t i=0; i < a.size(); i++) {
D(i,i)+= float(n)/float(n+1)*eigenvalues_(i);
D(D.rows()-1,i) = float(n) / float((n+1) * (n+1)) * gamma * a(i);
D(i,D.cols()-1) = D(D.rows()-1,i);
D(D.rows()-1,D.cols()-1) = float(n)/float((n+1) * (n+1)) * gamma * gamma;
}
Eigen::MatrixXf R(D.rows(), D.cols());
Eigen::EigenSolver<Eigen::MatrixXf> D_evd (D, false);
Eigen::VectorXf alphap = D_evd.eigenvalues().real();
eigenvalues_.resize(eigenvalues_.size() +1);
for(std::size_t i=0;i<eigenvalues_.size();i++) {
eigenvalues_(i) = alphap(eigenvalues_.size()-i-1);
R.col(i) = D.col(D.cols()-i-1);
}
Eigen::MatrixXf Up = Eigen::MatrixXf::Zero(eigenvectors_.rows(), eigenvectors_.cols()+1);
Up.topLeftCorner(eigenvectors_.rows(),eigenvectors_.cols()) = eigenvectors_;
Up.rightCols<1>() = h;
eigenvectors_ = Up*R;
if (!basis_only_) {
Eigen::Vector3f etha = Up.transpose() * (mean_.head<3>() - meanp);
coefficients_.resize(coefficients_.rows()+1,coefficients_.cols()+1);
for(std::size_t i=0; i < (coefficients_.cols() - 1); i++) {
coefficients_(coefficients_.rows()-1,i) = 0;
coefficients_.col(i) = (R.transpose() * coefficients_.col(i)) + etha;
}
a.resize(a.size()+1);
a(a.size()-1) = 0;
coefficients_.col(coefficients_.cols()-1) = (R.transpose() * a) + etha;
}
mean_.head<3>() = meanp;
switch (flag)
{
case increase:
if (eigenvectors_.rows() >= eigenvectors_.cols())
break;
case preserve:
if (!basis_only_)
coefficients_ = coefficients_.topRows(coefficients_.rows() - 1);
eigenvectors_ = eigenvectors_.leftCols(eigenvectors_.cols() - 1);
eigenvalues_.resize(eigenvalues_.size()-1);
break;
default:
PCL_ERROR("[pcl::PCA] unknown flag\n");
}
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::project (const PointT& input, PointT& projection)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed");
Eigen::Vector3f demean_input = input.getVector3fMap () - mean_.head<3> ();
projection.getVector3fMap () = eigenvectors_.transpose() * demean_input;
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::project (const PointCloud& input, PointCloud& projection)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed");
if (input.is_dense)
{
projection.resize (input.size ());
for (size_t i = 0; i < input.size (); ++i)
project (input[i], projection[i]);
}
else
{
PointT p;
for (size_t i = 0; i < input.size (); ++i)
{
if (!pcl_isfinite (input[i].x) ||
!pcl_isfinite (input[i].y) ||
!pcl_isfinite (input[i].z))
continue;
project (input[i], p);
projection.push_back (p);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::reconstruct (const PointT& projection, PointT& input)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed");
input.getVector3fMap ()= eigenvectors_ * projection.getVector3fMap ();
input.getVector3fMap ()+= mean_.head<3> ();
}
/////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> inline void
pcl::PCA<PointT>::reconstruct (const PointCloud& projection, PointCloud& input)
{
if(!compute_done_)
initCompute ();
if (!compute_done_)
PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed");
if (input.is_dense)
{
input.resize (projection.size ());
for (size_t i = 0; i < projection.size (); ++i)
reconstruct (projection[i], input[i]);
}
else
{
PointT p;
for (size_t i = 0; i < input.size (); ++i)
{
if (!pcl_isfinite (input[i].x) ||
!pcl_isfinite (input[i].y) ||
!pcl_isfinite (input[i].z))
continue;
reconstruct (projection[i], p);
input.push_back (p);
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "oddlib/compressiontype6or7aepsx.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <vector>
#include <cassert>
namespace Oddlib
{
template<Uint32 BitsSize, typename OutType>
void NextBits(unsigned int& bitCounter, unsigned int& srcWorkBits, Uint16 *&pSrc1, Uint16 *&pSrcCopy, const signed int kFixedMask, OutType& maskedSrcBits1)
{
if (bitCounter < 16)
{
const int srcBits = *pSrc1 << bitCounter;
bitCounter += 16;
srcWorkBits |= srcBits;
++pSrc1;
pSrcCopy = pSrc1;
}
bitCounter -= BitsSize;
maskedSrcBits1 = static_cast<OutType>(srcWorkBits & (kFixedMask - 1));
srcWorkBits >>= BitsSize;
}
// Function 0x004ABB90 in AE, function 0x8005B09C in AE PSX demo
template<Uint32 BitsSize>
std::vector<Uint8> CompressionType6or7AePsx<BitsSize>::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
{
std::vector<Uint8> out(finalW*h * 400);
std::vector<Uint8> in(dataSize);
stream.ReadBytes(in.data(), in.size());
Uint16* pInput = (Uint16*)in.data();
Uint8* pOutput = (Uint8*)out.data();
int whDWORD = dataSize;
unsigned int bitCounter = 0; // edx@1
Uint16 *pSrc1 = pInput; // ebp@1
Uint16 *pSrcCopy = pInput; // [sp+Ch] [bp-31Ch]@1
unsigned int srcWorkBits = 0; // esi@1
int count = 0; // eax@2
unsigned int maskedSrcBits1 = 0; // ebx@5
int v14 = 0; // ebx@15
char v16 = 0; // bl@18
char bLastByte = 0; // zf@19
int v19 = 0; // eax@23
int v23 = 0; // eax@25
int v24 = 0; // ebx@27
int v25 = 0; // ebx@28
int i = 0; // ebp@32
unsigned char v28 = 0; // cl@33
int count2 = 0; // [sp+10h] [bp-318h]@11
int v33 = 0; // [sp+10h] [bp-318h]@25
unsigned char tmp1[256] = {}; // [sp+28h] [bp-300h]@15
unsigned char tmp2[256] = {}; // [sp+128h] [bp-200h]@8
unsigned char tmp3[256] = {}; // [sp+228h] [bp-100h]@27
const signed int kFixedMask = 1 << BitsSize;
const unsigned int v36 = ((unsigned int)(kFixedMask) >> 1) - 1;
while (pSrc1 < (Uint16 *)((char *)pInput + ((unsigned int)(BitsSize * whDWORD) >> 3)))// could be the first dword of the frame which is usually the size?
{
count = 0;
do
{
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, maskedSrcBits1);
int maskedSrcBits1Copy = maskedSrcBits1;
if (maskedSrcBits1 > v36)
{
int remainder = maskedSrcBits1 - v36;
maskedSrcBits1Copy = remainder;
if (remainder)
{
int remainderCopy = remainder;
do
{
tmp2[count] = static_cast<char>(count);
++count;
--remainder;
--remainderCopy;
} while (remainderCopy);
maskedSrcBits1Copy = remainder;
}
}
if (count == kFixedMask)
{
break;
}
count2 = maskedSrcBits1Copy + 1;
for (;;)
{
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v14);
*(&tmp1[count] + (tmp2 - tmp1)) = static_cast<char>(v14);
if (count != v14)
{
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v16);
tmp1[count] = static_cast<unsigned char>(v16);
}
++count;
bLastByte = count2-- == 1;
if (bLastByte)
{
break;
}
pSrc1 = pSrcCopy; // dead?
}
pSrc1 = pSrcCopy; // dead?
} while (count != kFixedMask);
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v19);
v19 = v19 << BitsSize; // Extra
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v33);
v33 = v33 + v19; // Extra
v23 = 0;
for (;;)
{
if (v23)
{
--v23;
v24 = tmp3[v23];
}
else
{
v25 = v33--;
if (!v25)
{
break;
}
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v24);
}
for (i = tmp2[v24]; v24 != i; i = tmp2[i])
{
v28 = tmp1[v24];
v24 = i;
tmp3[v23++] = v28;
}
pSrc1 = pSrcCopy; // dead?
*pOutput++ = static_cast<Uint8>(v24);
}
}
return out;
}
// Explicit template instantiation
template class CompressionType6or7AePsx<6>;
template class CompressionType6or7AePsx<8>;
}
<commit_msg>read correct amount of input data<commit_after>#include "oddlib/compressiontype6or7aepsx.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <vector>
#include <cassert>
namespace Oddlib
{
template<Uint32 BitsSize, typename OutType>
void NextBits(unsigned int& bitCounter, unsigned int& srcWorkBits, Uint16 *&pSrc1, Uint16 *&pSrcCopy, const signed int kFixedMask, OutType& maskedSrcBits1)
{
if (bitCounter < 16)
{
const int srcBits = *pSrc1 << bitCounter;
bitCounter += 16;
srcWorkBits |= srcBits;
++pSrc1;
pSrcCopy = pSrc1;
}
bitCounter -= BitsSize;
maskedSrcBits1 = static_cast<OutType>(srcWorkBits & (kFixedMask - 1));
srcWorkBits >>= BitsSize;
}
// Function 0x004ABB90 in AE, function 0x8005B09C in AE PSX demo
template<Uint32 BitsSize>
std::vector<Uint8> CompressionType6or7AePsx<BitsSize>::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
{
unsigned int kInputSize = (BitsSize * dataSize) >> 3;
std::vector<Uint8> out(finalW*h * 4);
std::vector<Uint8> in(kInputSize);
stream.ReadBytes(in.data(), in.size());
Uint16* pInput = (Uint16*)in.data();
Uint8* pOutput = (Uint8*)out.data();
unsigned int bitCounter = 0; // edx@1
Uint16 *pSrc1 = pInput; // ebp@1
Uint16 *pSrcCopy = pInput; // [sp+Ch] [bp-31Ch]@1
unsigned int srcWorkBits = 0; // esi@1
int count = 0; // eax@2
unsigned int maskedSrcBits1 = 0; // ebx@5
int v14 = 0; // ebx@15
char v16 = 0; // bl@18
char bLastByte = 0; // zf@19
int v19 = 0; // eax@23
int v23 = 0; // eax@25
int v24 = 0; // ebx@27
int v25 = 0; // ebx@28
int i = 0; // ebp@32
unsigned char v28 = 0; // cl@33
int count2 = 0; // [sp+10h] [bp-318h]@11
int v33 = 0; // [sp+10h] [bp-318h]@25
unsigned char tmp1[256] = {}; // [sp+28h] [bp-300h]@15
unsigned char tmp2[256] = {}; // [sp+128h] [bp-200h]@8
unsigned char tmp3[256] = {}; // [sp+228h] [bp-100h]@27
const signed int kFixedMask = 1 << BitsSize;
const unsigned int v36 = ((unsigned int)(kFixedMask) >> 1) - 1;
while (pSrc1 < (Uint16 *)( ((char *)pInput) + kInputSize))// could be the first dword of the frame which is usually the size?
{
count = 0;
do
{
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, maskedSrcBits1);
int maskedSrcBits1Copy = maskedSrcBits1;
if (maskedSrcBits1 > v36)
{
int remainder = maskedSrcBits1 - v36;
maskedSrcBits1Copy = remainder;
if (remainder)
{
int remainderCopy = remainder;
do
{
tmp2[count] = static_cast<char>(count);
++count;
--remainder;
--remainderCopy;
} while (remainderCopy);
maskedSrcBits1Copy = remainder;
}
}
if (count == kFixedMask)
{
break;
}
count2 = maskedSrcBits1Copy + 1;
for (;;)
{
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v14);
*(&tmp1[count] + (tmp2 - tmp1)) = static_cast<char>(v14);
if (count != v14)
{
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v16);
tmp1[count] = static_cast<unsigned char>(v16);
}
++count;
bLastByte = count2-- == 1;
if (bLastByte)
{
break;
}
pSrc1 = pSrcCopy; // dead?
}
pSrc1 = pSrcCopy; // dead?
} while (count != kFixedMask);
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v19);
v19 = v19 << BitsSize; // Extra
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v33);
v33 = v33 + v19; // Extra
v23 = 0;
for (;;)
{
if (v23)
{
--v23;
v24 = tmp3[v23];
}
else
{
v25 = v33--;
if (!v25)
{
break;
}
NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v24);
}
for (i = tmp2[v24]; v24 != i; i = tmp2[i])
{
v28 = tmp1[v24];
v24 = i;
tmp3[v23++] = v28;
}
pSrc1 = pSrcCopy; // dead?
*pOutput++ = static_cast<Uint8>(v24);
}
}
return out;
}
// Explicit template instantiation
template class CompressionType6or7AePsx<6>;
template class CompressionType6or7AePsx<8>;
}
<|endoftext|> |
<commit_before>#include "JME_Time.h"
#include "boost/date_time/posix_time/posix_time.hpp"
namespace JMEngine
{
namespace game
{
bool JME_Time::isTimeToday(time_t t)
{
auto ct = boost::posix_time::from_time_t(t);
auto nt = boost::posix_time::second_clock::local_time();
return ct.date() == nt.date();
}
int JME_Time::todayYearday()
{
auto nt = boost::posix_time::second_clock::local_time();
return nt.date().day_of_year();
}
tm JME_Time::localTime()
{
return boost::posix_time::to_tm(boost::posix_time::second_clock::local_time());
}
tm JME_Time::localTime(time_t t)
{
tm * timeinfo = localtime(&t);
return *timeinfo;
}
}
}<commit_msg>JID:NO 判断时间戳 是否 当天错误<commit_after>#include "JME_Time.h"
#include "boost/date_time/posix_time/posix_time.hpp"
namespace JMEngine
{
namespace game
{
bool JME_Time::isTimeToday(time_t t)
{
tm timeinfo = *localtime(&t);
auto ct = boost::posix_time::ptime_from_tm(timeinfo);
auto nt = boost::posix_time::second_clock::local_time();
return ct.date() == nt.date();
}
int JME_Time::todayYearday()
{
auto nt = boost::posix_time::second_clock::local_time();
return nt.date().day_of_year();
}
tm JME_Time::localTime()
{
return boost::posix_time::to_tm(boost::posix_time::second_clock::local_time());
}
tm JME_Time::localTime(time_t t)
{
tm * timeinfo = localtime(&t);
return *timeinfo;
}
}
}<|endoftext|> |
<commit_before>/***
Copyright (C) 2013-2014 Aniket Deole <aniket.deole@gmail.com>
This program 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 program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.
***/
#include <protocol/TBinaryProtocol.h>
#include <transport/THttpClient.h>
#include <transport/TSSLSocket.h>
#include "evernote.hh"
void print_md5_sum(unsigned char* md) {
int i;
for(i=0; i <MD5_DIGEST_LENGTH; i++) {
printf("%02x",md[i]);
}
}
evernote::UserStore::UserStore (std::string eU, int p, std::string pT,
std::string authenticationToken) {
evernoteUrl = eU;
port = p;
parameterThree = pT;
auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
auth_http->open();
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
new apache::thrift::protocol::TBinaryProtocol(auth_http));
userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
/**
* We have the userStore working.
*/
delete userStore;
auth_http->close ();
}
evernote::UserStore::~UserStore () {
auth_http->close ();
}
std::string evernote::UserStore::getNoteStoreUrl (std::string authToken) {
auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
auth_http->open();
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
new apache::thrift::protocol::TBinaryProtocol(auth_http));
userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
std::string noteStoreUrl;
userStore->getNoteStoreUrl (noteStoreUrl, authToken);
auth_http->close ();
delete userStore;
return noteStoreUrl;
}
evernote::NoteStore::NoteStore (std::string noteStoreUrl) {
boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory> sslSocketFactory =
boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory>(
new apache::thrift::transport::TSSLSocketFactory());;
boost::shared_ptr<apache::thrift::transport::TSocket> sslSocket = sslSocketFactory->
createSocket("sandbox.evernote.com", 443);
boost::shared_ptr<apache::thrift::transport::TBufferedTransport> bufferedTransport(
new apache::thrift::transport::TBufferedTransport(sslSocket));
userStoreHttpClient = boost::shared_ptr<apache::thrift::transport::THttpClient>(
new apache::thrift::transport::THttpClient(bufferedTransport, "sandbox.evernote.com", noteStoreUrl));
userStoreHttpClient->open();
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> noteStoreProt(
new apache::thrift::protocol::TBinaryProtocol(userStoreHttpClient) );
noteStore = new evernote::edam::NoteStoreClient (noteStoreProt, noteStoreProt);
}
evernote::NoteStore::~NoteStore () {
userStoreHttpClient->close ();
}<commit_msg>Added Exception Handling.<commit_after>/***
Copyright (C) 2013-2014 Aniket Deole <aniket.deole@gmail.com>
This program 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 program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.
***/
#include <protocol/TBinaryProtocol.h>
#include <transport/THttpClient.h>
#include <transport/TSSLSocket.h>
#include "evernote.hh"
void print_md5_sum(unsigned char* md) {
int i;
for(i=0; i <MD5_DIGEST_LENGTH; i++) {
printf("%02x",md[i]);
}
}
evernote::UserStore::UserStore (std::string eU, int p, std::string pT,
std::string authenticationToken) {
evernoteUrl = eU;
port = p;
parameterThree = pT;
auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
auth_http->open();
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
new apache::thrift::protocol::TBinaryProtocol(auth_http));
userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
/**
* We have the userStore working.
*/
}
evernote::UserStore::~UserStore () {
auth_http->close ();
}
std::string evernote::UserStore::getNoteStoreUrl (std::string authToken) {
try {
std::string noteStoreUrl;
userStore->getNoteStoreUrl (noteStoreUrl, authToken);
return noteStoreUrl;
} catch (apache::thrift::transport::TTransportException e) {
auth_http->close ();
delete userStore;
auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
auth_http->open();
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
new apache::thrift::protocol::TBinaryProtocol(auth_http));
userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
std::string noteStoreUrl;
userStore->getNoteStoreUrl (noteStoreUrl, authToken);
auth_http->close ();
delete userStore;
return noteStoreUrl;
}
}
evernote::NoteStore::NoteStore (std::string noteStoreUrl) {
boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory> sslSocketFactory =
boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory>(
new apache::thrift::transport::TSSLSocketFactory());;
boost::shared_ptr<apache::thrift::transport::TSocket> sslSocket = sslSocketFactory->
createSocket("sandbox.evernote.com", 443);
boost::shared_ptr<apache::thrift::transport::TBufferedTransport> bufferedTransport(
new apache::thrift::transport::TBufferedTransport(sslSocket));
userStoreHttpClient = boost::shared_ptr<apache::thrift::transport::THttpClient>(
new apache::thrift::transport::THttpClient(bufferedTransport, "sandbox.evernote.com", noteStoreUrl));
userStoreHttpClient->open();
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> noteStoreProt(
new apache::thrift::protocol::TBinaryProtocol(userStoreHttpClient) );
noteStore = new evernote::edam::NoteStoreClient (noteStoreProt, noteStoreProt);
}
evernote::NoteStore::~NoteStore () {
userStoreHttpClient->close ();
}<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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.
//
// See the corresponding header file for description of the functions in this
// file.
#include "install_util.h"
#include <algorithm>
#include <shellapi.h>
#include <shlobj.h>
#include "base/logging.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"
bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
const std::wstring& params,
DWORD* exit_code) {
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = L"runas";
info.lpFile = exe.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
if (::ShellExecuteEx(&info) == FALSE)
return false;
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (!::GetExitCodeProcess(info.hProcess, &ret_val))
return false;
if (exit_code)
*exit_code = ret_val;
return true;
}
std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
RegKey key(root, dist->GetUninstallRegPath().c_str());
std::wstring uninstall_cmd;
key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
return uninstall_cmd;
}
installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
RegKey key;
std::wstring version_str;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
!key.ReadValue(google_update::kRegVersionField, &version_str)) {
LOG(INFO) << "No existing Chrome install found.";
key.Close();
return NULL;
}
key.Close();
LOG(INFO) << "Existing Chrome version found " << version_str;
return installer::Version::GetVersionFromString(version_str);
}
bool InstallUtil::IsOSSupported() {
int major, minor;
win_util::WinVersion version = win_util::GetWinVersion();
win_util::GetServicePackLevel(&major, &minor);
// We do not support Win2K or older, or XP without service pack 1.
LOG(INFO) << "Windows Version: " << version
<< ", Service Pack: " << major << "." << minor;
if ((version == win_util::WINVERSION_VISTA) ||
(version == win_util::WINVERSION_SERVER_2003) ||
(version == win_util::WINVERSION_XP && major >= 1)) {
return true;
}
return false;
}
void InstallUtil::WriteInstallerResult(bool system_install,
installer_util::InstallStatus status,
int string_resource_id,
const std::wstring* const launch_cmd) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
std::wstring key = dist->GetVersionKey();
int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
installer_result, true);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
status, true);
if (string_resource_id != 0) {
std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
msg, true);
}
if (launch_cmd != NULL) {
install_list->AddSetRegValueWorkItem(root, key,
L"InstallerSuccessLaunchCmdLine",
*launch_cmd, true);
}
if (!install_list->Do())
LOG(ERROR) << "Failed to record installer error information in registry.";
}
bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
std::wstring exe_path_copy = exe_path;
wchar_t program_files_path[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
SHGFP_TYPE_CURRENT, program_files_path))) {
std::wstring program_files_path_copy = program_files_path;
if (std::equal(program_files_path_copy.begin(),
program_files_path_copy.end(), exe_path_copy.begin(),
CaseInsensitiveCompare<wchar_t>())) {
return false;
}
} else {
NOTREACHED();
}
return true;
}<commit_msg>Fixes a crash if you put chrome in a very short directory - like c:\bang. - it will crash at startup on a bad iterator use.<commit_after>// Copyright (c) 2006-2008 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.
//
// See the corresponding header file for description of the functions in this
// file.
#include "install_util.h"
#include <algorithm>
#include <shellapi.h>
#include <shlobj.h>
#include "base/logging.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"
bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
const std::wstring& params,
DWORD* exit_code) {
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = L"runas";
info.lpFile = exe.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
if (::ShellExecuteEx(&info) == FALSE)
return false;
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (!::GetExitCodeProcess(info.hProcess, &ret_val))
return false;
if (exit_code)
*exit_code = ret_val;
return true;
}
std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
RegKey key(root, dist->GetUninstallRegPath().c_str());
std::wstring uninstall_cmd;
key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
return uninstall_cmd;
}
installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
RegKey key;
std::wstring version_str;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
!key.ReadValue(google_update::kRegVersionField, &version_str)) {
LOG(INFO) << "No existing Chrome install found.";
key.Close();
return NULL;
}
key.Close();
LOG(INFO) << "Existing Chrome version found " << version_str;
return installer::Version::GetVersionFromString(version_str);
}
bool InstallUtil::IsOSSupported() {
int major, minor;
win_util::WinVersion version = win_util::GetWinVersion();
win_util::GetServicePackLevel(&major, &minor);
// We do not support Win2K or older, or XP without service pack 1.
LOG(INFO) << "Windows Version: " << version
<< ", Service Pack: " << major << "." << minor;
if ((version == win_util::WINVERSION_VISTA) ||
(version == win_util::WINVERSION_SERVER_2003) ||
(version == win_util::WINVERSION_XP && major >= 1)) {
return true;
}
return false;
}
void InstallUtil::WriteInstallerResult(bool system_install,
installer_util::InstallStatus status,
int string_resource_id,
const std::wstring* const launch_cmd) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
std::wstring key = dist->GetVersionKey();
int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
installer_result, true);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
status, true);
if (string_resource_id != 0) {
std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
msg, true);
}
if (launch_cmd != NULL) {
install_list->AddSetRegValueWorkItem(root, key,
L"InstallerSuccessLaunchCmdLine",
*launch_cmd, true);
}
if (!install_list->Do())
LOG(ERROR) << "Failed to record installer error information in registry.";
}
bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
wchar_t program_files_path[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
SHGFP_TYPE_CURRENT, program_files_path))) {
return !StartsWith(exe_path, program_files_path, false);
} else {
NOTREACHED();
}
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: anytostring.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:48: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
*
************************************************************************/
#include "comphelper/anytostring.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "typelib/typedescription.h"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
namespace comphelper
{
//------------------------------------------------------------------------------
static void appendTypeError(
OUStringBuffer & buf, typelib_TypeDescriptionReference * typeRef )
{
buf.appendAscii(
RTL_CONSTASCII_STRINGPARAM("<cannot get type description of type ") );
buf.append( OUString::unacquired( &typeRef->pTypeName ) );
buf.append( static_cast< sal_Unicode >('>') );
}
//------------------------------------------------------------------------------
static inline void appendChar( OUStringBuffer & buf, sal_Unicode c )
{
if (c < ' ' || c > '~')
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\X") );
OUString s( OUString::valueOf( static_cast< sal_Int32 >(c), 16 ) );
for ( sal_Int32 f = 4 - s.getLength(); f > 0; --f )
buf.append( static_cast< sal_Unicode >('0') );
buf.append( s );
}
else
{
buf.append( c );
}
}
//------------------------------------------------------------------------------
static void appendValue(
OUStringBuffer & buf,
void const * val, typelib_TypeDescriptionReference * typeRef,
bool prependType )
{
if (typeRef->eTypeClass == typelib_TypeClass_VOID)
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("void") );
return;
}
OSL_ASSERT( val != 0 );
if (prependType &&
typeRef->eTypeClass != typelib_TypeClass_STRING &&
typeRef->eTypeClass != typelib_TypeClass_CHAR &&
typeRef->eTypeClass != typelib_TypeClass_BOOLEAN)
{
buf.append( static_cast< sal_Unicode >('(') );
buf.append( OUString::unacquired( &typeRef->pTypeName ) );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(") ") );
}
switch (typeRef->eTypeClass)
{
case typelib_TypeClass_INTERFACE:
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("0x") );
buf.append( reinterpret_cast< sal_Int64 >(
*reinterpret_cast< void * const * >(val) ), 16 );
Reference< lang::XServiceInfo > xServiceInfo(
*reinterpret_cast< XInterface * const * >(val), UNO_QUERY );
if (xServiceInfo.is())
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
" (ImplementationName = \"") );
buf.append( xServiceInfo->getImplementationName() );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\")") );
}
break;
}
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
typelib_TypeDescription * typeDescr = 0;
typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
appendTypeError( buf, typeRef );
}
else
{
typelib_CompoundTypeDescription * compType =
reinterpret_cast< typelib_CompoundTypeDescription * >(
typeDescr );
sal_Int32 nDescr = compType->nMembers;
if (compType->pBaseTypeDescription)
{
appendValue(
buf, val, reinterpret_cast<
typelib_TypeDescription * >(
compType->pBaseTypeDescription)->pWeakRef, false );
if (nDescr > 0)
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
typelib_TypeDescriptionReference ** ppTypeRefs =
compType->ppTypeRefs;
sal_Int32 * memberOffsets = compType->pMemberOffsets;
rtl_uString ** ppMemberNames = compType->ppMemberNames;
for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )
{
buf.append( ppMemberNames[ nPos ] );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" = ") );
typelib_TypeDescription * memberType = 0;
TYPELIB_DANGER_GET( &memberType, ppTypeRefs[ nPos ] );
if (memberType == 0)
{
appendTypeError( buf, ppTypeRefs[ nPos ] );
}
else
{
appendValue( buf,
reinterpret_cast< char const * >(
val ) + memberOffsets[ nPos ],
memberType->pWeakRef, true );
TYPELIB_DANGER_RELEASE( memberType );
}
if (nPos < (nDescr - 1))
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
}
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
if (typeDescr != 0)
typelib_typedescription_release( typeDescr );
break;
}
case typelib_TypeClass_SEQUENCE:
{
typelib_TypeDescription * typeDescr = 0;
TYPELIB_DANGER_GET( &typeDescr, typeRef );
if (typeDescr == 0)
{
appendTypeError( buf,typeRef );
}
else
{
typelib_TypeDescriptionReference * elementTypeRef =
reinterpret_cast<
typelib_IndirectTypeDescription * >(typeDescr)->pType;
typelib_TypeDescription * elementTypeDescr = 0;
TYPELIB_DANGER_GET( &elementTypeDescr, elementTypeRef );
if (elementTypeDescr == 0)
{
appendTypeError( buf, elementTypeRef );
}
else
{
sal_Int32 nElementSize = elementTypeDescr->nSize;
uno_Sequence * seq =
*reinterpret_cast< uno_Sequence * const * >(val);
sal_Int32 nElements = seq->nElements;
if (nElements > 0)
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
char const * pElements = seq->elements;
for ( sal_Int32 nPos = 0; nPos < nElements; ++nPos )
{
appendValue(
buf, pElements + (nElementSize * nPos),
elementTypeDescr->pWeakRef, false );
if (nPos < (nElements - 1))
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
}
else
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{}") );
}
TYPELIB_DANGER_RELEASE( elementTypeDescr );
}
TYPELIB_DANGER_RELEASE( typeDescr );
}
break;
}
case typelib_TypeClass_ANY:
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
uno_Any const * pAny = reinterpret_cast< uno_Any const * >(val);
appendValue( buf, pAny->pData, pAny->pType, true );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
break;
}
case typelib_TypeClass_TYPE:
buf.append( (*reinterpret_cast<
typelib_TypeDescriptionReference * const * >(val)
)->pTypeName );
break;
case typelib_TypeClass_STRING:
{
buf.append( static_cast< sal_Unicode >('\"') );
OUString const & str = OUString::unacquired(
reinterpret_cast< rtl_uString * const * >(val) );
sal_Int32 len = str.getLength();
for ( sal_Int32 pos = 0; pos < len; ++pos )
{
sal_Unicode c = str[ pos ];
if (c == '\"')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\"") );
else if (c == '\\')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
else
appendChar( buf, c );
}
buf.append( static_cast< sal_Unicode >('\"') );
break;
}
case typelib_TypeClass_ENUM:
{
typelib_TypeDescription * typeDescr = 0;
typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
appendTypeError( buf, typeRef );
}
else
{
sal_Int32 * pValues =
reinterpret_cast< typelib_EnumTypeDescription * >(
typeDescr )->pEnumValues;
sal_Int32 nPos = reinterpret_cast< typelib_EnumTypeDescription * >(
typeDescr )->nEnumValues;
while (nPos--)
{
if (pValues[ nPos ] == *reinterpret_cast< int const * >(val))
break;
}
if (nPos >= 0)
{
buf.append( reinterpret_cast< typelib_EnumTypeDescription * >(
typeDescr )->ppEnumNames[ nPos ] );
}
else
{
buf.appendAscii(
RTL_CONSTASCII_STRINGPARAM("?unknown enum value?") );
}
}
if (typeDescr != 0)
typelib_typedescription_release( typeDescr );
break;
}
case typelib_TypeClass_BOOLEAN:
if (*reinterpret_cast< sal_Bool const * >(val) != sal_False)
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("true") );
else
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("false") );
break;
case typelib_TypeClass_CHAR:
{
buf.append( static_cast< sal_Unicode >('\'') );
sal_Unicode c = *reinterpret_cast< sal_Unicode const * >(val);
if (c == '\'')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\'") );
else if (c == '\\')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
else
appendChar( buf, c );
buf.append( static_cast< sal_Unicode >('\'') );
break;
}
case typelib_TypeClass_FLOAT:
buf.append( *reinterpret_cast< float const * >(val) );
break;
case typelib_TypeClass_DOUBLE:
buf.append( *reinterpret_cast< double const * >(val) );
break;
case typelib_TypeClass_BYTE:
buf.append( static_cast< sal_Int32 >(
*reinterpret_cast< sal_Int8 const * >(val) ) );
break;
case typelib_TypeClass_SHORT:
buf.append( static_cast< sal_Int32 >(
*reinterpret_cast< sal_Int16 const * >(val) ) );
break;
case typelib_TypeClass_UNSIGNED_SHORT:
buf.append( static_cast< sal_Int32 >(
*reinterpret_cast< sal_uInt16 const * >(val) ) );
break;
case typelib_TypeClass_LONG:
buf.append( *reinterpret_cast< sal_Int32 const * >(val) );
break;
case typelib_TypeClass_UNSIGNED_LONG:
buf.append( static_cast< sal_Int64 >(
*reinterpret_cast< sal_uInt32 const * >(val) ) );
break;
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
buf.append( *reinterpret_cast< sal_Int64 const * >(val) );
break;
// case typelib_TypeClass_UNION:
// case typelib_TypeClass_ARRAY:
// case typelib_TypeClass_UNKNOWN:
// case typelib_TypeClass_SERVICE:
// case typelib_TypeClass_MODULE:
default:
buf.append( static_cast< sal_Unicode >('?') );
break;
}
}
//==============================================================================
OUString anyToString( Any const & value )
{
OUStringBuffer buf;
appendValue( buf, value.getValue(), value.getValueTypeRef(), true );
return buf.makeStringAndClear();
}
}
<commit_msg>INTEGRATION: CWS dbo510 (1.5.24); FILE MERGED 2005/10/31 10:27:04 dbo 1.5.24.1: cleanup, printing @ADDR instead of 0xADDR<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: anytostring.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2006-03-06 10:13:45 $
*
* 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
*
************************************************************************/
#include "comphelper/anytostring.hxx"
#include "osl/diagnose.h"
#include "rtl/ustrbuf.hxx"
#include "typelib/typedescription.h"
#include "com/sun/star/lang/XServiceInfo.hpp"
using namespace ::com::sun::star;
namespace comphelper {
namespace {
void appendTypeError(
rtl::OUStringBuffer & buf, typelib_TypeDescriptionReference * typeRef )
{
buf.appendAscii(
RTL_CONSTASCII_STRINGPARAM("<cannot get type description of type ") );
buf.append( rtl::OUString::unacquired( &typeRef->pTypeName ) );
buf.append( static_cast< sal_Unicode >('>') );
}
inline void appendChar( rtl::OUStringBuffer & buf, sal_Unicode c )
{
if (c < ' ' || c > '~') {
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\X") );
rtl::OUString const s(
rtl::OUString::valueOf( static_cast< sal_Int32 >(c), 16 ) );
for ( sal_Int32 f = 4 - s.getLength(); f > 0; --f )
buf.append( static_cast< sal_Unicode >('0') );
buf.append( s );
}
else {
buf.append( c );
}
}
//------------------------------------------------------------------------------
void appendValue( rtl::OUStringBuffer & buf,
void const * val, typelib_TypeDescriptionReference * typeRef,
bool prependType )
{
if (typeRef->eTypeClass == typelib_TypeClass_VOID) {
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("void") );
return;
}
OSL_ASSERT( val != 0 );
if (prependType &&
typeRef->eTypeClass != typelib_TypeClass_STRING &&
typeRef->eTypeClass != typelib_TypeClass_CHAR &&
typeRef->eTypeClass != typelib_TypeClass_BOOLEAN)
{
buf.append( static_cast< sal_Unicode >('(') );
buf.append( rtl::OUString::unacquired( &typeRef->pTypeName ) );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(") ") );
}
switch (typeRef->eTypeClass) {
case typelib_TypeClass_INTERFACE: {
buf.append( static_cast<sal_Unicode>('@') );
buf.append( reinterpret_cast< sal_Int64 >(
*static_cast< void * const * >(val) ), 16 );
uno::Reference< lang::XServiceInfo > xServiceInfo(
*static_cast< uno::XInterface * const * >(val),
uno::UNO_QUERY );
if (xServiceInfo.is()) {
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
" (ImplementationName = \"") );
buf.append( xServiceInfo->getImplementationName() );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\")") );
}
break;
}
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION: {
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
typelib_TypeDescription * typeDescr = 0;
typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
appendTypeError( buf, typeRef );
}
else {
typelib_CompoundTypeDescription * compType =
reinterpret_cast< typelib_CompoundTypeDescription * >(
typeDescr );
sal_Int32 nDescr = compType->nMembers;
if (compType->pBaseTypeDescription) {
appendValue(
buf, val, reinterpret_cast<
typelib_TypeDescription * >(
compType->pBaseTypeDescription)->pWeakRef, false );
if (nDescr > 0)
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
typelib_TypeDescriptionReference ** ppTypeRefs =
compType->ppTypeRefs;
sal_Int32 * memberOffsets = compType->pMemberOffsets;
rtl_uString ** ppMemberNames = compType->ppMemberNames;
for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )
{
buf.append( ppMemberNames[ nPos ] );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" = ") );
typelib_TypeDescription * memberType = 0;
TYPELIB_DANGER_GET( &memberType, ppTypeRefs[ nPos ] );
if (memberType == 0) {
appendTypeError( buf, ppTypeRefs[ nPos ] );
}
else {
appendValue( buf,
static_cast< char const * >(
val ) + memberOffsets[ nPos ],
memberType->pWeakRef, true );
TYPELIB_DANGER_RELEASE( memberType );
}
if (nPos < (nDescr - 1))
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
}
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
if (typeDescr != 0)
typelib_typedescription_release( typeDescr );
break;
}
case typelib_TypeClass_SEQUENCE: {
typelib_TypeDescription * typeDescr = 0;
TYPELIB_DANGER_GET( &typeDescr, typeRef );
if (typeDescr == 0) {
appendTypeError( buf,typeRef );
}
else {
typelib_TypeDescriptionReference * elementTypeRef =
reinterpret_cast<
typelib_IndirectTypeDescription * >(typeDescr)->pType;
typelib_TypeDescription * elementTypeDescr = 0;
TYPELIB_DANGER_GET( &elementTypeDescr, elementTypeRef );
if (elementTypeDescr == 0)
{
appendTypeError( buf, elementTypeRef );
}
else
{
sal_Int32 nElementSize = elementTypeDescr->nSize;
uno_Sequence * seq =
*static_cast< uno_Sequence * const * >(val);
sal_Int32 nElements = seq->nElements;
if (nElements > 0)
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
char const * pElements = seq->elements;
for ( sal_Int32 nPos = 0; nPos < nElements; ++nPos )
{
appendValue(
buf, pElements + (nElementSize * nPos),
elementTypeDescr->pWeakRef, false );
if (nPos < (nElements - 1))
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
}
else
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{}") );
}
TYPELIB_DANGER_RELEASE( elementTypeDescr );
}
TYPELIB_DANGER_RELEASE( typeDescr );
}
break;
}
case typelib_TypeClass_ANY: {
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
uno_Any const * pAny = static_cast< uno_Any const * >(val);
appendValue( buf, pAny->pData, pAny->pType, true );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
break;
}
case typelib_TypeClass_TYPE:
buf.append( (*reinterpret_cast<
typelib_TypeDescriptionReference * const * >(val)
)->pTypeName );
break;
case typelib_TypeClass_STRING: {
buf.append( static_cast< sal_Unicode >('\"') );
rtl::OUString const & str = rtl::OUString::unacquired(
static_cast< rtl_uString * const * >(val) );
sal_Int32 len = str.getLength();
for ( sal_Int32 pos = 0; pos < len; ++pos )
{
sal_Unicode c = str[ pos ];
if (c == '\"')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\"") );
else if (c == '\\')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
else
appendChar( buf, c );
}
buf.append( static_cast< sal_Unicode >('\"') );
break;
}
case typelib_TypeClass_ENUM: {
typelib_TypeDescription * typeDescr = 0;
typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
appendTypeError( buf, typeRef );
}
else
{
sal_Int32 * pValues =
reinterpret_cast< typelib_EnumTypeDescription * >(
typeDescr )->pEnumValues;
sal_Int32 nPos = reinterpret_cast< typelib_EnumTypeDescription * >(
typeDescr )->nEnumValues;
while (nPos--)
{
if (pValues[ nPos ] == *static_cast< int const * >(val))
break;
}
if (nPos >= 0)
{
buf.append( reinterpret_cast< typelib_EnumTypeDescription * >(
typeDescr )->ppEnumNames[ nPos ] );
}
else
{
buf.appendAscii(
RTL_CONSTASCII_STRINGPARAM("?unknown enum value?") );
}
}
if (typeDescr != 0)
typelib_typedescription_release( typeDescr );
break;
}
case typelib_TypeClass_BOOLEAN:
if (*static_cast< sal_Bool const * >(val) != sal_False)
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("true") );
else
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("false") );
break;
case typelib_TypeClass_CHAR: {
buf.append( static_cast< sal_Unicode >('\'') );
sal_Unicode c = *static_cast< sal_Unicode const * >(val);
if (c == '\'')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\'") );
else if (c == '\\')
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
else
appendChar( buf, c );
buf.append( static_cast< sal_Unicode >('\'') );
break;
}
case typelib_TypeClass_FLOAT:
buf.append( *static_cast< float const * >(val) );
break;
case typelib_TypeClass_DOUBLE:
buf.append( *static_cast< double const * >(val) );
break;
case typelib_TypeClass_BYTE:
buf.append( static_cast< sal_Int32 >(
*static_cast< sal_Int8 const * >(val) ) );
break;
case typelib_TypeClass_SHORT:
buf.append( static_cast< sal_Int32 >(
*static_cast< sal_Int16 const * >(val) ) );
break;
case typelib_TypeClass_UNSIGNED_SHORT:
buf.append( static_cast< sal_Int32 >(
*static_cast< sal_uInt16 const * >(val) ) );
break;
case typelib_TypeClass_LONG:
buf.append( *static_cast< sal_Int32 const * >(val) );
break;
case typelib_TypeClass_UNSIGNED_LONG:
buf.append( static_cast< sal_Int64 >(
*static_cast< sal_uInt32 const * >(val) ) );
break;
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
buf.append( *static_cast< sal_Int64 const * >(val) );
break;
// case typelib_TypeClass_UNION:
// case typelib_TypeClass_ARRAY:
// case typelib_TypeClass_UNKNOWN:
// case typelib_TypeClass_SERVICE:
// case typelib_TypeClass_MODULE:
default:
buf.append( static_cast< sal_Unicode >('?') );
break;
}
}
} // anon namespace
//==============================================================================
rtl::OUString anyToString( uno::Any const & value )
{
rtl::OUStringBuffer buf;
appendValue( buf, value.getValue(), value.getValueTypeRef(), true );
return buf.makeStringAndClear();
}
} // namespace comphelper
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <vespa/fastos/fastos.h>
#include <vespa/filedistribution/distributor/filedownloader.h>
#include <vespa/filedistribution/distributor/filedistributortrackerimpl.h>
#include <fstream>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/tracker_manager.hpp>
#include <libtorrent/torrent.hpp>
#include <vespa/filedistribution/manager/createtorrent.h>
#include <vespa/filedistribution/model/filedistributionmodel.h>
#include <vespa/filedistribution/common/componentsdeleter.h>
namespace fs = boost::filesystem;
using namespace filedistribution;
namespace {
const std::string localHost("localhost");
const int uploaderPort = 9113;
const int downloaderPort = 9112;
#if 0
std::shared_ptr<FileDownloader>
createDownloader(ComponentsDeleter& deleter,
int port, const fs::path& downloaderPath,
const std::shared_ptr<FileDistributionModel>& model)
{
std::shared_ptr<FileDistributorTrackerImpl> tracker(deleter.track(new FileDistributorTrackerImpl(model)));
std::shared_ptr<FileDownloader> downloader(deleter.track(new FileDownloader(tracker,
localHost, port, downloaderPath)));
tracker->setDownloader(downloader);
return downloader;
}
#endif
} //anonymous namespace
class MockFileDistributionModel : public FileDistributionModel {
virtual FileDBModel& getFileDBModel() {
abort();
}
virtual std::set<std::string> getFilesToDownload() {
return std::set<std::string>();
}
virtual PeerEntries getPeers(const std::string& , size_t) {
PeerEntries peers(2);
peers[0].ip = localHost;
peers[0].port = uploaderPort;
peers[1].ip = localHost;
peers[1].port = downloaderPort;
return peers;
}
virtual void addPeer(const std::string&) {}
virtual void removePeer(const std::string&) {}
virtual void peerFinished(const std::string&) {}
};
#if 0
BOOST_AUTO_TEST_CASE(fileDownloaderTest) {
fs::path testPath = "/tmp/filedownloadertest";
fs::remove_all(testPath);
fs::path downloaderPath = testPath / "downloader";
fs::path uploaderPath = testPath / "uploader";
const std::string fileReference = "0123456789012345678901234567890123456789";
const std::string fileToSend = "filetosend.txt";
fs::create_directories(downloaderPath);
fs::create_directories(uploaderPath / fileReference);
fs::path fileToUploadPath = uploaderPath / fileReference / "filetosend.txt";
{
fs::ofstream stream(fileToUploadPath);
stream <<"Hello, world!" <<std::endl;
}
CreateTorrent createTorrent(fileToUploadPath);
Buffer buffer(createTorrent.bencode());
ComponentsDeleter deleter;
std::shared_ptr<FileDistributionModel> model(deleter.track(new MockFileDistributionModel()));
std::shared_ptr<FileDownloader> downloader =
createDownloader(deleter, downloaderPort, downloaderPath, model);
std::shared_ptr<FileDownloader> uploader =
createDownloader(deleter, uploaderPort, uploaderPath, model);
std::thread uploaderThread( [&] () { uploader->runEventLoop(); });
std::thread downloaderThread( [&] () { downloader->runEventLoop(); });
uploader->addTorrent(fileReference, buffer);
downloader->addTorrent(fileReference, buffer);
sleep(5);
BOOST_CHECK(fs::exists(downloaderPath / fileReference / fileToSend));
uploaderThread.interrupt();
uploaderThread.join();
downloaderThread.interrupt();
downloaderThread.join();
fs::remove_all(testPath);
}
#endif
//TODO: cleanup
libtorrent::sha1_hash
toInfoHash(const std::string& fileReference) {
assert (fileReference.size() == 40);
std::istringstream s(fileReference);
libtorrent::sha1_hash infoHash;
s >> infoHash;
return infoHash;
}
BOOST_AUTO_TEST_CASE(test_filereference_infohash_conversion) {
const std::string fileReference = "3a281c905c9b6ebe4d969037a198454fedefbdf3";
libtorrent::sha1_hash infoHash = toInfoHash(fileReference);
std::ostringstream fileReferenceString;
fileReferenceString <<infoHash;
BOOST_CHECK(fileReference == fileReferenceString.str());
std::cout <<fileReference <<std::endl <<fileReferenceString.str() <<std::endl;
}
<commit_msg>capture by value<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <vespa/fastos/fastos.h>
#include <vespa/filedistribution/distributor/filedownloader.h>
#include <vespa/filedistribution/distributor/filedistributortrackerimpl.h>
#include <fstream>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/tracker_manager.hpp>
#include <libtorrent/torrent.hpp>
#include <vespa/filedistribution/manager/createtorrent.h>
#include <vespa/filedistribution/model/filedistributionmodel.h>
#include <vespa/filedistribution/common/componentsdeleter.h>
namespace fs = boost::filesystem;
using namespace filedistribution;
namespace {
const std::string localHost("localhost");
const int uploaderPort = 9113;
const int downloaderPort = 9112;
#if 0
std::shared_ptr<FileDownloader>
createDownloader(ComponentsDeleter& deleter,
int port, const fs::path& downloaderPath,
const std::shared_ptr<FileDistributionModel>& model)
{
std::shared_ptr<FileDistributorTrackerImpl> tracker(deleter.track(new FileDistributorTrackerImpl(model)));
std::shared_ptr<FileDownloader> downloader(deleter.track(new FileDownloader(tracker,
localHost, port, downloaderPath)));
tracker->setDownloader(downloader);
return downloader;
}
#endif
} //anonymous namespace
class MockFileDistributionModel : public FileDistributionModel {
virtual FileDBModel& getFileDBModel() {
abort();
}
virtual std::set<std::string> getFilesToDownload() {
return std::set<std::string>();
}
virtual PeerEntries getPeers(const std::string& , size_t) {
PeerEntries peers(2);
peers[0].ip = localHost;
peers[0].port = uploaderPort;
peers[1].ip = localHost;
peers[1].port = downloaderPort;
return peers;
}
virtual void addPeer(const std::string&) {}
virtual void removePeer(const std::string&) {}
virtual void peerFinished(const std::string&) {}
};
#if 0
BOOST_AUTO_TEST_CASE(fileDownloaderTest) {
fs::path testPath = "/tmp/filedownloadertest";
fs::remove_all(testPath);
fs::path downloaderPath = testPath / "downloader";
fs::path uploaderPath = testPath / "uploader";
const std::string fileReference = "0123456789012345678901234567890123456789";
const std::string fileToSend = "filetosend.txt";
fs::create_directories(downloaderPath);
fs::create_directories(uploaderPath / fileReference);
fs::path fileToUploadPath = uploaderPath / fileReference / "filetosend.txt";
{
fs::ofstream stream(fileToUploadPath);
stream <<"Hello, world!" <<std::endl;
}
CreateTorrent createTorrent(fileToUploadPath);
Buffer buffer(createTorrent.bencode());
ComponentsDeleter deleter;
std::shared_ptr<FileDistributionModel> model(deleter.track(new MockFileDistributionModel()));
std::shared_ptr<FileDownloader> downloader =
createDownloader(deleter, downloaderPort, downloaderPath, model);
std::shared_ptr<FileDownloader> uploader =
createDownloader(deleter, uploaderPort, uploaderPath, model);
std::thread uploaderThread( [uploader] () { uploader->runEventLoop(); });
std::thread downloaderThread( [downloader] () { downloader->runEventLoop(); });
uploader->addTorrent(fileReference, buffer);
downloader->addTorrent(fileReference, buffer);
sleep(5);
BOOST_CHECK(fs::exists(downloaderPath / fileReference / fileToSend));
uploaderThread.interrupt();
uploaderThread.join();
downloaderThread.interrupt();
downloaderThread.join();
fs::remove_all(testPath);
}
#endif
//TODO: cleanup
libtorrent::sha1_hash
toInfoHash(const std::string& fileReference) {
assert (fileReference.size() == 40);
std::istringstream s(fileReference);
libtorrent::sha1_hash infoHash;
s >> infoHash;
return infoHash;
}
BOOST_AUTO_TEST_CASE(test_filereference_infohash_conversion) {
const std::string fileReference = "3a281c905c9b6ebe4d969037a198454fedefbdf3";
libtorrent::sha1_hash infoHash = toInfoHash(fileReference);
std::ostringstream fileReferenceString;
fileReferenceString <<infoHash;
BOOST_CHECK(fileReference == fileReferenceString.str());
std::cout <<fileReference <<std::endl <<fileReferenceString.str() <<std::endl;
}
<|endoftext|> |
<commit_before>#pragma once
#include <libgen.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "logging/log.hh"
#include "macros.hh"
namespace jcc {
namespace {
inline char* filename(char const* const argument) {
return basename(const_cast<char*>(argument));
}
template <typename T>
inline std::stringstream to_expr(const T& val, char const* const expr) {
std::stringstream ss;
ss << expr << " (" << val << ")";
return ss;
}
template <typename A, typename B>
inline std::stringstream binary_expector_string(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num,
char const* const operator_name) {
std::stringstream ss;
ss << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": " << to_expr(a, a_expr).str()
<< operator_name << " " << to_expr(b, b_expr).str() << ": " << msg;
return ss;
}
} // namespace
template <typename A, typename B>
inline void assert_gt(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a <= b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, ">")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_ge(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a < b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, ">=")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_lt(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a >= b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "<")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_le(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a > b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "<=")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_eq(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a != b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "==")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_ne(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a == b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "!=")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_between(const A& a,
const B& b,
const B& c,
char const* const a_expr,
char const* const b_expr,
char const* const c_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(((a < b) || (a > c)))) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": "
<< to_expr(b, b_expr).str() << " <= " << to_expr(a, a_expr).str()
<< " <= " << to_expr(c, c_expr).str() << ": " << msg;
std::abort();
}
}
template <typename A, typename B>
inline void assert_outside(const A& a,
const B& b,
const B& c,
char const* const a_expr,
char const* const b_expr,
char const* const c_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(((a < b) || (a > c)))) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": "
<< to_expr(b, b_expr).str() << " < " << to_expr(a, a_expr).str() << " < "
<< to_expr(c, c_expr).str() << ": " << msg;
std::abort();
}
}
inline void assert_true(const bool& a,
char const* const a_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(!a)) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": " << a_expr
<< std::boolalpha << a << ": " << msg << std::endl;
std::abort();
}
}
inline void assert_false(const bool& a,
char const* const a_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a)) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": " << a_expr
<< std::boolalpha << a << ": " << msg << std::endl;
std::abort();
}
}
} // namespace jcc
//
// Comparison Assertions
//
#define JASSERT_GE(a, b, msg) jcc::assert_ge(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_GT(a, b, msg) jcc::assert_gt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LE(a, b, msg) jcc::assert_le(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LT(a, b, msg) jcc::assert_lt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_EQ(a, b, msg) jcc::assert_eq(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_NE(a, b, msg) jcc::assert_ne(a, b, #a, #b, msg, __FILE__, __LINE__);
//
// Ternary Assertions
//
#define JASSERT_BETWEEN(a, b, c, msg) \
jcc::assert_between(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);
#define JASSERT_OUTSIDE(a, b, c, msg) \
jcc::assert_outside(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);
//
// Unary Assertions
//
#define JASSERT(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_TRUE(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_FALSE(a, msg) jcc::assert_false(a, #a, msg, __FILE__, __LINE__);
<commit_msg>Fix whitespace in assertions<commit_after>#pragma once
#include <libgen.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "logging/log.hh"
#include "macros.hh"
namespace jcc {
namespace {
inline char* filename(char const* const argument) {
return basename(const_cast<char*>(argument));
}
template <typename T>
inline std::stringstream to_expr(const T& val, char const* const expr) {
std::stringstream ss;
ss << expr << " (" << val << ")";
return ss;
}
template <typename A, typename B>
inline std::stringstream binary_expector_string(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num,
char const* const operator_name) {
std::stringstream ss;
ss << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": " << to_expr(a, a_expr).str()
<< " " << operator_name << " " << to_expr(b, b_expr).str() << ": " << msg;
return ss;
}
} // namespace
template <typename A, typename B>
inline void assert_gt(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a <= b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, ">")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_ge(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a < b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, ">=")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_lt(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a >= b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "<")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_le(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a > b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "<=")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_eq(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a != b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "==")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_ne(const A& a,
const B& b,
char const* const a_expr,
char const* const b_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a == b)) {
std::cerr << binary_expector_string(
a, b, a_expr, b_expr, msg, file_name, line_num, "!=")
.str()
<< std::endl;
std::abort();
}
}
template <typename A, typename B>
inline void assert_between(const A& a,
const B& b,
const B& c,
char const* const a_expr,
char const* const b_expr,
char const* const c_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(((a < b) || (a > c)))) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": "
<< to_expr(b, b_expr).str() << " <= " << to_expr(a, a_expr).str()
<< " <= " << to_expr(c, c_expr).str() << ": " << msg;
std::abort();
}
}
template <typename A, typename B>
inline void assert_outside(const A& a,
const B& b,
const B& c,
char const* const a_expr,
char const* const b_expr,
char const* const c_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(((a < b) || (a > c)))) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": "
<< to_expr(b, b_expr).str() << " < " << to_expr(a, a_expr).str() << " < "
<< to_expr(c, c_expr).str() << ": " << msg;
std::abort();
}
}
inline void assert_true(const bool& a,
char const* const a_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(!a)) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": " << a_expr
<< std::boolalpha << " " << a << ": " << msg << std::endl;
std::abort();
}
}
inline void assert_false(const bool& a,
char const* const a_expr,
char const* const msg,
char const* const file_name,
int line_num) {
if (UNLIKELY(a)) {
std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
<< Format::red() << "Expected" << Format::reset() << ": " << a_expr
<< std::boolalpha << " " << a << ": " << msg << std::endl;
std::abort();
}
}
} // namespace jcc
//
// Comparison Assertions
//
#define JASSERT_GE(a, b, msg) jcc::assert_ge(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_GT(a, b, msg) jcc::assert_gt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LE(a, b, msg) jcc::assert_le(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LT(a, b, msg) jcc::assert_lt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_EQ(a, b, msg) jcc::assert_eq(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_NE(a, b, msg) jcc::assert_ne(a, b, #a, #b, msg, __FILE__, __LINE__);
//
// Ternary Assertions
//
#define JASSERT_BETWEEN(a, b, c, msg) \
jcc::assert_between(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);
#define JASSERT_OUTSIDE(a, b, c, msg) \
jcc::assert_outside(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);
//
// Unary Assertions
//
#define JASSERT(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_TRUE(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_FALSE(a, msg) jcc::assert_false(a, #a, msg, __FILE__, __LINE__);
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include "server.h"
#include "duckchat.h"
// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
struct sockaddr_in *address;
std::list<Channel *> channels;
User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};
std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer, struct sockaddr_in *address) {
struct request current_request;
User *new_user;
std::map<std::string, User *>::iterator it;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
new_user = new User(login_request.req_username, address);
users.insert({std::string(login_request.req_username), new_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : users) {
unsigned short user_port = user.second->address->sin_port;
in_addr_t user_address = user.second->address->sin_addr.s_addr;
unsigned short request_port = address->sin_port;
in_addr_t request_address = address->sin_addr.s_addr;
std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;
if (user_port == request_port && user_address == request_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
users.erase(user.first);
break;
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
// std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
break;
default:
break;
}
//
// for (auto user : users) {
// unsigned short user_port = user.second->address->sin_port;
// in_addr_t user_address = user.second->address->sin_addr.s_addr;
//
// std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
// }
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// user = "";
if (argc < 2) {
std::cerr << "server: no port provided" << std::endl;
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
ProcessRequest(buffer, &client_addr);
}
}
}
<commit_msg>more logout testing<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include "server.h"
#include "duckchat.h"
// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
struct sockaddr_in *address;
std::list<Channel *> channels;
User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};
std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer, struct sockaddr_in *address) {
struct request current_request;
User *new_user;
std::map<std::string, User *>::iterator it;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
new_user = new User(login_request.req_username, address);
users.insert({std::string(login_request.req_username), new_user});
for (auto user : users) {
unsigned short user_port = user.second->address->sin_port;
in_addr_t user_address = user.second->address->sin_addr.s_addr;
std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
std::cout << std::endl;
}
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : users) {
unsigned short user_port = user.second->address->sin_port;
in_addr_t user_address = user.second->address->sin_addr.s_addr;
unsigned short request_port = address->sin_port;
in_addr_t request_address = address->sin_addr.s_addr;
std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;
if (user_port == request_port && user_address == request_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
users.erase(user.first);
break;
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
// std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// user = "";
if (argc < 2) {
std::cerr << "server: no port provided" << std::endl;
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
ProcessRequest(buffer, &client_addr);
}
}
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include "server.h"
#include "duckchat.h"
// TODO Handle domain
// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
in_addr_t address;
unsigned short port;
// std::set<Channel *> channels;
User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};
std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(int server_socket, void *buffer, in_addr_t user_address, unsigned short user_port) {
struct request current_request;
User *current_user;
Channel *channel;
std::string current_channel;
std::list<User *>::const_iterator it;
bool is_new_channel;
bool is_channel;
memcpy(¤t_request, buffer, sizeof(struct request));
// std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
current_user = new User(login_request.req_username, user_address, user_port);
kUsers.insert({std::string(login_request.req_username), current_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
kUsers.erase(user.first);
break;
}
}
break;
case REQ_LEAVE:
struct request_leave leave_request;
memcpy(&leave_request, buffer, sizeof(struct request_leave));
current_channel = leave_request.req_channel;
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
is_channel = false;
for(auto ch : kChannels){
if(ch.first == current_channel){
std::cout << "channel found" << std::endl;
is_channel = true;
break;
}
}
if(is_channel){
channel = kChannels[current_channel];
for (it = channel->users.begin(); it != channel->users.end(); ++it){
if((*it)->name == user.first){
break;
}
}
if( it != channel->users.end()){
channel->users.remove(*it);
std::cout << user.first << " leaves channel " << channel->name << std::endl;
if (channel->users.size() == 0) {
kChannels.erase(channel->name);
std::cout << "server: removing empty channel " << channel->name << std::endl;
}
}
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
} else {
std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl;
}
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
is_new_channel = true;
// If channel does exists in global map, set local channel to channel from kChannels
for (auto ch : kChannels) {
if (join_request.req_channel == ch.second->name) {
is_new_channel = false;
channel = ch.second;
break;
}
}
// If channel is new create a new channel
if (is_new_channel) {
channel = new Channel(join_request.req_channel);
}
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;
channel->users.push_back(user.second);
// Otherwise
if (is_new_channel) {
kChannels.insert({channel->name, channel});
}
// Test print
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
}
}
break;
case REQ_SAY:
struct request_say say_request;
memcpy(&say_request, buffer, sizeof(struct request_say));
std::cout << "user said: " << say_request.req_text << std::endl;
for(auto user : kChannels[say_request.req_channel]->users){
std::cout << "server sending message to: " << user->name << std::endl;
struct sockaddr_in client_addr;
struct text_say say;
memcpy(&say, buffer, sizeof(struct text_say));
memset(&client_addr, 0, sizeof(struct sockaddr_in));
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(user->port);
client_addr.sin_addr.s_addr = htonl(user->address);
strncpy(say.txt_channel, say_request.req_channel, CHANNEL_MAX);
strncpy(say.txt_text, say_request.req_text, SAY_MAX);
say.txt_type = TXT_SAY;
strncpy(say.txt_username, user->name.c_str(), USERNAME_MAX);
size_t message_size = sizeof(struct text_say);
if (sendto(server_socket, &say, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) {
Error("server: failed to send say\n");
}
}
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// std::string domain;
if (argc < 3) {
std::cerr << "Usage: ./server domain_name port_num" << std::endl;
exit(1);
}
// domain = argv[1];
port = atoi(argv[2]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
// std::cout << "port " << client_addr.sin_port << std::endl;
ProcessRequest(server_socket, buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
}
}
}
<commit_msg>print testing<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include "server.h"
#include "duckchat.h"
// TODO Handle domain
// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
in_addr_t address;
unsigned short port;
// std::set<Channel *> channels;
User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};
struct sockaddr_in most_recent_client_addr;
std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(int server_socket, void *buffer, in_addr_t user_address, unsigned short user_port) {
struct request current_request;
User *current_user;
Channel *channel;
std::string current_channel;
std::list<User *>::const_iterator it;
bool is_new_channel;
bool is_channel;
memcpy(¤t_request, buffer, sizeof(struct request));
// std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
current_user = new User(login_request.req_username, user_address, user_port);
kUsers.insert({std::string(login_request.req_username), current_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
kUsers.erase(user.first);
break;
}
}
break;
case REQ_LEAVE:
struct request_leave leave_request;
memcpy(&leave_request, buffer, sizeof(struct request_leave));
current_channel = leave_request.req_channel;
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
is_channel = false;
for(auto ch : kChannels){
if(ch.first == current_channel){
std::cout << "channel found" << std::endl;
is_channel = true;
break;
}
}
if(is_channel){
channel = kChannels[current_channel];
for (it = channel->users.begin(); it != channel->users.end(); ++it){
if((*it)->name == user.first){
break;
}
}
if( it != channel->users.end()){
channel->users.remove(*it);
std::cout << user.first << " leaves channel " << channel->name << std::endl;
if (channel->users.size() == 0) {
kChannels.erase(channel->name);
std::cout << "server: removing empty channel " << channel->name << std::endl;
}
}
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
} else {
std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl;
}
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
is_new_channel = true;
// If channel does exists in global map, set local channel to channel from kChannels
for (auto ch : kChannels) {
if (join_request.req_channel == ch.second->name) {
is_new_channel = false;
channel = ch.second;
break;
}
}
// If channel is new create a new channel
if (is_new_channel) {
channel = new Channel(join_request.req_channel);
}
for (auto user : kUsers) {
unsigned short current_port = user.second->port;
in_addr_t current_address = user.second->address;
if (current_port == user_port && current_address == user_address) {
std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;
channel->users.push_back(user.second);
// Otherwise
if (is_new_channel) {
kChannels.insert({channel->name, channel});
}
// Test print
for (auto u : channel->users) {
std::cout << "user: " << u->name << std::endl;
}
break;
}
}
break;
case REQ_SAY:
struct request_say say_request;
memcpy(&say_request, buffer, sizeof(struct request_say));
std::cout << "user said: " << say_request.req_text << std::endl;
for(auto user : kChannels[say_request.req_channel]->users){
std::cout << "server sending message to: " << user->name << std::endl;
struct sockaddr_in client_addr;
struct text_say say;
memcpy(&say, buffer, sizeof(struct text_say));
memset(&client_addr, 0, sizeof(struct sockaddr_in));
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(user->port);
client_addr.sin_addr.s_addr = htonl(user->address);
strncpy(say.txt_channel, say_request.req_channel, CHANNEL_MAX);
strncpy(say.txt_text, say_request.req_text, SAY_MAX);
say.txt_type = TXT_SAY;
strncpy(say.txt_username, user->name.c_str(), USERNAME_MAX);
size_t message_size = sizeof(struct text_say);
if (sendto(server_socket, &say, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) {
Error("server: failed to send say\n");
}
}
break;
default:
break;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// std::string domain;
if (argc < 3) {
std::cerr << "Usage: ./server domain_name port_num" << std::endl;
exit(1);
}
// domain = argv[1];
port = atoi(argv[2]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
memcpy(&most_recent_client_addr, &client_addr, sizeof(most_recent_client_addr));
std::cout << "port " << most_recent_client_addr.sin_port << std::endl;
if (receive_len > 0) {
buffer[receive_len] = 0;
// std::cout << "port " << client_addr.sin_port << std::endl;
ProcessRequest(server_socket, buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
}
}
}
<|endoftext|> |
<commit_before>#define byte uint8_t
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <cstring>
#include <unistd.h>
#include <wiringPi.h>
#include <iostream>
#include <sys/types.h>
using namespace std;
const byte rfPin = 7;
void SelectPlus(uint32_t address) {
int pulseWidth = 325; // Pulse width in uS
byte repeat = 40; // Repeat send
uint32_t databit;
uint32_t mask = 0x10000;
uint32_t sendbuff;
for (byte j = 0; j <= repeat; j++) {
sendbuff = address;
// send 3 HIGH pulses for syncing
digitalWrite(rfPin, HIGH);
delayMicroseconds(pulseWidth * 3);
// Send command
for (int i = 0; i < 17; i++) { // 13+4 bits
databit = sendbuff & mask; // Get most left bit
sendbuff = (sendbuff << 1);// Shift left
if (databit != mask) { // Write 0
digitalWrite(rfPin, LOW);
delayMicroseconds(pulseWidth);
digitalWrite(rfPin, HIGH);
delayMicroseconds(pulseWidth * 3);
} else { // Write 1
digitalWrite(rfPin, LOW);
delayMicroseconds(pulseWidth * 3);
digitalWrite(rfPin, HIGH);
delayMicroseconds(pulseWidth);
}
}
digitalWrite(rfPin, LOW);
delayMicroseconds(pulseWidth * 16);
}
}
int main(int argc, char* argv[])
{
// Check if WiringPi is properly installed.
if (wiringPiSetup () == -1) {
std::cout << "Please install WiringPi first (http://wiringpi.com/download-and-install/)." << '\n';
return 1;
}
// Check if an argument is present.
if (argc < 2) {
std::cout << "Please enter at least one argument: ./Ring white" << '\n' << "You can also use multiple arguments: ./Ring black white black." << '\n';
return 1;
}
// Loop through arguments.
for (int count=1; count < argc; ++count) {
if (!strcmp(argv[count], "white")) {
SelectPlus(0x1BB40); // White
std::cout << count << " Ding Dong (White) " << '\n';
} else {
SelectPlus(0x1C330); // Black
std::cout << count << " Ding Dong (Black)" << '\n';
}
if (count < argc) {
std::cout << count << " Pause (5s)" << '\n';
usleep(5000000);
}
}
}
/* ___
'0': _| | (T,3T)
_
'1': ___| | (3T,T)
*/
<commit_msg>Update ring.cpp<commit_after>#define byte uint8_t
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <cstring>
#include <unistd.h>
#include <wiringPi.h>
#include <iostream>
#include <sys/types.h>
using namespace std;
const byte rfPin = 7;
void SelectPlus(uint32_t address) {
int pulseWidth = 325; // Pulse width in uS
byte repeat = 40; // Repeat send
uint32_t databit;
uint32_t mask = 0x10000;
uint32_t sendbuff;
for (byte j = 0; j <= repeat; j++) {
sendbuff = address;
// send 3 HIGH pulses for syncing
digitalWrite(rfPin, HIGH);
delayMicroseconds(pulseWidth * 3);
// Send command
for (int i = 0; i < 17; i++) { // 13+4 bits
databit = sendbuff & mask; // Get most left bit
sendbuff = (sendbuff << 1);// Shift left
if (databit != mask) { // Write 0
digitalWrite(rfPin, LOW);
delayMicroseconds(pulseWidth);
digitalWrite(rfPin, HIGH);
delayMicroseconds(pulseWidth * 3);
} else { // Write 1
digitalWrite(rfPin, LOW);
delayMicroseconds(pulseWidth * 3);
digitalWrite(rfPin, HIGH);
delayMicroseconds(pulseWidth);
}
}
digitalWrite(rfPin, LOW);
delayMicroseconds(pulseWidth * 16);
}
}
int main(int argc, char* argv[])
{
// Check if WiringPi is properly installed.
if (wiringPiSetup () == -1) {
std::cout << "Please install WiringPi first (http://wiringpi.com/download-and-install/)." << '\n';
return 1;
}
// Check if an argument is present.
if (argc < 2) {
std::cout << "Please enter at least one argument: ./Ring white" << '\n' << "You can also use multiple arguments: ./Ring black white black." << '\n';
return 1;
}
// Loop through arguments.
for (int count=1; count < argc; ++count) {
if (!strcmp(argv[count], "white")) {
SelectPlus(0x3BB40); // White
std::cout << count << " Ding Dong (White) " << '\n';
} else {
SelectPlus(0x3C330); // Black
std::cout << count << " Ding Dong (Black)" << '\n';
}
if (count < argc) {
std::cout << count << " Pause (5s)" << '\n';
usleep(5000000);
}
}
}
/* ___
'0': _| | (T,3T)
_
'1': ___| | (3T,T)
*/
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "plugin.h"
#include "ilxqtpanelplugin.h"
#include "pluginsettings_p.h"
#include "lxqtpanel.h"
#include <QDebug>
#include <QProcessEnvironment>
#include <QStringList>
#include <QDir>
#include <QFileInfo>
#include <QPluginLoader>
#include <QGridLayout>
#include <QDialog>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QApplication>
#include <memory>
#include <LXQt/Settings>
#include <LXQt/Translator>
#include <XdgIcon>
// statically linked built-in plugins
#include "../plugin-clock/lxqtclock.h" // clock
extern void * loadPluginTranslation_clock_helper;
#include "../plugin-desktopswitch/desktopswitch.h" // desktopswitch
extern void * loadPluginTranslation_desktopswitch_helper;
#include "../plugin-mainmenu/lxqtmainmenu.h" // mainmenu
extern void * loadPluginTranslation_mainmenu_helper;
#include "../plugin-quicklaunch/lxqtquicklaunchplugin.h" // quicklaunch
extern void * loadPluginTranslation_quicklaunch_helper;
#include "../plugin-showdesktop/showdesktop.h" // showdesktop
extern void * loadPluginTranslation_showdesktop_helper;
#include "../plugin-spacer/spacer.h" // spacer
extern void * loadPluginTranslation_spacer_helper;
#include "../plugin-statusnotifier/statusnotifier.h" // statusnotifier
extern void * loadPluginTranslation_statusnotifier_helper;
#include "../plugin-taskbar/lxqttaskbarplugin.h" // taskbar
extern void * loadPluginTranslation_taskbar_helper;
#include "../plugin-tray/lxqttrayplugin.h" // tray
extern void * loadPluginTranslation_tray_helper;
#include "../plugin-worldclock/lxqtworldclock.h" // worldclock
extern void * loadPluginTranslation_worldclock_helper;
QColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);
/************************************************
************************************************/
Plugin::Plugin(const LXQt::PluginInfo &desktopFile, LXQt::Settings *settings, const QString &settingsGroup, LXQtPanel *panel) :
QFrame(panel),
mDesktopFile(desktopFile),
mPluginLoader(0),
mPlugin(0),
mPluginWidget(0),
mAlignment(AlignLeft),
mPanel(panel)
{
mSettings = PluginSettingsFactory::create(settings, settingsGroup);
setWindowTitle(desktopFile.name());
mName = desktopFile.name();
QStringList dirs;
dirs << QProcessEnvironment::systemEnvironment().value("LXQTPANEL_PLUGIN_PATH").split(":");
dirs << PLUGIN_DIR;
bool found = false;
if(ILXQtPanelPluginLibrary const * pluginLib = findStaticPlugin(desktopFile.id()))
{
// this is a static plugin
found = true;
loadLib(pluginLib);
}
else {
// this plugin is a dynamically loadable module
QString baseName = QString("lib%1.so").arg(desktopFile.id());
foreach(const QString &dirName, dirs)
{
QFileInfo fi(QDir(dirName), baseName);
if (fi.exists())
{
found = true;
if (loadModule(fi.absoluteFilePath()))
break;
}
}
}
if (!isLoaded())
{
if (!found)
qWarning() << QString("Plugin %1 not found in the").arg(desktopFile.id()) << dirs;
return;
}
setObjectName(mPlugin->themeId() + "Plugin");
// plugin handle for easy context menu
setProperty("NeedsHandle", mPlugin->flags().testFlag(ILXQtPanelPlugin::NeedsHandle));
QString s = mSettings->value("alignment").toString();
// Retrun default value
if (s.isEmpty())
{
mAlignment = (mPlugin->flags().testFlag(ILXQtPanelPlugin::PreferRightAlignment)) ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
else
{
mAlignment = (s.toUpper() == "RIGHT") ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
if (mPluginWidget)
{
QGridLayout* layout = new QGridLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
layout->addWidget(mPluginWidget, 0, 0);
}
// delay the connection to settingsChanged to avoid conflicts
// while the plugin is still being initialized
connect(mSettings, &PluginSettings::settingsChanged,
this, &Plugin::settingsChanged);
saveSettings();
}
/************************************************
************************************************/
Plugin::~Plugin()
{
delete mPlugin;
delete mPluginLoader;
delete mSettings;
}
void Plugin::setAlignment(Plugin::Alignment alignment)
{
mAlignment = alignment;
saveSettings();
}
/************************************************
************************************************/
namespace
{
//helper types for static plugins storage & binary search
typedef std::unique_ptr<ILXQtPanelPluginLibrary> plugin_ptr_t;
typedef std::tuple<QString, plugin_ptr_t, void *> plugin_tuple_t;
//NOTE: Please keep the plugins sorted by name while adding new plugins.
//NOTE2: we need to reference some (dummy) symbol from (autogenerated) LXQtPluginTranslationLoader.cpp
// to be not stripped (as unused/unreferenced) in static linking time
static plugin_tuple_t const static_plugins[] = {
#if defined(WITH_CLOCK_PLUGIN)
std::make_tuple(QLatin1String("clock"), plugin_ptr_t{new LXQtClockPluginLibrary}, loadPluginTranslation_clock_helper),// clock
#endif
#if defined(WITH_DESKTOPSWITCH_PLUGIN)
std::make_tuple(QLatin1String("desktopswitch"), plugin_ptr_t{new DesktopSwitchPluginLibrary}, loadPluginTranslation_desktopswitch_helper),// desktopswitch
#endif
#if defined(WITH_MAINMENU_PLUGIN)
std::make_tuple(QLatin1String("mainmenu"), plugin_ptr_t{new LXQtMainMenuPluginLibrary}, loadPluginTranslation_mainmenu_helper),// mainmenu
#endif
#if defined(WITH_QUICKLAUNCH_PLUGIN)
std::make_tuple(QLatin1String("quicklaunch"), plugin_ptr_t{new LXQtQuickLaunchPluginLibrary}, loadPluginTranslation_quicklaunch_helper),// quicklaunch
#endif
#if defined(WITH_SHOWDESKTOP_PLUGIN)
std::make_tuple(QLatin1String("showdesktop"), plugin_ptr_t{new ShowDesktopLibrary}, loadPluginTranslation_showdesktop_helper),// showdesktop
#endif
#if defined(WITH_SPACER_PLUGIN)
std::make_tuple(QLatin1String("spacer"), plugin_ptr_t{new SpacerPluginLibrary}, loadPluginTranslation_spacer_helper),// spacer
#endif
#if defined(WITH_STATUSNOTIFIER_PLUGIN)
std::make_tuple(QLatin1String("statusnotifier"), plugin_ptr_t{new StatusNotifierLibrary}, loadPluginTranslation_statusnotifier_helper),// statusnotifier
#endif
#if defined(WITH_TASKBAR_PLUGIN)
std::make_tuple(QLatin1String("taskbar"), plugin_ptr_t{new LXQtTaskBarPluginLibrary}, loadPluginTranslation_taskbar_helper),// taskbar
#endif
#if defined(WITH_TRAY_PLUGIN)
std::make_tuple(QLatin1String("tray"), plugin_ptr_t{new LXQtTrayPluginLibrary}, loadPluginTranslation_tray_helper),// tray
#endif
#if defined(WITH_WORLDCLOCK_PLUGIN)
std::make_tuple(QLatin1String("worldclock"), plugin_ptr_t{new LXQtWorldClockLibrary}, loadPluginTranslation_worldclock_helper),// worldclock
#endif
};
static constexpr plugin_tuple_t const * const plugins_begin = static_plugins;
static constexpr plugin_tuple_t const * const plugins_end = static_plugins + sizeof (static_plugins) / sizeof (static_plugins[0]);
struct assert_helper
{
assert_helper()
{
Q_ASSERT(std::is_sorted(plugins_begin, plugins_end
, [] (plugin_tuple_t const & p1, plugin_tuple_t const & p2) -> bool { return std::get<0>(p1) < std::get<0>(p2); }));
}
};
static assert_helper h;
}
ILXQtPanelPluginLibrary const * Plugin::findStaticPlugin(const QString &libraryName)
{
// find a static plugin library by name -> binary search
plugin_tuple_t const * plugin = std::lower_bound(plugins_begin, plugins_end, libraryName
, [] (plugin_tuple_t const & plugin, QString const & name) -> bool { return std::get<0>(plugin) < name; });
if (plugins_end != plugin && libraryName == std::get<0>(*plugin))
return std::get<1>(*plugin).get();
return nullptr;
}
// load a plugin from a library
bool Plugin::loadLib(ILXQtPanelPluginLibrary const * pluginLib)
{
ILXQtPanelPluginStartupInfo startupInfo;
startupInfo.settings = mSettings;
startupInfo.desktopFile = &mDesktopFile;
startupInfo.lxqtPanel = mPanel;
mPlugin = pluginLib->instance(startupInfo);
if (!mPlugin)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin can't build ILXQtPanelPlugin.").arg(mPluginLoader->fileName());
return false;
}
mPluginWidget = mPlugin->widget();
if (mPluginWidget)
{
mPluginWidget->setObjectName(mPlugin->themeId());
}
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
return true;
}
// load dynamic plugin from a *.so module
bool Plugin::loadModule(const QString &libraryName)
{
mPluginLoader = new QPluginLoader(libraryName);
if (!mPluginLoader->load())
{
qWarning() << mPluginLoader->errorString();
return false;
}
QObject *obj = mPluginLoader->instance();
if (!obj)
{
qWarning() << mPluginLoader->errorString();
return false;
}
ILXQtPanelPluginLibrary* pluginLib= qobject_cast<ILXQtPanelPluginLibrary*>(obj);
if (!pluginLib)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin is not a ILXQtPanelPluginLibrary.").arg(mPluginLoader->fileName());
delete obj;
return false;
}
return loadLib(pluginLib);
}
/************************************************
************************************************/
void Plugin::settingsChanged()
{
mPlugin->settingsChanged();
}
/************************************************
************************************************/
void Plugin::saveSettings()
{
mSettings->setValue("alignment", (mAlignment == AlignLeft) ? "Left" : "Right");
mSettings->setValue("type", mDesktopFile.id());
mSettings->sync();
}
/************************************************
************************************************/
void Plugin::contextMenuEvent(QContextMenuEvent *event)
{
mPanel->showPopupMenu(this);
}
/************************************************
************************************************/
void Plugin::mousePressEvent(QMouseEvent *event)
{
switch (event->button())
{
case Qt::LeftButton:
mPlugin->activated(ILXQtPanelPlugin::Trigger);
break;
case Qt::MidButton:
mPlugin->activated(ILXQtPanelPlugin::MiddleClick);
break;
default:
break;
}
}
/************************************************
************************************************/
void Plugin::mouseDoubleClickEvent(QMouseEvent*)
{
mPlugin->activated(ILXQtPanelPlugin::DoubleClick);
}
/************************************************
************************************************/
void Plugin::showEvent(QShowEvent *)
{
if (mPluginWidget)
mPluginWidget->adjustSize();
}
/************************************************
************************************************/
QMenu *Plugin::popupMenu() const
{
QString name = this->name().replace("&", "&&");
QMenu* menu = new QMenu(windowTitle());
if (mPlugin->flags().testFlag(ILXQtPanelPlugin::HaveConfigDialog))
{
QAction* configAction = new QAction(
XdgIcon::fromTheme(QLatin1String("preferences-other")),
tr("Configure \"%1\"").arg(name), menu);
menu->addAction(configAction);
connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
}
QAction* moveAction = new QAction(XdgIcon::fromTheme("transform-move"), tr("Move \"%1\"").arg(name), menu);
menu->addAction(moveAction);
connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));
menu->addSeparator();
QAction* removeAction = new QAction(
XdgIcon::fromTheme(QLatin1String("list-remove")),
tr("Remove \"%1\"").arg(name), menu);
menu->addAction(removeAction);
connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));
return menu;
}
/************************************************
************************************************/
bool Plugin::isSeparate() const
{
return mPlugin->isSeparate();
}
/************************************************
************************************************/
bool Plugin::isExpandable() const
{
return mPlugin->isExpandable();
}
/************************************************
************************************************/
void Plugin::realign()
{
if (mPlugin)
mPlugin->realign();
}
/************************************************
************************************************/
void Plugin::showConfigureDialog()
{
if (!mConfigDialog)
mConfigDialog = mPlugin->configureDialog();
if (!mConfigDialog)
return;
connect(this, &Plugin::destroyed, mConfigDialog, &QWidget::close);
mPanel->willShowWindow(mConfigDialog);
mConfigDialog->show();
mConfigDialog->raise();
mConfigDialog->activateWindow();
}
/************************************************
************************************************/
void Plugin::requestRemove()
{
emit remove();
deleteLater();
}
<commit_msg>plugin: Force config dialog activation/raise<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "plugin.h"
#include "ilxqtpanelplugin.h"
#include "pluginsettings_p.h"
#include "lxqtpanel.h"
#include <QDebug>
#include <QProcessEnvironment>
#include <QStringList>
#include <QDir>
#include <QFileInfo>
#include <QPluginLoader>
#include <QGridLayout>
#include <QDialog>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QApplication>
#include <QWindow>
#include <memory>
#include <LXQt/Settings>
#include <LXQt/Translator>
#include <XdgIcon>
// statically linked built-in plugins
#include "../plugin-clock/lxqtclock.h" // clock
extern void * loadPluginTranslation_clock_helper;
#include "../plugin-desktopswitch/desktopswitch.h" // desktopswitch
extern void * loadPluginTranslation_desktopswitch_helper;
#include "../plugin-mainmenu/lxqtmainmenu.h" // mainmenu
extern void * loadPluginTranslation_mainmenu_helper;
#include "../plugin-quicklaunch/lxqtquicklaunchplugin.h" // quicklaunch
extern void * loadPluginTranslation_quicklaunch_helper;
#include "../plugin-showdesktop/showdesktop.h" // showdesktop
extern void * loadPluginTranslation_showdesktop_helper;
#include "../plugin-spacer/spacer.h" // spacer
extern void * loadPluginTranslation_spacer_helper;
#include "../plugin-statusnotifier/statusnotifier.h" // statusnotifier
extern void * loadPluginTranslation_statusnotifier_helper;
#include "../plugin-taskbar/lxqttaskbarplugin.h" // taskbar
extern void * loadPluginTranslation_taskbar_helper;
#include "../plugin-tray/lxqttrayplugin.h" // tray
extern void * loadPluginTranslation_tray_helper;
#include "../plugin-worldclock/lxqtworldclock.h" // worldclock
extern void * loadPluginTranslation_worldclock_helper;
QColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);
/************************************************
************************************************/
Plugin::Plugin(const LXQt::PluginInfo &desktopFile, LXQt::Settings *settings, const QString &settingsGroup, LXQtPanel *panel) :
QFrame(panel),
mDesktopFile(desktopFile),
mPluginLoader(0),
mPlugin(0),
mPluginWidget(0),
mAlignment(AlignLeft),
mPanel(panel)
{
mSettings = PluginSettingsFactory::create(settings, settingsGroup);
setWindowTitle(desktopFile.name());
mName = desktopFile.name();
QStringList dirs;
dirs << QProcessEnvironment::systemEnvironment().value("LXQTPANEL_PLUGIN_PATH").split(":");
dirs << PLUGIN_DIR;
bool found = false;
if(ILXQtPanelPluginLibrary const * pluginLib = findStaticPlugin(desktopFile.id()))
{
// this is a static plugin
found = true;
loadLib(pluginLib);
}
else {
// this plugin is a dynamically loadable module
QString baseName = QString("lib%1.so").arg(desktopFile.id());
foreach(const QString &dirName, dirs)
{
QFileInfo fi(QDir(dirName), baseName);
if (fi.exists())
{
found = true;
if (loadModule(fi.absoluteFilePath()))
break;
}
}
}
if (!isLoaded())
{
if (!found)
qWarning() << QString("Plugin %1 not found in the").arg(desktopFile.id()) << dirs;
return;
}
setObjectName(mPlugin->themeId() + "Plugin");
// plugin handle for easy context menu
setProperty("NeedsHandle", mPlugin->flags().testFlag(ILXQtPanelPlugin::NeedsHandle));
QString s = mSettings->value("alignment").toString();
// Retrun default value
if (s.isEmpty())
{
mAlignment = (mPlugin->flags().testFlag(ILXQtPanelPlugin::PreferRightAlignment)) ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
else
{
mAlignment = (s.toUpper() == "RIGHT") ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
if (mPluginWidget)
{
QGridLayout* layout = new QGridLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
layout->addWidget(mPluginWidget, 0, 0);
}
// delay the connection to settingsChanged to avoid conflicts
// while the plugin is still being initialized
connect(mSettings, &PluginSettings::settingsChanged,
this, &Plugin::settingsChanged);
saveSettings();
}
/************************************************
************************************************/
Plugin::~Plugin()
{
delete mPlugin;
delete mPluginLoader;
delete mSettings;
}
void Plugin::setAlignment(Plugin::Alignment alignment)
{
mAlignment = alignment;
saveSettings();
}
/************************************************
************************************************/
namespace
{
//helper types for static plugins storage & binary search
typedef std::unique_ptr<ILXQtPanelPluginLibrary> plugin_ptr_t;
typedef std::tuple<QString, plugin_ptr_t, void *> plugin_tuple_t;
//NOTE: Please keep the plugins sorted by name while adding new plugins.
//NOTE2: we need to reference some (dummy) symbol from (autogenerated) LXQtPluginTranslationLoader.cpp
// to be not stripped (as unused/unreferenced) in static linking time
static plugin_tuple_t const static_plugins[] = {
#if defined(WITH_CLOCK_PLUGIN)
std::make_tuple(QLatin1String("clock"), plugin_ptr_t{new LXQtClockPluginLibrary}, loadPluginTranslation_clock_helper),// clock
#endif
#if defined(WITH_DESKTOPSWITCH_PLUGIN)
std::make_tuple(QLatin1String("desktopswitch"), plugin_ptr_t{new DesktopSwitchPluginLibrary}, loadPluginTranslation_desktopswitch_helper),// desktopswitch
#endif
#if defined(WITH_MAINMENU_PLUGIN)
std::make_tuple(QLatin1String("mainmenu"), plugin_ptr_t{new LXQtMainMenuPluginLibrary}, loadPluginTranslation_mainmenu_helper),// mainmenu
#endif
#if defined(WITH_QUICKLAUNCH_PLUGIN)
std::make_tuple(QLatin1String("quicklaunch"), plugin_ptr_t{new LXQtQuickLaunchPluginLibrary}, loadPluginTranslation_quicklaunch_helper),// quicklaunch
#endif
#if defined(WITH_SHOWDESKTOP_PLUGIN)
std::make_tuple(QLatin1String("showdesktop"), plugin_ptr_t{new ShowDesktopLibrary}, loadPluginTranslation_showdesktop_helper),// showdesktop
#endif
#if defined(WITH_SPACER_PLUGIN)
std::make_tuple(QLatin1String("spacer"), plugin_ptr_t{new SpacerPluginLibrary}, loadPluginTranslation_spacer_helper),// spacer
#endif
#if defined(WITH_STATUSNOTIFIER_PLUGIN)
std::make_tuple(QLatin1String("statusnotifier"), plugin_ptr_t{new StatusNotifierLibrary}, loadPluginTranslation_statusnotifier_helper),// statusnotifier
#endif
#if defined(WITH_TASKBAR_PLUGIN)
std::make_tuple(QLatin1String("taskbar"), plugin_ptr_t{new LXQtTaskBarPluginLibrary}, loadPluginTranslation_taskbar_helper),// taskbar
#endif
#if defined(WITH_TRAY_PLUGIN)
std::make_tuple(QLatin1String("tray"), plugin_ptr_t{new LXQtTrayPluginLibrary}, loadPluginTranslation_tray_helper),// tray
#endif
#if defined(WITH_WORLDCLOCK_PLUGIN)
std::make_tuple(QLatin1String("worldclock"), plugin_ptr_t{new LXQtWorldClockLibrary}, loadPluginTranslation_worldclock_helper),// worldclock
#endif
};
static constexpr plugin_tuple_t const * const plugins_begin = static_plugins;
static constexpr plugin_tuple_t const * const plugins_end = static_plugins + sizeof (static_plugins) / sizeof (static_plugins[0]);
struct assert_helper
{
assert_helper()
{
Q_ASSERT(std::is_sorted(plugins_begin, plugins_end
, [] (plugin_tuple_t const & p1, plugin_tuple_t const & p2) -> bool { return std::get<0>(p1) < std::get<0>(p2); }));
}
};
static assert_helper h;
}
ILXQtPanelPluginLibrary const * Plugin::findStaticPlugin(const QString &libraryName)
{
// find a static plugin library by name -> binary search
plugin_tuple_t const * plugin = std::lower_bound(plugins_begin, plugins_end, libraryName
, [] (plugin_tuple_t const & plugin, QString const & name) -> bool { return std::get<0>(plugin) < name; });
if (plugins_end != plugin && libraryName == std::get<0>(*plugin))
return std::get<1>(*plugin).get();
return nullptr;
}
// load a plugin from a library
bool Plugin::loadLib(ILXQtPanelPluginLibrary const * pluginLib)
{
ILXQtPanelPluginStartupInfo startupInfo;
startupInfo.settings = mSettings;
startupInfo.desktopFile = &mDesktopFile;
startupInfo.lxqtPanel = mPanel;
mPlugin = pluginLib->instance(startupInfo);
if (!mPlugin)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin can't build ILXQtPanelPlugin.").arg(mPluginLoader->fileName());
return false;
}
mPluginWidget = mPlugin->widget();
if (mPluginWidget)
{
mPluginWidget->setObjectName(mPlugin->themeId());
}
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
return true;
}
// load dynamic plugin from a *.so module
bool Plugin::loadModule(const QString &libraryName)
{
mPluginLoader = new QPluginLoader(libraryName);
if (!mPluginLoader->load())
{
qWarning() << mPluginLoader->errorString();
return false;
}
QObject *obj = mPluginLoader->instance();
if (!obj)
{
qWarning() << mPluginLoader->errorString();
return false;
}
ILXQtPanelPluginLibrary* pluginLib= qobject_cast<ILXQtPanelPluginLibrary*>(obj);
if (!pluginLib)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin is not a ILXQtPanelPluginLibrary.").arg(mPluginLoader->fileName());
delete obj;
return false;
}
return loadLib(pluginLib);
}
/************************************************
************************************************/
void Plugin::settingsChanged()
{
mPlugin->settingsChanged();
}
/************************************************
************************************************/
void Plugin::saveSettings()
{
mSettings->setValue("alignment", (mAlignment == AlignLeft) ? "Left" : "Right");
mSettings->setValue("type", mDesktopFile.id());
mSettings->sync();
}
/************************************************
************************************************/
void Plugin::contextMenuEvent(QContextMenuEvent *event)
{
mPanel->showPopupMenu(this);
}
/************************************************
************************************************/
void Plugin::mousePressEvent(QMouseEvent *event)
{
switch (event->button())
{
case Qt::LeftButton:
mPlugin->activated(ILXQtPanelPlugin::Trigger);
break;
case Qt::MidButton:
mPlugin->activated(ILXQtPanelPlugin::MiddleClick);
break;
default:
break;
}
}
/************************************************
************************************************/
void Plugin::mouseDoubleClickEvent(QMouseEvent*)
{
mPlugin->activated(ILXQtPanelPlugin::DoubleClick);
}
/************************************************
************************************************/
void Plugin::showEvent(QShowEvent *)
{
if (mPluginWidget)
mPluginWidget->adjustSize();
}
/************************************************
************************************************/
QMenu *Plugin::popupMenu() const
{
QString name = this->name().replace("&", "&&");
QMenu* menu = new QMenu(windowTitle());
if (mPlugin->flags().testFlag(ILXQtPanelPlugin::HaveConfigDialog))
{
QAction* configAction = new QAction(
XdgIcon::fromTheme(QLatin1String("preferences-other")),
tr("Configure \"%1\"").arg(name), menu);
menu->addAction(configAction);
connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
}
QAction* moveAction = new QAction(XdgIcon::fromTheme("transform-move"), tr("Move \"%1\"").arg(name), menu);
menu->addAction(moveAction);
connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));
menu->addSeparator();
QAction* removeAction = new QAction(
XdgIcon::fromTheme(QLatin1String("list-remove")),
tr("Remove \"%1\"").arg(name), menu);
menu->addAction(removeAction);
connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));
return menu;
}
/************************************************
************************************************/
bool Plugin::isSeparate() const
{
return mPlugin->isSeparate();
}
/************************************************
************************************************/
bool Plugin::isExpandable() const
{
return mPlugin->isExpandable();
}
/************************************************
************************************************/
void Plugin::realign()
{
if (mPlugin)
mPlugin->realign();
}
/************************************************
************************************************/
void Plugin::showConfigureDialog()
{
if (!mConfigDialog)
mConfigDialog = mPlugin->configureDialog();
if (!mConfigDialog)
return;
connect(this, &Plugin::destroyed, mConfigDialog, &QWidget::close);
mPanel->willShowWindow(mConfigDialog);
mConfigDialog->show();
mConfigDialog->raise();
mConfigDialog->activateWindow();
WId wid = mConfigDialog->windowHandle()->winId();
KWindowSystem::activateWindow(wid);
KWindowSystem::setOnDesktop(wid, KWindowSystem::currentDesktop());
}
/************************************************
************************************************/
void Plugin::requestRemove()
{
emit remove();
deleteLater();
}
<|endoftext|> |
<commit_before>/*
This program will add histograms from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hadd targetfile source1 source2 ...
or
hadd -f targetfile source1 source2 ...
(targetfile is overwritten if it exists)
For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn
f1 with h1 h2 h3 T1
f2 with h1 h4 T1 T2
f3 with h5
the result of
hadd -f x.root f1.root f2.root f3.root
will be a file x.root with
x with h1 h2 h3 h4 h5 T1 T2
where h1 will be the sum of the 2 histograms in f1 and f2
T1 will be the merge of the Trees in f1 and f2
if the source files contains histograms and Trees, one can skip
the Trees with
hadd -T targetfile source1 source2 ...
Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch
*/
#include "RConfig.h"
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TH1.h"
#include "TKey.h"
#include "TObjString.h"
#include "Riostream.h"
TList *FileList;
TFile *Target, *Source;
Bool_t noTrees;
void MergeRootfile( TDirectory *target, TList *sourcelist );
int main( int argc, char **argv ) {
if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) {
cout << "Usage: " << argv[0] << " [-f] [-T] targetfile source1 source2 [source3 ...]" << endl;
cout << "This program will add histograms from a list of root files and write them" << endl;
cout << "to a target root file. The target file is newly created and must not " << endl;
cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl;
cout << "Supply at least two source files for this to make sense... ;-)" << endl;
cout << "If the first argument is -T, Trees are not merged" <<endl;
return 1;
}
FileList = new TList();
Bool_t force = (!strcmp(argv[1],"-f") || !strcmp(argv[2],"-f"));
noTrees = (!strcmp(argv[1],"-T") || !strcmp(argv[2],"-T"));
int ffirst = 2;
if (force) ffirst++;
if (noTrees) ffirst++;
cout << "Target file: " << argv[ffirst-1] << endl;
Target = TFile::Open( argv[ffirst-1], (force?"RECREATE":"CREATE") );
if (!Target || Target->IsZombie()) {
cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl;
cerr << "Pass \"-f\" argument to force re-creation of output file." << endl;
exit(1);
}
// by default hadd can merge Trees in a file that can go up to 100 Gbytes
Long64_t maxsize = 100000000; //100GB
maxsize *= 100; //to bypass some compiler limitations with big constants
TTree::SetMaxTreeSize(maxsize);
for ( int i = ffirst; i < argc; i++ ) {
cout << "Source file " << i-ffirst+1 << ": " << argv[i] << endl;
Source = TFile::Open( argv[i] );
FileList->Add(Source);
}
MergeRootfile( Target, FileList );
//must delete Target to avoid a problem with dictionaries in~ TROOT
delete Target;
return 0;
}
void MergeRootfile( TDirectory *target, TList *sourcelist ) {
// cout << "Target path: " << target->GetPath() << endl;
TString path( (char*)strstr( target->GetPath(), ":" ) );
path.Remove( 0, 2 );
TFile *first_source = (TFile*)sourcelist->First();
THashList allNames;
while(first_source) {
first_source->cd( path );
TDirectory *current_sourcedir = gDirectory;
// loop over all keys in this directory
TChain *globChain = 0;
TIter nextkey( current_sourcedir->GetListOfKeys() );
TKey *key, *oldkey=0;
//gain time, do not add the objects in the list in memory
TH1::AddDirectory(kFALSE);
while ( (key = (TKey*)nextkey())) {
//keep only the highest cycle number for each key
if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;
if (allNames.FindObject(key->GetName())) continue;
allNames.Add(new TObjString(key->GetName()));
// read object from first source file
first_source->cd( path );
TObject *obj = key->ReadObj();
if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) {
// descendant of TH1 -> merge it
//cout << "Merging histogram " << obj->GetName() << endl;
TH1 *h1 = (TH1*)obj;
TList listH;
// loop over all source files and add the content of the
// correspondant histogram to the one pointed to by "h1"
TFile *nextsource = (TFile*)sourcelist->After( first_source );
while ( nextsource ) {
// make sure we are at the correct directory level by cd'ing to path
nextsource->cd( path );
TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
if (key2) {
listH.Add(key2->ReadObj());
h1->Merge(&listH);
listH.Delete();
}
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
// loop over all source files create a chain of Trees "globChain"
if (!noTrees) {
TString obj_name;
if (path.Length()) {
obj_name = path + "/" + obj->GetName();
} else {
obj_name = obj->GetName();
}
globChain = new TChain(obj_name);
globChain->Add(first_source->GetName());
TFile *nextsource = (TFile*)sourcelist->After( first_source );
// const char* file_name = nextsource->GetName();
// cout << "file name " << file_name << endl;
while ( nextsource ) {
//do not add to the list a file that does not contain this Tree
TFile *curf = TFile::Open(nextsource->GetName());
if (curf && curf->FindObject(obj_name)) {
globChain->Add(nextsource->GetName());
}
delete curf;
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
} else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
// it's a subdirectory
cout << "Found subdirectory " << obj->GetName() << endl;
// create a new subdir of same name and title in the target file
target->cd();
TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );
// newdir is now the starting point of another round of merging
// newdir still knows its depth within the target file via
// GetPath(), so we can still figure out where we are in the recursion
MergeRootfile( newdir, sourcelist );
} else {
// object is of no type that we know or can handle
cout << "Unknown object type, name: "
<< obj->GetName() << " title: " << obj->GetTitle() << endl;
}
// now write the merged histogram (which is "in" obj) to the target file
// note that this will just store obj in the current directory level,
// which is not persistent until the complete directory itself is stored
// by "target->Write()" below
if ( obj ) {
target->cd();
//!!if the object is a tree, it is stored in globChain...
if(obj->IsA()->InheritsFrom( "TTree" )) {
if (!noTrees) {
globChain->Merge(target->GetFile(),0,"keep");
delete globChain;
}
} else {
obj->Write( key->GetName() );
}
}
oldkey = key;
} // while ( ( TKey *key = (TKey*)nextkey() ) )
sourcelist->Remove(first_source);
first_source = (TFile*)sourcelist->First();
}
// save modifications to target file
target->SaveSelf(kTRUE);
}
<commit_msg>It is now possible to specify the compression factor of the destination file. hadd -f result.root file1.root file2.root (case 1) hadd -f0 result.root file1.root file2.root (case 2) hadd -f6 result.root file1.root (case 3)<commit_after>/*
This program will add histograms from a list of root files and write them
to a target root file. The target file is newly created and must not be
identical to one of the source files.
Syntax:
hadd targetfile source1 source2 ...
or
hadd -f targetfile source1 source2 ...
(targetfile is overwritten if it exists)
When -the -f option is specified, one can also specify the compression
level of the target file. By default the compression level is 1, but
if "-f0" is specified, the target file will not be compressed.
if "-f6" is specified, the compression level 6 will be used.
For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn
f1 with h1 h2 h3 T1
f2 with h1 h4 T1 T2
f3 with h5
the result of
hadd -f x.root f1.root f2.root f3.root
will be a file x.root with
x with h1 h2 h3 h4 h5 T1 T2
where h1 will be the sum of the 2 histograms in f1 and f2
T1 will be the merge of the Trees in f1 and f2
if the source files contains histograms and Trees, one can skip
the Trees with
hadd -T targetfile source1 source2 ...
Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch
*/
#include "RConfig.h"
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TH1.h"
#include "TKey.h"
#include "TObjString.h"
#include "Riostream.h"
TList *FileList;
TFile *Target, *Source;
Bool_t noTrees;
void MergeRootfile( TDirectory *target, TList *sourcelist );
int main( int argc, char **argv ) {
if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) {
cout << "Usage: " << argv[0] << " [-f] [-T] targetfile source1 source2 [source3 ...]" << endl;
cout << "This program will add histograms from a list of root files and write them" << endl;
cout << "to a target root file. The target file is newly created and must not " << endl;
cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl;
cout << "Supply at least two source files for this to make sense... ;-)" << endl;
cout << "If the first argument is -T, Trees are not merged" <<endl;
cout << "When -the -f option is specified, one can also specify the compression" <<endl;
cout << "level of the target file. By default the compression level is 1, but" <<endl;
cout << "if \"-f0\" is specified, the target file will not be compressed." <<endl;
cout << "if \"-f6\" is specified, the compression level 6 will be used." <<endl;
return 1;
}
FileList = new TList();
Bool_t force = (!strcmp(argv[1],"-f") || !strcmp(argv[2],"-f"));
noTrees = (!strcmp(argv[1],"-T") || !strcmp(argv[2],"-T"));
Int_t newcomp = 1;
char ft[4];
for (int j=0;j<9;j++) {
sprintf(ft,"-f%d",j);
if (!strcmp(argv[1],ft) || !strcmp(argv[2],ft)) {
force = kTRUE;
newcomp = j;
break;
}
}
int ffirst = 2;
if (force) ffirst++;
if (noTrees) ffirst++;
cout << "Target file: " << argv[ffirst-1] << endl;
Target = TFile::Open( argv[ffirst-1], (force?"RECREATE":"CREATE") );
if (!Target || Target->IsZombie()) {
cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl;
cerr << "Pass \"-f\" argument to force re-creation of output file." << endl;
exit(1);
}
Target->SetCompressionLevel(newcomp);
// by default hadd can merge Trees in a file that can go up to 100 Gbytes
Long64_t maxsize = 100000000; //100GB
maxsize *= 100; //to bypass some compiler limitations with big constants
TTree::SetMaxTreeSize(maxsize);
for ( int i = ffirst; i < argc; i++ ) {
cout << "Source file " << i-ffirst+1 << ": " << argv[i] << endl;
Source = TFile::Open( argv[i] );
FileList->Add(Source);
}
MergeRootfile( Target, FileList );
//must delete Target to avoid a problem with dictionaries in~ TROOT
delete Target;
return 0;
}
void MergeRootfile( TDirectory *target, TList *sourcelist ) {
// cout << "Target path: " << target->GetPath() << endl;
TString path( (char*)strstr( target->GetPath(), ":" ) );
path.Remove( 0, 2 );
TFile *first_source = (TFile*)sourcelist->First();
THashList allNames;
while(first_source) {
first_source->cd( path );
TDirectory *current_sourcedir = gDirectory;
// loop over all keys in this directory
TChain *globChain = 0;
TIter nextkey( current_sourcedir->GetListOfKeys() );
TKey *key, *oldkey=0;
//gain time, do not add the objects in the list in memory
TH1::AddDirectory(kFALSE);
while ( (key = (TKey*)nextkey())) {
//keep only the highest cycle number for each key
if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;
if (allNames.FindObject(key->GetName())) continue;
allNames.Add(new TObjString(key->GetName()));
// read object from first source file
first_source->cd( path );
TObject *obj = key->ReadObj();
if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) {
// descendant of TH1 -> merge it
//cout << "Merging histogram " << obj->GetName() << endl;
TH1 *h1 = (TH1*)obj;
TList listH;
// loop over all source files and add the content of the
// correspondant histogram to the one pointed to by "h1"
TFile *nextsource = (TFile*)sourcelist->After( first_source );
while ( nextsource ) {
// make sure we are at the correct directory level by cd'ing to path
nextsource->cd( path );
TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
if (key2) {
listH.Add(key2->ReadObj());
h1->Merge(&listH);
listH.Delete();
}
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
// loop over all source files create a chain of Trees "globChain"
if (!noTrees) {
TString obj_name;
if (path.Length()) {
obj_name = path + "/" + obj->GetName();
} else {
obj_name = obj->GetName();
}
globChain = new TChain(obj_name);
globChain->Add(first_source->GetName());
TFile *nextsource = (TFile*)sourcelist->After( first_source );
// const char* file_name = nextsource->GetName();
// cout << "file name " << file_name << endl;
while ( nextsource ) {
//do not add to the list a file that does not contain this Tree
TFile *curf = TFile::Open(nextsource->GetName());
if (curf && curf->FindObject(obj_name)) {
globChain->Add(nextsource->GetName());
}
delete curf;
nextsource = (TFile*)sourcelist->After( nextsource );
}
}
} else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
// it's a subdirectory
cout << "Found subdirectory " << obj->GetName() << endl;
// create a new subdir of same name and title in the target file
target->cd();
TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );
// newdir is now the starting point of another round of merging
// newdir still knows its depth within the target file via
// GetPath(), so we can still figure out where we are in the recursion
MergeRootfile( newdir, sourcelist );
} else {
// object is of no type that we know or can handle
cout << "Unknown object type, name: "
<< obj->GetName() << " title: " << obj->GetTitle() << endl;
}
// now write the merged histogram (which is "in" obj) to the target file
// note that this will just store obj in the current directory level,
// which is not persistent until the complete directory itself is stored
// by "target->Write()" below
if ( obj ) {
target->cd();
//!!if the object is a tree, it is stored in globChain...
if(obj->IsA()->InheritsFrom( "TTree" )) {
if (!noTrees) {
globChain->Merge(target->GetFile(),0,"keep");
delete globChain;
}
} else {
obj->Write( key->GetName() );
}
}
oldkey = key;
} // while ( ( TKey *key = (TKey*)nextkey() ) )
sourcelist->Remove(first_source);
first_source = (TFile*)sourcelist->First();
}
// save modifications to target file
target->SaveSelf(kTRUE);
}
<|endoftext|> |
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Overpass_API 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 Overpass_API. If not, see <http://www.gnu.org/licenses/>.
*/
#include "output.h"
#include "web_output.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void Web_Output::add_encoding_error(const string& error)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"encoding error: "<<error;
display_error(out.str(), 400);
}
encoding_errors = true;
}
void Web_Output::add_parse_error(const string& error, int line_number)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"line "<<line_number<<": parse error: "<<error;
display_error(out.str(), 400);
}
parse_errors = true;
}
void Web_Output::add_static_error(const string& error, int line_number)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"line "<<line_number<<": static error: "<<error;
display_error(out.str(), 400);
}
static_errors = true;
}
void Web_Output::add_encoding_remark(const string& error)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"encoding remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::add_parse_remark(const string& error, int line_number)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"line "<<line_number<<": parse remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::add_static_remark(const string& error, int line_number)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"line "<<line_number<<": static remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::runtime_error(const string& error)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"runtime error: "<<error;
display_error(out.str(), 200);
}
}
void Web_Output::runtime_remark(const string& error)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"runtime remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::enforce_header(uint write_mime)
{
if (header_written == not_yet)
write_html_header("", "", write_mime);
}
void Web_Output::write_html_header
(const string& timestamp, const string& area_timestamp, uint write_mime, bool write_js_init,
bool write_remarks)
{
if (header_written != not_yet)
return;
header_written = html;
if (write_mime > 0)
{
if (write_mime != 200)
{
if (write_mime == 504)
cout<<"Status: "<<write_mime<<" Gateway Timeout\n";
else if (write_mime == 400)
cout<<"Status: "<<write_mime<<" Bad Request\n";
else if (write_mime == 429)
cout<<"Status: "<<write_mime<<" Too Many Requests\n";
else
cout<<"Status: "<<write_mime<<"\n";
}
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: text/html; charset=utf-8\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
cout<<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
"<head>\n"
" <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n"
" <title>OSM3S Response</title>\n"
"</head>\n";
cout<<(write_js_init ? "<body onload=\"init()\">\n\n" : "<body>\n\n");
if (write_remarks)
{
cout<<
"<p>The data included in this document is from www.openstreetmap.org. "
"The data is made available under ODbL.</p>\n";
if (timestamp != "")
{
cout<<"<p>Data included until: "<<timestamp;
if (area_timestamp != "")
cout<<"<br/>Areas based on data until: "<<area_timestamp;
cout<<"</p>\n";
}
}
}
void Web_Output::write_xml_header
(const string& timestamp, const string& area_timestamp, bool write_mime)
{
if (header_written != not_yet)
return;
header_written = xml;
if (write_mime)
{
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: application/osm3s+xml\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
cout<<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"0.6\" generator=\"Overpass API\">\n"
"<note>The data included in this document is from www.openstreetmap.org. "
"The data is made available under ODbL.</note>\n";
cout<<"<meta osm_base=\""<<timestamp<<'\"';
if (area_timestamp != "")
cout<<" areas=\""<<area_timestamp<<"\"";
cout<<"/>\n\n";
}
void Web_Output::write_json_header
(const string& timestamp, const string& area_timestamp, bool write_mime)
{
if (header_written != not_yet)
return;
header_written = json;
if (write_mime)
{
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: application/json\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
if (padding != "")
cout<<padding<<"(";
cout<<"{\n"
" \"version\": 0.6,\n"
" \"generator\": \"Overpass API\",\n"
" \"osm3s\": {\n"
" \"timestamp_osm_base\": \""<<timestamp<<"\",\n";
if (area_timestamp != "")
cout<<" \"timestamp_areas_base\": \""<<area_timestamp<<"\",\n";
cout<<" \"copyright\": \"The data included in this document is from www.openstreetmap.org."
" The data is made available under ODbL.\"\n"
" },\n"
" \"elements\": [\n\n";
}
void Web_Output::write_text_header
(const string& timestamp, const string& area_timestamp, bool write_mime)
{
if (header_written != not_yet)
return;
header_written = text;
if (write_mime)
{
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: text/plain\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
cout<<timestamp<<"\n";
}
void Web_Output::write_footer()
{
if (http_method == http_options || http_method == http_head)
return;
if (header_written == xml)
cout<<"\n</osm>\n";
else if (header_written == html)
cout<<"\n</body>\n</html>\n";
else if (header_written == json)
cout<<"\n\n ]"<<(messages != "" ? ",\n\"remark\": \"" + escape_cstr(messages) + "\"" : "")
<<"\n}"<<(padding != "" ? ");\n" : "\n");
header_written = final;
}
void Web_Output::display_remark(const string& text)
{
enforce_header(200);
if (http_method == http_options || http_method == http_head)
return;
if (header_written == xml)
cout<<"<remark> "<<text<<" </remark>\n";
else if (header_written == html)
cout<<"<p><strong style=\"color:#00BB00\">Remark</strong>: "
<<text<<" </p>\n";
}
void Web_Output::display_error(const string& text, uint write_mime)
{
enforce_header(write_mime);
if (http_method == http_options || http_method == http_head)
return;
if (header_written == xml)
cout<<"<remark> "<<text<<" </remark>\n";
else if (header_written == html)
cout<<"<p><strong style=\"color:#FF0000\">Error</strong>: "
<<text<<" </p>\n";
else if (header_written == json)
messages += text;
}
<commit_msg>Remove whitespace<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Overpass_API 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 Overpass_API. If not, see <http://www.gnu.org/licenses/>.
*/
#include "output.h"
#include "web_output.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void Web_Output::add_encoding_error(const string& error)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"encoding error: "<<error;
display_error(out.str(), 400);
}
encoding_errors = true;
}
void Web_Output::add_parse_error(const string& error, int line_number)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"line "<<line_number<<": parse error: "<<error;
display_error(out.str(), 400);
}
parse_errors = true;
}
void Web_Output::add_static_error(const string& error, int line_number)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"line "<<line_number<<": static error: "<<error;
display_error(out.str(), 400);
}
static_errors = true;
}
void Web_Output::add_encoding_remark(const string& error)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"encoding remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::add_parse_remark(const string& error, int line_number)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"line "<<line_number<<": parse remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::add_static_remark(const string& error, int line_number)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"line "<<line_number<<": static remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::runtime_error(const string& error)
{
if (log_level != Error_Output::QUIET)
{
ostringstream out;
out<<"runtime error: "<<error;
display_error(out.str(), 200);
}
}
void Web_Output::runtime_remark(const string& error)
{
if (log_level == Error_Output::VERBOSE)
{
ostringstream out;
out<<"runtime remark: "<<error;
display_remark(out.str());
}
}
void Web_Output::enforce_header(uint write_mime)
{
if (header_written == not_yet)
write_html_header("", "", write_mime);
}
void Web_Output::write_html_header
(const string& timestamp, const string& area_timestamp, uint write_mime, bool write_js_init,
bool write_remarks)
{
if (header_written != not_yet)
return;
header_written = html;
if (write_mime > 0)
{
if (write_mime != 200)
{
if (write_mime == 504)
cout<<"Status: "<<write_mime<<" Gateway Timeout\n";
else if (write_mime == 400)
cout<<"Status: "<<write_mime<<" Bad Request\n";
else if (write_mime == 429)
cout<<"Status: "<<write_mime<<" Too Many Requests\n";
else
cout<<"Status: "<<write_mime<<"\n";
}
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: text/html; charset=utf-8\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
cout<<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
"<head>\n"
" <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n"
" <title>OSM3S Response</title>\n"
"</head>\n";
cout<<(write_js_init ? "<body onload=\"init()\">\n\n" : "<body>\n\n");
if (write_remarks)
{
cout<<
"<p>The data included in this document is from www.openstreetmap.org. "
"The data is made available under ODbL.</p>\n";
if (timestamp != "")
{
cout<<"<p>Data included until: "<<timestamp;
if (area_timestamp != "")
cout<<"<br/>Areas based on data until: "<<area_timestamp;
cout<<"</p>\n";
}
}
}
void Web_Output::write_xml_header
(const string& timestamp, const string& area_timestamp, bool write_mime)
{
if (header_written != not_yet)
return;
header_written = xml;
if (write_mime)
{
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: application/osm3s+xml\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
cout<<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"0.6\" generator=\"Overpass API\">\n"
"<note>The data included in this document is from www.openstreetmap.org. "
"The data is made available under ODbL.</note>\n";
cout<<"<meta osm_base=\""<<timestamp<<'\"';
if (area_timestamp != "")
cout<<" areas=\""<<area_timestamp<<"\"";
cout<<"/>\n\n";
}
void Web_Output::write_json_header
(const string& timestamp, const string& area_timestamp, bool write_mime)
{
if (header_written != not_yet)
return;
header_written = json;
if (write_mime)
{
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: application/json\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
if (padding != "")
cout<<padding<<"(";
cout<<"{\n"
" \"version\": 0.6,\n"
" \"generator\": \"Overpass API\",\n"
" \"osm3s\": {\n"
" \"timestamp_osm_base\": \""<<timestamp<<"\",\n";
if (area_timestamp != "")
cout<<" \"timestamp_areas_base\": \""<<area_timestamp<<"\",\n";
cout<<" \"copyright\": \"The data included in this document is from www.openstreetmap.org."
" The data is made available under ODbL.\"\n"
" },\n"
" \"elements\": [\n\n";
}
void Web_Output::write_text_header
(const string& timestamp, const string& area_timestamp, bool write_mime)
{
if (header_written != not_yet)
return;
header_written = text;
if (write_mime)
{
if (allow_headers != "")
cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n';
if (has_origin)
cout<<"Access-Control-Allow-Origin: *\n"
"Access-Control-Max-Age: 600\n";
if (http_method == http_options)
cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n"
"Content-Length: 0\n";
cout<<"Content-type: text/plain\n\n";
if (http_method == http_options || http_method == http_head)
return;
}
cout<<timestamp<<"\n";
}
void Web_Output::write_footer()
{
if (http_method == http_options || http_method == http_head)
return;
if (header_written == xml)
cout<<"\n</osm>\n";
else if (header_written == html)
cout<<"\n</body>\n</html>\n";
else if (header_written == json)
cout<<"\n\n ]"<<(messages != "" ? ",\n\"remark\": \"" + escape_cstr(messages) + "\"" : "")
<<"\n}"<<(padding != "" ? ");\n" : "\n");
header_written = final;
}
void Web_Output::display_remark(const string& text)
{
enforce_header(200);
if (http_method == http_options || http_method == http_head)
return;
if (header_written == xml)
cout<<"<remark> "<<text<<" </remark>\n";
else if (header_written == html)
cout<<"<p><strong style=\"color:#00BB00\">Remark</strong>: "
<<text<<" </p>\n";
}
void Web_Output::display_error(const string& text, uint write_mime)
{
enforce_header(write_mime);
if (http_method == http_options || http_method == http_head)
return;
if (header_written == xml)
cout<<"<remark> "<<text<<" </remark>\n";
else if (header_written == html)
cout<<"<p><strong style=\"color:#FF0000\">Error</strong>: "
<<text<<" </p>\n";
else if (header_written == json)
messages += text;
}
<|endoftext|> |
<commit_before>#include "phune_rest_jamp.h"
static s3eCallback onResultPending;
static PhuneMatch *currentMatch = NULL;
static int32 onNullReturn(void *, void*){
return 0;
}
static int32 onStartMatchReturn(void *data, void* userData){
currentMatch = static_cast<PhuneMatch*>(data);
onResultPending(NULL, userData);
return 0;
}
int32 PhuneRestJamp::Init(s3eCallback onResult, s3eCallback onError, void *userData){
return PhuneRest::Init(onResult, onError, userData);
}
int32 PhuneRestJamp::Login(s3eWebView* g_WebView, s3eCallback onResult, s3eCallback onError, void *userData){
return PhuneRest::Login(g_WebView, onResult, onError, userData);
}
int32 PhuneRestJamp::GetMe(s3eCallback onResult, s3eCallback onError, void *userData){
return PhuneRest::GetMe(onResult, onError, userData);
}
int32 PhuneRestJamp::StartMatch(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
onResultPending = onResult;
return PhuneRest::StartMatch(s.c_str(), onStartMatchReturn, onError, userData);
}
int32 PhuneRestJamp::EndMatch(JampGameId gameId, std::string level, JampScore score, PlayerStatus status, s3eCallback onResult, s3eCallback onError, void *userData){
if (currentMatch == NULL){
onError(NULL, NULL);
return 0;
}
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
std::string s3 = std::string(SCORE_LEVEL_KEY_PREFIX);
s3.append(level);
score.matchId = currentMatch->matchId;
PhunePlayer player;
player.score = score.score;
player.status = status;
player.id = currentMatch->playerId;
int64 t = getCurrentTime();
//Send the result of the match
PhuneRest::EndMatch(score.matchId, player, onResult, onError, userData);
IwTrace(PHUNE, ("Creating map begin"));
std::map<int64, JsonListObject<JsonString> > map;
int consecutivePerfects = 0;
int bestSequence = -1;
bool allPerfects = true;
//aggregate cells performance
for (std::vector<JampCellPerformance>::iterator it = score.cellsPerformance.elements.begin(); it != score.cellsPerformance.elements.end(); it++){
//Use the notes for events
if(it->useNoteEvaluation){
for (std::vector<JampNotePerformance>::iterator it2 = it->notesPerformance.elements.begin(); it2 != it->notesPerformance.elements.end(); it2++){
if (it2->classification == PERFECT) {
consecutivePerfects++;
}
else{
allPerfects = false;
if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
bestSequence = consecutivePerfects;
}
consecutivePerfects = 0;
}
}
}
//use the cell for events
else{
if (it->classification == PERFECT) {
consecutivePerfects++;
}
else{
allPerfects = false;
if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
bestSequence = consecutivePerfects;
}
consecutivePerfects = 0;
}
}
//found
if (map.find(it->cellId) == map.end()) {
JsonListObject<JsonString> list;
it->timeStamp = t;
JsonString js;
js.Deserialize(it->Serialize());
list.pushElement(js);
map.insert(std::make_pair(it->cellId,list));
}
else {
it->timeStamp = t;
std::string aux2;
JsonString js2;
js2.Deserialize(it->Serialize());
map.find(it->cellId)->second.pushElement(js2);
}
}
if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
bestSequence = consecutivePerfects;
}
IwTrace(PHUNE, ("Creating map end"));
IwTrace(PHUNE, ("Sending cells begin"));
//store the Cell performances
for (std::map<int64, JsonListObject<JsonString> >::iterator itMap = map.begin(); itMap != map.end(); itMap++){
if (itMap->first > 0) {
char buffer4[50];
sprintf(buffer4, "%s%lld", CELL_PERFORMACE_PREFIX, itMap->first);
std::string key_cell = std::string(buffer4);
std::string out = itMap->second.Serialize();
IwTrace(PHUNE, ("Sending cell %lld begin", itMap->first));
PhuneRestBase::StoreGameDataJsonBatch(s.c_str(), key_cell.c_str(), itMap->second.Serialize().c_str(), onNullReturn, onError, userData, true);
IwTrace(PHUNE, ("Sending cell %lld end", itMap->first));
}
else{
IwTrace(PHUNE, ("Cell with invalid id:%lld. Ignoring...", itMap->first));
}
}
IwTrace(PHUNE, ("Sending cells end"));
//Send the events
JsonListObject<GameTriggerdEvent> events;
//consecutive perfects
if(bestSequence != -1){
ConsecutivePerfectsEvent cpe(bestSequence, gameId);
cpe.playerId = currentMatch->playerId;
events.pushElement(cpe);
}
//all perfects
if(allPerfects){
AllPerfectsEvent ape(gameId, level);
ape.playerId = currentMatch->playerId;
events.pushElement(ape);
}
if(events.elements.size() > 0){
PhuneRest::StoreMatchEvents(events, score.matchId, onNullReturn, onError);
}
//store the score for the match
score.timeStamp = t;
PhuneRestBase::StoreGameDataJson(s.c_str(), s3.c_str(), score.Serialize().c_str(), onNullReturn, onError, NULL, true);
currentMatch = NULL;
return 0;
}
int32 PhuneRestJamp::GetHistoricScoreForLevelInGame(JampGameId gameId, const char *level, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
std::string key_score = std::string(SCORE_LEVEL_KEY_PREFIX);
key_score.append(level);
return PhuneRestBase::GetGameDataJsonList(s.c_str(), key_score.c_str(), onResult, onError, userData);
}
int32 PhuneRestJamp::StorePackInfoInGame(JampGameId gameId, JampPack pack, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
char buffer2[50];
sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
std::string s2 = std::string(buffer2);
return PhuneRestBase::StoreGameDataJson(s.c_str(), s2.c_str(), pack.Serialize().c_str(), onResult, onError, userData);
}
int32 PhuneRestJamp::GetPackInfoInGame(JampGameId gameId, int64 packid, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
char buffer2[50];
sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
std::string s2 = std::string(buffer2);
return PhuneRestBase::GetGameDataJson(s.c_str(), s2.c_str(), onResult, onError, userData);
}
int32 PhuneRestJamp::StorePacksInGame(JampGameId gameId, JsonListObject<JampPack> packs, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
int64 totalStars = 0;
int64 starsWon = 0;
for (std::vector<JampPack>::iterator it = packs.elements.begin(); it != packs.elements.end(); it++){
totalStars += it->starsMax;
starsWon += it->starsWon;
}
JampGameProgress gp;
gp.progress = (starsWon/(float)totalStars)*100;
PhuneRestBase::StoreGameDataJson(s.c_str(), GAME_PROGRESS_KEY, gp.Serialize().c_str(), onNullReturn, onError, NULL);
return PhuneRestBase::StoreGameDataJsonList(s.c_str(), PACKS_KEY, packs, onResult, onError, userData);
}
int32 PhuneRestJamp::GetPacksInGame(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
return PhuneRestBase::GetGameDataJsonList(s.c_str(), PACKS_KEY, onResult, onError, userData);
}
<commit_msg>JAMP: changed order in send package information<commit_after>#include "phune_rest_jamp.h"
static s3eCallback onResultPending;
static PhuneMatch *currentMatch = NULL;
static int32 onNullReturn(void *, void*){
return 0;
}
static int32 onStartMatchReturn(void *data, void* userData){
currentMatch = static_cast<PhuneMatch*>(data);
onResultPending(NULL, userData);
return 0;
}
int32 PhuneRestJamp::Init(s3eCallback onResult, s3eCallback onError, void *userData){
return PhuneRest::Init(onResult, onError, userData);
}
int32 PhuneRestJamp::Login(s3eWebView* g_WebView, s3eCallback onResult, s3eCallback onError, void *userData){
return PhuneRest::Login(g_WebView, onResult, onError, userData);
}
int32 PhuneRestJamp::GetMe(s3eCallback onResult, s3eCallback onError, void *userData){
return PhuneRest::GetMe(onResult, onError, userData);
}
int32 PhuneRestJamp::StartMatch(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
onResultPending = onResult;
return PhuneRest::StartMatch(s.c_str(), onStartMatchReturn, onError, userData);
}
int32 PhuneRestJamp::EndMatch(JampGameId gameId, std::string level, JampScore score, PlayerStatus status, s3eCallback onResult, s3eCallback onError, void *userData){
if (currentMatch == NULL){
onError(NULL, NULL);
return 0;
}
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
std::string s3 = std::string(SCORE_LEVEL_KEY_PREFIX);
s3.append(level);
score.matchId = currentMatch->matchId;
PhunePlayer player;
player.score = score.score;
player.status = status;
player.id = currentMatch->playerId;
int64 t = getCurrentTime();
//Send the result of the match
PhuneRest::EndMatch(score.matchId, player, onResult, onError, userData);
IwTrace(PHUNE, ("Creating map begin"));
std::map<int64, JsonListObject<JsonString> > map;
int consecutivePerfects = 0;
int bestSequence = -1;
bool allPerfects = true;
//aggregate cells performance
for (std::vector<JampCellPerformance>::iterator it = score.cellsPerformance.elements.begin(); it != score.cellsPerformance.elements.end(); it++){
//Use the notes for events
if(it->useNoteEvaluation){
for (std::vector<JampNotePerformance>::iterator it2 = it->notesPerformance.elements.begin(); it2 != it->notesPerformance.elements.end(); it2++){
if (it2->classification == PERFECT) {
consecutivePerfects++;
}
else{
allPerfects = false;
if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
bestSequence = consecutivePerfects;
}
consecutivePerfects = 0;
}
}
}
//use the cell for events
else{
if (it->classification == PERFECT) {
consecutivePerfects++;
}
else{
allPerfects = false;
if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
bestSequence = consecutivePerfects;
}
consecutivePerfects = 0;
}
}
//found
if (map.find(it->cellId) == map.end()) {
JsonListObject<JsonString> list;
it->timeStamp = t;
JsonString js;
js.Deserialize(it->Serialize());
list.pushElement(js);
map.insert(std::make_pair(it->cellId,list));
}
else {
it->timeStamp = t;
std::string aux2;
JsonString js2;
js2.Deserialize(it->Serialize());
map.find(it->cellId)->second.pushElement(js2);
}
}
if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
bestSequence = consecutivePerfects;
}
IwTrace(PHUNE, ("Creating map end"));
IwTrace(PHUNE, ("Sending cells begin"));
//store the Cell performances
for (std::map<int64, JsonListObject<JsonString> >::iterator itMap = map.begin(); itMap != map.end(); itMap++){
if (itMap->first > 0) {
char buffer4[50];
sprintf(buffer4, "%s%lld", CELL_PERFORMACE_PREFIX, itMap->first);
std::string key_cell = std::string(buffer4);
std::string out = itMap->second.Serialize();
IwTrace(PHUNE, ("Sending cell %lld begin", itMap->first));
PhuneRestBase::StoreGameDataJsonBatch(s.c_str(), key_cell.c_str(), itMap->second.Serialize().c_str(), onNullReturn, onError, userData, true);
IwTrace(PHUNE, ("Sending cell %lld end", itMap->first));
}
else{
IwTrace(PHUNE, ("Cell with invalid id:%lld. Ignoring...", itMap->first));
}
}
IwTrace(PHUNE, ("Sending cells end"));
//Send the events
JsonListObject<GameTriggerdEvent> events;
//consecutive perfects
if(bestSequence != -1){
ConsecutivePerfectsEvent cpe(bestSequence, gameId);
cpe.playerId = currentMatch->playerId;
events.pushElement(cpe);
}
//all perfects
if(allPerfects){
AllPerfectsEvent ape(gameId, level);
ape.playerId = currentMatch->playerId;
events.pushElement(ape);
}
if(events.elements.size() > 0){
PhuneRest::StoreMatchEvents(events, score.matchId, onNullReturn, onError);
}
//store the score for the match
score.timeStamp = t;
PhuneRestBase::StoreGameDataJson(s.c_str(), s3.c_str(), score.Serialize().c_str(), onNullReturn, onError, NULL, true);
currentMatch = NULL;
return 0;
}
int32 PhuneRestJamp::GetHistoricScoreForLevelInGame(JampGameId gameId, const char *level, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
std::string key_score = std::string(SCORE_LEVEL_KEY_PREFIX);
key_score.append(level);
return PhuneRestBase::GetGameDataJsonList(s.c_str(), key_score.c_str(), onResult, onError, userData);
}
int32 PhuneRestJamp::StorePackInfoInGame(JampGameId gameId, JampPack pack, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
char buffer2[50];
sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
std::string s2 = std::string(buffer2);
return PhuneRestBase::StoreGameDataJson(s.c_str(), s2.c_str(), pack.Serialize().c_str(), onResult, onError, userData);
}
int32 PhuneRestJamp::GetPackInfoInGame(JampGameId gameId, int64 packid, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
char buffer2[50];
sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
std::string s2 = std::string(buffer2);
return PhuneRestBase::GetGameDataJson(s.c_str(), s2.c_str(), onResult, onError, userData);
}
int32 PhuneRestJamp::StorePacksInGame(JampGameId gameId, JsonListObject<JampPack> packs, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
int64 totalStars = 0;
int64 starsWon = 0;
for (std::vector<JampPack>::iterator it = packs.elements.begin(); it != packs.elements.end(); it++){
totalStars += it->starsMax;
starsWon += it->starsWon;
}
JampGameProgress gp;
gp.progress = (starsWon/(float)totalStars)*100;
PhuneRestBase::StoreGameDataJsonList(s.c_str(), PACKS_KEY, packs, onResult, onError, userData);
PhuneRestBase::StoreGameDataJson(s.c_str(), GAME_PROGRESS_KEY, gp.Serialize().c_str(), onNullReturn, onError, NULL, false);
return 0;
}
int32 PhuneRestJamp::GetPacksInGame(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
char buffer[50];
sprintf(buffer, "%d", gameId);
std::string s = std::string(buffer);
return PhuneRestBase::GetGameDataJsonList(s.c_str(), PACKS_KEY, onResult, onError, userData);
}
<|endoftext|> |
<commit_before>#include "xchainer/python/array.h"
#include <algorithm>
#include <pybind11/numpy.h>
#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
namespace xchainer {
namespace py = pybind11;
Dtype NumpyDtypeToDtype(py::dtype npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
Array MakeArrayFromList(const Shape& shape, Dtype dtype, py::list list) {
auto total_size = shape.total_size();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
auto func = [&](auto dummy) {
using T = decltype(dummy);
std::transform(list.begin(), list.end(), reinterpret_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
};
switch (dtype) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return Array{shape, dtype, ptr};
}
std::unique_ptr<Array> MakeArrayFromNumpyArray(py::array array) {
if (!(array.flags() & py::array::c_style)) {
throw DimensionError("cannot convert non-contiguous NumPy array to Array");
}
// TODO(hvy): When Unified Memory Array creation and its Python binding is in-place, create the Array on the correct device
Dtype dtype = NumpyDtypeToDtype(array.dtype());
py::buffer_info info = array.request();
Shape shape(info.shape);
std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());
return std::make_unique<Array>(shape, dtype, data);
}
void InitXchainerArray(pybind11::module& m) {
py::class_<Array>{m, "Array"}
.def(py::init(&MakeArrayFromList))
.def(py::init(&MakeArrayFromNumpyArray))
.def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
.def_property_readonly("dtype", &Array::dtype)
.def_property_readonly("shape", &Array::shape)
.def_property_readonly("is_contiguous", &Array::is_contiguous)
.def_property_readonly("total_size", &Array::total_size)
.def_property_readonly("element_bytes", &Array::element_bytes)
.def_property_readonly("total_bytes", &Array::total_bytes)
.def_property_readonly("offset", &Array::offset)
.def_property_readonly("debug_flat_data",
[](const Array& self) { // This method is a stub for testing
py::list list;
auto size = self.total_size();
auto func = [&](auto dummy) {
using T = decltype(dummy);
const T& data = *std::static_pointer_cast<const T>(self.data());
for (int64_t i = 0; i < size; ++i) {
list.append((&data)[i]);
}
};
switch (self.dtype()) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return list;
})
.def("__add__", static_cast<Array (Array::*)(const Array&) const>(&Array::Add))
.def("__iadd__", static_cast<Array& (Array::*)(const Array&)>(&Array::IAdd))
.def("__mul__", static_cast<Array (Array::*)(const Array&) const>(&Array::Mul))
.def("__imul__", static_cast<Array& (Array::*)(const Array&)>(&Array::IMul));
}
} // namespace xchainer
<commit_msg>Add pybind comment<commit_after>#include "xchainer/python/array.h"
#include <algorithm>
#include <pybind11/numpy.h>
#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
namespace xchainer {
namespace py = pybind11;
Dtype NumpyDtypeToDtype(py::dtype npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
Array MakeArrayFromList(const Shape& shape, Dtype dtype, py::list list) {
auto total_size = shape.total_size();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
auto func = [&](auto dummy) {
using T = decltype(dummy);
std::transform(list.begin(), list.end(), reinterpret_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
};
switch (dtype) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return Array{shape, dtype, ptr};
}
std::unique_ptr<Array> MakeArrayFromNumpyArray(py::array array) {
if (!(array.flags() & py::array::c_style)) {
throw DimensionError("cannot convert non-contiguous NumPy array to Array");
}
// TODO(hvy): When Unified Memory Array creation and its Python binding is in-place, create the Array on the correct device
Dtype dtype = NumpyDtypeToDtype(array.dtype());
py::buffer_info info = array.request();
Shape shape(info.shape);
// Assuming pybind increases the reference count to the underlying NumPy object, we choose not to copy the data
std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());
return std::make_unique<Array>(shape, dtype, data);
}
void InitXchainerArray(pybind11::module& m) {
py::class_<Array>{m, "Array"}
.def(py::init(&MakeArrayFromList))
.def(py::init(&MakeArrayFromNumpyArray))
.def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
.def_property_readonly("dtype", &Array::dtype)
.def_property_readonly("shape", &Array::shape)
.def_property_readonly("is_contiguous", &Array::is_contiguous)
.def_property_readonly("total_size", &Array::total_size)
.def_property_readonly("element_bytes", &Array::element_bytes)
.def_property_readonly("total_bytes", &Array::total_bytes)
.def_property_readonly("offset", &Array::offset)
.def_property_readonly("debug_flat_data",
[](const Array& self) { // This method is a stub for testing
py::list list;
auto size = self.total_size();
auto func = [&](auto dummy) {
using T = decltype(dummy);
const T& data = *std::static_pointer_cast<const T>(self.data());
for (int64_t i = 0; i < size; ++i) {
list.append((&data)[i]);
}
};
switch (self.dtype()) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return list;
})
.def("__add__", static_cast<Array (Array::*)(const Array&) const>(&Array::Add))
.def("__iadd__", static_cast<Array& (Array::*)(const Array&)>(&Array::IAdd))
.def("__mul__", static_cast<Array (Array::*)(const Array&) const>(&Array::Mul))
.def("__imul__", static_cast<Array& (Array::*)(const Array&)>(&Array::IMul));
}
} // namespace xchainer
<|endoftext|> |
<commit_before>#include "xchainer/python/shape.h"
#include <algorithm>
#include <pybind11/operators.h>
#include "xchainer/shape.h"
#include "xchainer/python/common.h"
namespace xchainer {
namespace py = pybind11;
void InitXchainerShape(pybind11::module& m) {
py::class_<Shape>{m, "Shape"}
.def(py::init([](py::tuple tup) { // __init__ by a tuple
std::vector<int64_t> v;
std::transform(tup.begin(), tup.end(), std::back_inserter(v), [](auto& item) { return py::cast<int64_t>(item); });
return Shape(v);
}))
.def(py::self == py::self) // NOLINT
.def("__eq__", // Equality with a tuple
[](const Shape& self, const py::tuple& tup) {
if (static_cast<size_t>(self.ndim()) != tup.size()) {
return false;
}
try {
return std::equal(self.begin(), self.end(), tup.begin(), tup.end(), [](const auto& dim, const auto& item) {
int64_t dim2 = py::cast<int64_t>(item);
return dim == dim2;
});
} catch (const py::cast_error& e) {
return false;
}
})
.def("__repr__", static_cast<std::string (Shape::*)() const>(&Shape::ToString))
.def_property_readonly("ndim", &Shape::ndim)
.def_property_readonly("total_size", &Shape::GetTotalSize);
py::implicitly_convertible<py::tuple, Shape>();
}
} // namespace xchainer
<commit_msg>xchainer/python/shape.cc:18: Add #include <vector> for vector<> [build/include_what_you_use] [4] xchainer/python/shape.cc:37: Add #include <string> for string [build/include_what_you_use] [4]<commit_after>#include "xchainer/python/shape.h"
#include <algorithm>
#include <string>
#include <vector>
#include <pybind11/operators.h>
#include "xchainer/shape.h"
#include "xchainer/python/common.h"
namespace xchainer {
namespace py = pybind11;
void InitXchainerShape(pybind11::module& m) {
py::class_<Shape>{m, "Shape"}
.def(py::init([](py::tuple tup) { // __init__ by a tuple
std::vector<int64_t> v;
std::transform(tup.begin(), tup.end(), std::back_inserter(v), [](auto& item) { return py::cast<int64_t>(item); });
return Shape(v);
}))
.def(py::self == py::self) // NOLINT
.def("__eq__", // Equality with a tuple
[](const Shape& self, const py::tuple& tup) {
if (static_cast<size_t>(self.ndim()) != tup.size()) {
return false;
}
try {
return std::equal(self.begin(), self.end(), tup.begin(), tup.end(), [](const auto& dim, const auto& item) {
int64_t dim2 = py::cast<int64_t>(item);
return dim == dim2;
});
} catch (const py::cast_error& e) {
return false;
}
})
.def("__repr__", static_cast<std::string (Shape::*)() const>(&Shape::ToString))
.def_property_readonly("ndim", &Shape::ndim)
.def_property_readonly("total_size", &Shape::GetTotalSize);
py::implicitly_convertible<py::tuple, Shape>();
}
} // namespace xchainer
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basefilefind.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/filemanager.h>
#include <find/textfindconstants.h>
#include <find/searchresultwindow.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <utils/stylehelper.h>
#include <QtCore/QDebug>
#include <QtCore/QDirIterator>
#include <QtCore/QSettings>
#include <QtGui/QFileDialog>
#include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTextBlock>
using namespace Utils;
using namespace Find;
using namespace TextEditor;
BaseFileFind::BaseFileFind(SearchResultWindow *resultWindow)
: m_resultWindow(resultWindow),
m_isSearching(false),
m_resultLabel(0),
m_filterCombo(0)
{
m_watcher.setPendingResultsLimit(1);
connect(&m_watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int)));
connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
}
bool BaseFileFind::isEnabled() const
{
return !m_isSearching;
}
bool BaseFileFind::canCancel() const
{
return m_isSearching;
}
void BaseFileFind::cancel()
{
m_watcher.cancel();
}
QStringList BaseFileFind::fileNameFilters() const
{
QStringList filters;
if (m_filterCombo && !m_filterCombo->currentText().isEmpty()) {
const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
foreach (const QString &part, parts) {
const QString filter = part.trimmed();
if (!filter.isEmpty()) {
filters << filter;
}
}
}
return filters;
}
void BaseFileFind::findAll(const QString &txt, Find::FindFlags findFlags)
{
m_isSearching = true;
emit changed();
if (m_filterCombo)
updateComboEntries(m_filterCombo, true);
m_watcher.setFuture(QFuture<FileSearchResultList>());
SearchResult *result = m_resultWindow->startNewSearch();
connect(result, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
m_resultWindow->popup(true);
if (findFlags & Find::FindRegularExpression) {
m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
} else {
m_watcher.setFuture(Utils::findInFiles(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
}
Core::FutureProgress *progress =
Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
"Search",
Constants::TASK_SEARCH);
progress->setWidget(createProgressWidget());
connect(progress, SIGNAL(clicked()), m_resultWindow, SLOT(popup()));
}
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
{
m_isSearching = true;
emit changed();
if (m_filterCombo)
updateComboEntries(m_filterCombo, true);
m_watcher.setFuture(QFuture<FileSearchResultList>());
SearchResult *result = m_resultWindow->startNewSearch(SearchResultWindow::SearchAndReplace);
connect(result, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
connect(result, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
m_resultWindow->popup(true);
if (findFlags & Find::FindRegularExpression) {
m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
} else {
m_watcher.setFuture(Utils::findInFiles(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
}
Core::FutureProgress *progress =
Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
"Search",
Constants::TASK_SEARCH);
progress->setWidget(createProgressWidget());
connect(progress, SIGNAL(clicked()), m_resultWindow, SLOT(popup()));
}
void BaseFileFind::doReplace(const QString &text,
const QList<Find::SearchResultItem> &items)
{
QStringList files = replaceAll(text, items);
Core::FileManager *fileManager = Core::ICore::instance()->fileManager();
if (!files.isEmpty()) {
fileManager->notifyFilesChangedInternally(files);
m_resultWindow->hide();
}
}
void BaseFileFind::displayResult(int index) {
Utils::FileSearchResultList results = m_watcher.future().resultAt(index);
QList<Find::SearchResultItem> items; // this conversion is stupid...
foreach (const Utils::FileSearchResult &result, results) {
Find::SearchResultItem item;
item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
item.lineNumber = result.lineNumber;
item.text = result.matchingLine;
item.textMarkLength = result.matchLength;
item.textMarkPos = result.matchStart;
item.useTextEditorFont = true;
item.userData = result.regexpCapturedTexts;
items << item;
}
m_resultWindow->addResults(items, Find::SearchResultWindow::AddOrdered);
if (m_resultLabel)
m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
}
void BaseFileFind::searchFinished()
{
m_resultWindow->finishSearch();
m_isSearching = false;
m_resultLabel = 0;
emit changed();
}
QWidget *BaseFileFind::createProgressWidget()
{
m_resultLabel = new QLabel;
m_resultLabel->setAlignment(Qt::AlignCenter);
// ### TODO this setup should be done by style
QFont f = m_resultLabel->font();
f.setBold(true);
f.setPointSizeF(StyleHelper::sidebarFontSize());
m_resultLabel->setFont(f);
m_resultLabel->setPalette(StyleHelper::sidebarFontPalette(m_resultLabel->palette()));
m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
return m_resultLabel;
}
QWidget *BaseFileFind::createPatternWidget()
{
QString filterToolTip = tr("List of comma separated wildcard filters");
m_filterCombo = new QComboBox;
m_filterCombo->setEditable(true);
m_filterCombo->setModel(&m_filterStrings);
m_filterCombo->setMaxCount(10);
m_filterCombo->setMinimumContentsLength(10);
m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
m_filterCombo->setInsertPolicy(QComboBox::InsertAtBottom);
m_filterCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
m_filterCombo->setToolTip(filterToolTip);
syncComboWithSettings(m_filterCombo, m_filterSetting);
return m_filterCombo;
}
void BaseFileFind::writeCommonSettings(QSettings *settings)
{
settings->setValue("filters", m_filterStrings.stringList());
if (m_filterCombo)
settings->setValue("currentFilter", m_filterCombo->currentText());
}
void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
QStringList filters = settings->value("filters").toStringList();
m_filterSetting = settings->value("currentFilter").toString();
if (filters.isEmpty())
filters << defaultFilter;
if (m_filterSetting.isEmpty())
m_filterSetting = filters.first();
m_filterStrings.setStringList(filters);
if (m_filterCombo)
syncComboWithSettings(m_filterCombo, m_filterSetting);
}
void BaseFileFind::syncComboWithSettings(QComboBox *combo, const QString &setting)
{
if (!combo)
return;
int index = combo->findText(setting);
if (index < 0)
combo->setEditText(setting);
else
combo->setCurrentIndex(index);
}
void BaseFileFind::updateComboEntries(QComboBox *combo, bool onTop)
{
int index = combo->findText(combo->currentText());
if (index < 0) {
if (onTop) {
combo->insertItem(0, combo->currentText());
} else {
combo->addItem(combo->currentText());
}
combo->setCurrentIndex(combo->findText(combo->currentText()));
}
}
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
{
if (item.path.size() > 0) {
TextEditor::BaseTextEditor::openEditorAt(item.path.first(), item.lineNumber, item.textMarkPos,
QString(), Core::EditorManager::ModeSwitch);
} else {
Core::EditorManager::instance()->openEditor(item.text, QString(), Core::EditorManager::ModeSwitch);
}
}
// #pragma mark Static methods
static void applyChanges(QTextDocument *doc, const QString &text, const QList<Find::SearchResultItem> &items)
{
QList<QPair<QTextCursor, QString> > changes;
foreach (const Find::SearchResultItem &item, items) {
const int blockNumber = item.lineNumber - 1;
QTextCursor tc(doc->findBlockByNumber(blockNumber));
const int cursorPosition = tc.position() + item.textMarkPos;
int cursorIndex = 0;
for (; cursorIndex < changes.size(); ++cursorIndex) {
const QTextCursor &otherTc = changes.at(cursorIndex).first;
if (otherTc.position() == cursorPosition)
break;
}
if (cursorIndex != changes.size())
continue; // skip this change.
tc.setPosition(cursorPosition);
tc.setPosition(tc.position() + item.textMarkLength,
QTextCursor::KeepAnchor);
QString substitutionText;
if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty())
substitutionText = Utils::expandRegExpReplacement(text, item.userData.toStringList());
else
substitutionText = text;
changes.append(QPair<QTextCursor, QString>(tc, substitutionText));
}
for (int i = 0; i < changes.size(); ++i) {
QPair<QTextCursor, QString> &cursor = changes[i];
cursor.first.insertText(cursor.second);
}
}
QStringList BaseFileFind::replaceAll(const QString &text,
const QList<Find::SearchResultItem> &items)
{
if (text.isEmpty() || items.isEmpty())
return QStringList();
QHash<QString, QList<Find::SearchResultItem> > changes;
foreach (const Find::SearchResultItem &item, items)
changes[item.path.first()].append(item);
Core::EditorManager *editorManager = Core::EditorManager::instance();
QHashIterator<QString, QList<Find::SearchResultItem> > it(changes);
while (it.hasNext()) {
it.next();
const QString fileName = it.key();
const QList<Find::SearchResultItem> changeItems = it.value();
const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName);
TextEditor::BaseTextEditor *textEditor = 0;
foreach (Core::IEditor *editor, editors) {
textEditor = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
if (textEditor != 0)
break;
}
if (textEditor != 0) {
QTextCursor tc = textEditor->textCursor();
tc.beginEditBlock();
applyChanges(textEditor->document(), text, changeItems);
tc.endEditBlock();
} else {
QFile file(fileName);
if (file.open(QFile::ReadOnly)) {
QTextStream stream(&file);
// ### set the encoding
const QString plainText = stream.readAll();
file.close();
QTextDocument doc;
doc.setPlainText(plainText);
applyChanges(&doc, text, changeItems);
QFile newFile(fileName);
if (newFile.open(QFile::WriteOnly)) {
QTextStream stream(&newFile);
// ### set the encoding
stream << doc.toPlainText();
}
}
}
}
return changes.keys();
}
<commit_msg>Open files from search result list with right encoding, even on Windows.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basefilefind.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/filemanager.h>
#include <find/textfindconstants.h>
#include <find/searchresultwindow.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <utils/stylehelper.h>
#include <QtCore/QDebug>
#include <QtCore/QDirIterator>
#include <QtCore/QSettings>
#include <QtGui/QFileDialog>
#include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTextBlock>
using namespace Utils;
using namespace Find;
using namespace TextEditor;
BaseFileFind::BaseFileFind(SearchResultWindow *resultWindow)
: m_resultWindow(resultWindow),
m_isSearching(false),
m_resultLabel(0),
m_filterCombo(0)
{
m_watcher.setPendingResultsLimit(1);
connect(&m_watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int)));
connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
}
bool BaseFileFind::isEnabled() const
{
return !m_isSearching;
}
bool BaseFileFind::canCancel() const
{
return m_isSearching;
}
void BaseFileFind::cancel()
{
m_watcher.cancel();
}
QStringList BaseFileFind::fileNameFilters() const
{
QStringList filters;
if (m_filterCombo && !m_filterCombo->currentText().isEmpty()) {
const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
foreach (const QString &part, parts) {
const QString filter = part.trimmed();
if (!filter.isEmpty()) {
filters << filter;
}
}
}
return filters;
}
void BaseFileFind::findAll(const QString &txt, Find::FindFlags findFlags)
{
m_isSearching = true;
emit changed();
if (m_filterCombo)
updateComboEntries(m_filterCombo, true);
m_watcher.setFuture(QFuture<FileSearchResultList>());
SearchResult *result = m_resultWindow->startNewSearch();
connect(result, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
m_resultWindow->popup(true);
if (findFlags & Find::FindRegularExpression) {
m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
} else {
m_watcher.setFuture(Utils::findInFiles(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
}
Core::FutureProgress *progress =
Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
"Search",
Constants::TASK_SEARCH);
progress->setWidget(createProgressWidget());
connect(progress, SIGNAL(clicked()), m_resultWindow, SLOT(popup()));
}
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
{
m_isSearching = true;
emit changed();
if (m_filterCombo)
updateComboEntries(m_filterCombo, true);
m_watcher.setFuture(QFuture<FileSearchResultList>());
SearchResult *result = m_resultWindow->startNewSearch(SearchResultWindow::SearchAndReplace);
connect(result, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
connect(result, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
m_resultWindow->popup(true);
if (findFlags & Find::FindRegularExpression) {
m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
} else {
m_watcher.setFuture(Utils::findInFiles(txt, files(),
textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
}
Core::FutureProgress *progress =
Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
"Search",
Constants::TASK_SEARCH);
progress->setWidget(createProgressWidget());
connect(progress, SIGNAL(clicked()), m_resultWindow, SLOT(popup()));
}
void BaseFileFind::doReplace(const QString &text,
const QList<Find::SearchResultItem> &items)
{
QStringList files = replaceAll(text, items);
Core::FileManager *fileManager = Core::ICore::instance()->fileManager();
if (!files.isEmpty()) {
fileManager->notifyFilesChangedInternally(files);
m_resultWindow->hide();
}
}
void BaseFileFind::displayResult(int index) {
Utils::FileSearchResultList results = m_watcher.future().resultAt(index);
QList<Find::SearchResultItem> items; // this conversion is stupid...
foreach (const Utils::FileSearchResult &result, results) {
Find::SearchResultItem item;
item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
item.lineNumber = result.lineNumber;
item.text = result.matchingLine;
item.textMarkLength = result.matchLength;
item.textMarkPos = result.matchStart;
item.useTextEditorFont = true;
item.userData = result.regexpCapturedTexts;
items << item;
}
m_resultWindow->addResults(items, Find::SearchResultWindow::AddOrdered);
if (m_resultLabel)
m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
}
void BaseFileFind::searchFinished()
{
m_resultWindow->finishSearch();
m_isSearching = false;
m_resultLabel = 0;
emit changed();
}
QWidget *BaseFileFind::createProgressWidget()
{
m_resultLabel = new QLabel;
m_resultLabel->setAlignment(Qt::AlignCenter);
// ### TODO this setup should be done by style
QFont f = m_resultLabel->font();
f.setBold(true);
f.setPointSizeF(StyleHelper::sidebarFontSize());
m_resultLabel->setFont(f);
m_resultLabel->setPalette(StyleHelper::sidebarFontPalette(m_resultLabel->palette()));
m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
return m_resultLabel;
}
QWidget *BaseFileFind::createPatternWidget()
{
QString filterToolTip = tr("List of comma separated wildcard filters");
m_filterCombo = new QComboBox;
m_filterCombo->setEditable(true);
m_filterCombo->setModel(&m_filterStrings);
m_filterCombo->setMaxCount(10);
m_filterCombo->setMinimumContentsLength(10);
m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
m_filterCombo->setInsertPolicy(QComboBox::InsertAtBottom);
m_filterCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
m_filterCombo->setToolTip(filterToolTip);
syncComboWithSettings(m_filterCombo, m_filterSetting);
return m_filterCombo;
}
void BaseFileFind::writeCommonSettings(QSettings *settings)
{
settings->setValue("filters", m_filterStrings.stringList());
if (m_filterCombo)
settings->setValue("currentFilter", m_filterCombo->currentText());
}
void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
QStringList filters = settings->value("filters").toStringList();
m_filterSetting = settings->value("currentFilter").toString();
if (filters.isEmpty())
filters << defaultFilter;
if (m_filterSetting.isEmpty())
m_filterSetting = filters.first();
m_filterStrings.setStringList(filters);
if (m_filterCombo)
syncComboWithSettings(m_filterCombo, m_filterSetting);
}
void BaseFileFind::syncComboWithSettings(QComboBox *combo, const QString &setting)
{
if (!combo)
return;
int index = combo->findText(setting);
if (index < 0)
combo->setEditText(setting);
else
combo->setCurrentIndex(index);
}
void BaseFileFind::updateComboEntries(QComboBox *combo, bool onTop)
{
int index = combo->findText(combo->currentText());
if (index < 0) {
if (onTop) {
combo->insertItem(0, combo->currentText());
} else {
combo->addItem(combo->currentText());
}
combo->setCurrentIndex(combo->findText(combo->currentText()));
}
}
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
{
if (item.path.size() > 0) {
TextEditor::BaseTextEditor::openEditorAt(QDir::fromNativeSeparators(item.path.first()), item.lineNumber, item.textMarkPos,
QString(), Core::EditorManager::ModeSwitch);
} else {
Core::EditorManager::instance()->openEditor(item.text, QString(), Core::EditorManager::ModeSwitch);
}
}
// #pragma mark Static methods
static void applyChanges(QTextDocument *doc, const QString &text, const QList<Find::SearchResultItem> &items)
{
QList<QPair<QTextCursor, QString> > changes;
foreach (const Find::SearchResultItem &item, items) {
const int blockNumber = item.lineNumber - 1;
QTextCursor tc(doc->findBlockByNumber(blockNumber));
const int cursorPosition = tc.position() + item.textMarkPos;
int cursorIndex = 0;
for (; cursorIndex < changes.size(); ++cursorIndex) {
const QTextCursor &otherTc = changes.at(cursorIndex).first;
if (otherTc.position() == cursorPosition)
break;
}
if (cursorIndex != changes.size())
continue; // skip this change.
tc.setPosition(cursorPosition);
tc.setPosition(tc.position() + item.textMarkLength,
QTextCursor::KeepAnchor);
QString substitutionText;
if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty())
substitutionText = Utils::expandRegExpReplacement(text, item.userData.toStringList());
else
substitutionText = text;
changes.append(QPair<QTextCursor, QString>(tc, substitutionText));
}
for (int i = 0; i < changes.size(); ++i) {
QPair<QTextCursor, QString> &cursor = changes[i];
cursor.first.insertText(cursor.second);
}
}
QStringList BaseFileFind::replaceAll(const QString &text,
const QList<Find::SearchResultItem> &items)
{
if (text.isEmpty() || items.isEmpty())
return QStringList();
QHash<QString, QList<Find::SearchResultItem> > changes;
foreach (const Find::SearchResultItem &item, items)
changes[QDir::fromNativeSeparators(item.path.first())].append(item);
Core::EditorManager *editorManager = Core::EditorManager::instance();
QHashIterator<QString, QList<Find::SearchResultItem> > it(changes);
while (it.hasNext()) {
it.next();
const QString fileName = it.key();
const QList<Find::SearchResultItem> changeItems = it.value();
const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName);
TextEditor::BaseTextEditor *textEditor = 0;
foreach (Core::IEditor *editor, editors) {
textEditor = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
if (textEditor != 0)
break;
}
if (textEditor != 0) {
QTextCursor tc = textEditor->textCursor();
tc.beginEditBlock();
applyChanges(textEditor->document(), text, changeItems);
tc.endEditBlock();
} else {
QFile file(fileName);
if (file.open(QFile::ReadOnly)) {
QTextStream stream(&file);
// ### set the encoding
const QString plainText = stream.readAll();
file.close();
QTextDocument doc;
doc.setPlainText(plainText);
applyChanges(&doc, text, changeItems);
QFile newFile(fileName);
if (newFile.open(QFile::WriteOnly)) {
QTextStream stream(&newFile);
// ### set the encoding
stream << doc.toPlainText();
}
}
}
}
return changes.keys();
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// XFAIL: c++03
// <system_error>
// class error_code
// explicit operator bool() const;
#include <system_error>
bool test_func(void)
{
const std::error_code ec(0, std::generic_category());
return ec; // conversion to bool is explicit; should fail.
}
int main()
{
return 0;
}
<commit_msg>Extend XFAIL to c++98.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// XFAIL: c++98, c++03
// <system_error>
// class error_code
// explicit operator bool() const;
#include <system_error>
bool test_func(void)
{
const std::error_code ec(0, std::generic_category());
return ec; // conversion to bool is explicit; should fail.
}
int main()
{
return 0;
}
<|endoftext|> |
<commit_before>// Infra.
#include <AMDTBaseTools/Include/gtString.h>
#include <AMDTOSWrappers/Include/osFilePath.h>
#include <AMDTOSWrappers/Include/osFile.h>
#include <AMDTOSWrappers/Include/osDirectory.h>
// Backend.
#include <RadeonGPUAnalyzerBackend/include/beStaticIsaAnalyzer.h>
// Local.
#include <RadeonGPUAnalyzerCLI/src/kcUtils.h>
#include <RadeonGPUAnalyzerCLI/src/kcCliStringConstants.h>
#include <RadeonGPUAnalyzerCLI/src/kcCLICommander.h>
using namespace beKA;
bool kcUtils::ValidateShaderFileName(const char* shaderType, const std::string& shaderFileName, std::stringstream& logMsg)
{
bool isShaderNameValid = true;
gtString shaderFileNameAsGtStr;
shaderFileNameAsGtStr << shaderFileName.c_str();
osFilePath shaderFile(shaderFileNameAsGtStr);
if (!shaderFile.exists())
{
isShaderNameValid = false;
logMsg << STR_ERR_CANNOT_FIND_SHADER_PREFIX << shaderType << STR_ERR_CANNOT_FIND_SHADER_SUFFIX << shaderFileName << std::endl;
}
return isShaderNameValid;
}
bool kcUtils::ValidateShaderOutputDir(const std::string& outputFileName, std::stringstream& logMsg)
{
bool isShaderOutputDirValid = true;
gtString shaderFileNameAsGtStr;
shaderFileNameAsGtStr << outputFileName.c_str();
osFilePath shaderFile(shaderFileNameAsGtStr);
osDirectory outputDir;
shaderFile.getFileDirectory(outputDir);
if(outputDir.IsEmpty())
{
// If the directory is empty then we assume the output directory is the active directory which should exist.
return true;
}
isShaderOutputDirValid = outputDir.exists();
if (!isShaderOutputDirValid)
{
logMsg << STR_ERR_CANNOT_FIND_OUTPUT_DIR << outputDir.directoryPath().asString().asASCIICharArray() << std::endl;
}
return isShaderOutputDirValid;
}
void kcUtils::AdjustRenderingPipelineOutputFileNames(const std::string& baseOutputFileName, const std::string& device, beProgramPipeline& pipelineFiles)
{
// Clear the existing pipeline.
pipelineFiles.ClearAll();
// Isolate the original file name.
gtString outputFileAsGtStr;
outputFileAsGtStr << baseOutputFileName.c_str();
osFilePath outputFilePath(outputFileAsGtStr);
// Directory.
osDirectory outputDir;
outputFilePath.getFileDirectory(outputDir);
// File name.
gtString originalFileName;
outputFilePath.getFileName(originalFileName);
// File extension.
gtString originalFileExtension;
outputFilePath.getFileExtension(originalFileExtension);
// Make the adjustments.
gtString fixedFileName;
fixedFileName << outputDir.directoryPath().asString(true) << device.c_str() << "_";
pipelineFiles.m_vertexShader << fixedFileName << KA_CLI_STR_VERTEX_ABBREVIATION;
pipelineFiles.m_tessControlShader << fixedFileName << KA_CLI_STR_TESS_CTRL_ABBREVIATION;
pipelineFiles.m_tessEvaluationShader << fixedFileName << KA_CLI_STR_TESS_EVAL_ABBREVIATION;
pipelineFiles.m_geometryShader << fixedFileName << KA_CLI_STR_GEOMETRY_ABBREVIATION;
pipelineFiles.m_fragmentShader << fixedFileName << KA_CLI_STR_FRAGMENT_ABBREVIATION;
pipelineFiles.m_computeShader << fixedFileName << KA_CLI_STR_COMPUTE_ABBREVIATION;
if (!originalFileName.isEmpty())
{
pipelineFiles.m_vertexShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_tessControlShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_tessEvaluationShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_geometryShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_fragmentShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_computeShader << "_" << originalFileName.asASCIICharArray();
}
if (!originalFileExtension.isEmpty())
{
pipelineFiles.m_vertexShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_tessControlShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_tessEvaluationShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_geometryShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_fragmentShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_computeShader << "." << originalFileExtension.asASCIICharArray();
}
}
std::string kcUtils::DeviceStatisticsToCsvString(const Config& config, const std::string& device, const beKA::AnalysisData& statistics)
{
std::stringstream output;
// Device name.
char csvSeparator = GetCsvSeparator(config);
output << device << csvSeparator;
// Scratch registers.
output << statistics.maxScratchRegsNeeded << csvSeparator;
// Work-items per work-group.
output << statistics.numThreadPerGroup << csvSeparator;
// Wavefront size.
output << statistics.wavefrontSize << csvSeparator;
// LDS available bytes.
output << statistics.LDSSizeAvailable << csvSeparator;
// LDS actual bytes.
output << statistics.LDSSizeUsed << csvSeparator;
// Available SGPRs.
output << statistics.numSGPRsAvailable << csvSeparator;
// Used SGPRs.
output << statistics.numSGPRsUsed << csvSeparator;
// Available VGPRs.
output << statistics.numVGPRsAvailable << csvSeparator;
// Used VGPRs.
output << statistics.numVGPRsUsed << csvSeparator;
// CL Work-group dimensions (for a unified format, to be revisited).
output << statistics.numThreadPerGroupX << csvSeparator;
output << statistics.numThreadPerGroupY << csvSeparator;
output << statistics.numThreadPerGroupZ << csvSeparator;
// ISA size.
output << statistics.ISASize;
output << std::endl;
return output.str().c_str();
}
bool kcUtils::CreateStatisticsFile(const gtString& fileName, const Config& config,
const std::map<std::string, beKA::AnalysisData>& analysisData, LoggingCallBackFunc_t pLogCallback)
{
bool ret = false;
// Get the separator for CSV list items.
char csvSeparator = GetCsvSeparator(config);
// Open output file.
std::ofstream output;
output.open(fileName.asASCIICharArray());
if (output.is_open())
{
// Write the header.
output << GetStatisticsCsvHeaderString(csvSeparator) << std::endl;
// Write the device data.
for (const auto& deviceStatsPair : analysisData)
{
// Write a line of CSV.
output << DeviceStatisticsToCsvString(config, deviceStatsPair.first, deviceStatsPair.second);
}
output.close();
ret = true;
}
else if (pLogCallback != nullptr)
{
std::stringstream s_Log;
s_Log << STR_ERR_CANNOT_OPEN_FILE_FOR_WRITE_A << fileName.asASCIICharArray() <<
STR_ERR_CANNOT_OPEN_FILE_FOR_WRITE_B << std::endl;
pLogCallback(s_Log.str());
}
return ret;
}
std::string kcUtils::GetStatisticsCsvHeaderString(char csvSeparator)
{
std::stringstream output;
output << STR_CSV_HEADER_DEVICE << csvSeparator;
output << STR_CSV_HEADER_SCRATCH_REGS << csvSeparator;
output << STR_CSV_HEADER_THREADS_PER_WG << csvSeparator;
output << STR_CSV_HEADER_WAVEFRONT_SIZE << csvSeparator;
output << STR_CSV_HEADER_LDS_BYTES_MAX << csvSeparator;
output << STR_CSV_HEADER_LDS_BYTES_ACTUAL << csvSeparator;
output << STR_CSV_HEADER_SGPR_AVAILABLE << csvSeparator;
output << STR_CSV_HEADER_SGPR_USED << csvSeparator;
output << STR_CSV_HEADER_VGPR_AVAILABLE << csvSeparator;
output << STR_CSV_HEADER_VGPR_USED << csvSeparator;
output << STR_CSV_HEADER_CL_WORKGROUP_DIM_X << csvSeparator;
output << STR_CSV_HEADER_CL_WORKGROUP_DIM_Y << csvSeparator;
output << STR_CSV_HEADER_CL_WORKGROUP_DIM_Z << csvSeparator;
output << STR_CSV_HEADER_ISA_SIZE_BYTES;
return output.str().c_str();
}
void kcUtils::CreateStatisticsFile(const gtString& fileName, const Config& config, const std::string& device,
const beKA::AnalysisData& deviceStatistics, LoggingCallBackFunc_t pLogCallback)
{
// Create a temporary map and invoke the general routine.
std::map<std::string, beKA::AnalysisData> tmpMap;
tmpMap[device] = deviceStatistics;
CreateStatisticsFile(fileName, config, tmpMap, pLogCallback);
}
char kcUtils::GetCsvSeparator(const Config& config)
{
char csvSeparator;
if (!config.m_CSVSeparator.empty())
{
csvSeparator = config.m_CSVSeparator[0];
if (config.m_CSVSeparator[0] == '\\' && config.m_CSVSeparator.size() > 1)
{
switch (config.m_CSVSeparator[1])
{
case 'a': csvSeparator = '\a'; break;
case 'b': csvSeparator = '\b'; break;
case 'f': csvSeparator = '\f'; break;
case 'n': csvSeparator = '\n'; break;
case 'r': csvSeparator = '\r'; break;
case 't': csvSeparator = '\t'; break;
case 'v': csvSeparator = '\v'; break;
default:
csvSeparator = config.m_CSVSeparator[1];
break;
}
}
}
else
{
// The default separator.
csvSeparator = ',';
}
return csvSeparator;
}
bool kcUtils::DeleteFile(const gtString& fileFullPath)
{
bool ret = false;
osFilePath path(fileFullPath);
if (path.exists())
{
osFile file(path);
ret = file.deleteFile();
}
return ret;
}
void kcUtils::ReplaceStatisticsFile(const gtString& statisticsFile, const Config& config,
const std::string& device, IStatisticsParser& statsParser, LoggingCallBackFunc_t logCb)
{
// Parse the backend statistics.
beKA::AnalysisData statistics;
statsParser.ParseStatistics(statisticsFile, statistics);
// Delete the older statistics file.
kcUtils::DeleteFile(statisticsFile);
// Create a new statistics file in the CLI format.
kcUtils::CreateStatisticsFile(statisticsFile, config, device, statistics, logCb);
}
void kcUtils::PerformLiveRegisterAnalysis(const gtString& isaFileName,
const gtString& outputFileName, LoggingCallBackFunc_t pCallback)
{
// Call the backend.
beStatus rc = beStaticIsaAnalyzer::PerformLiveRegisterAnalysis(isaFileName, outputFileName);
if (rc != beStatus_SUCCESS && pCallback != nullptr)
{
// Inform the user in case of an error.
std::stringstream msg;
switch (rc)
{
case beKA::beStatus_shaeCannotLocateAnalyzer:
// Failed to locate the ISA analyzer.
msg << STR_ERR_CANNOT_LOCATE_LIVE_REG_ANALYZER << std::endl;
break;
case beKA::beStatus_shaeIsaFileNotFound:
// ISA file not found.
msg << STR_ERR_CANNOT_FIND_ISA_FILE << std::endl;
break;
case beKA::beStatus_shaeFailedToLaunch:
#ifndef __linux__
// Failed to launch the ISA analyzer.
// On Linux, there is an issue with this return code due to the
// executable format that we use for the backend.
msg << STR_ERR_CANNOT_LAUNCH_LIVE_REG_ANALYZER << std::endl;
#endif
break;
case beKA::beStatus_General_FAILED:
default:
// Generic error message.
msg << STR_ERR_CANNOT_PERFORM_LIVE_REG_ANALYSIS << std::endl;
break;
}
const std::string& errMsg = msg.str();
if (!errMsg.empty() && pCallback != nullptr)
{
pCallback(errMsg);
}
}
}
void kcUtils::GenerateControlFlowGraph(const gtString& isaFileName, const gtString& outputFileName, LoggingCallBackFunc_t pCallback)
{
// Call the backend.
beStatus rc = beStaticIsaAnalyzer::GenerateControlFlowGraph(isaFileName, outputFileName);
if (rc != beStatus_SUCCESS && pCallback != nullptr)
{
// Inform the user in case of an error.
std::stringstream msg;
switch (rc)
{
case beKA::beStatus_shaeCannotLocateAnalyzer:
// Failed to locate the ISA analyzer.
msg << STR_ERR_CANNOT_LOCATE_LIVE_REG_ANALYZER << std::endl;
break;
case beKA::beStatus_shaeIsaFileNotFound:
// ISA file not found.
msg << STR_ERR_CANNOT_FIND_ISA_FILE << std::endl;
break;
case beKA::beStatus_shaeFailedToLaunch:
// Failed to launch the ISA analyzer.
msg << STR_ERR_CANNOT_LAUNCH_CFG_ANALYZER << std::endl;
break;
case beKA::beStatus_General_FAILED:
default:
// Generic error message.
msg << STR_ERR_CANNOT_PERFORM_LIVE_REG_ANALYSIS << std::endl;
break;
}
const std::string& errMsg = msg.str();
if (!errMsg.empty() && pCallback != nullptr)
{
pCallback(errMsg);
}
}
}
void kcUtils::ConstructOutputFileName(const std::string& baseOutputFileName, const std::string& defaultExtension, const std::string& kernelName, const std::string& deviceName, gtString& generatedFileName)
{
// Convert the base output file name to gtString.
gtString baseOutputFileNameAsGtStr;
baseOutputFileNameAsGtStr << baseOutputFileName.c_str();
osFilePath outputFilePath(baseOutputFileNameAsGtStr);
// Extract the user's file name and extension.
gtString fileName;
if (!outputFilePath.isDirectory())
{
outputFilePath.getFileName(fileName);
}
else
{
osDirectory outputDir(baseOutputFileNameAsGtStr);
outputFilePath.setFileDirectory(outputDir);
}
// Fix the user's file name to generate a unique output file name in the Analyzer CLI format.
gtString fixedFileName;
fixedFileName << deviceName.c_str();
if (!kernelName.empty())
{
if (!fixedFileName.isEmpty())
{
fixedFileName << "_";
}
fixedFileName << kernelName.c_str();
}
if (!fileName.isEmpty())
{
if (!fixedFileName.isEmpty())
{
fixedFileName << "_";
}
fixedFileName << fileName;
}
outputFilePath.setFileName(fixedFileName);
// Handle the default extension (unless the user specified an extension).
gtString outputFileExtension;
outputFilePath.getFileExtension(outputFileExtension);
if (outputFileExtension.isEmpty())
{
outputFileExtension.fromASCIIString(defaultExtension.c_str());
outputFilePath.setFileExtension(outputFileExtension);
}
// Set the output string.
generatedFileName = outputFilePath.asString();
}
kcUtils::kcUtils()
{
}
kcUtils::~kcUtils()
{
}
<commit_msg>Fix check for empty directory string.<commit_after>// Infra.
#include <AMDTBaseTools/Include/gtString.h>
#include <AMDTOSWrappers/Include/osFilePath.h>
#include <AMDTOSWrappers/Include/osFile.h>
#include <AMDTOSWrappers/Include/osDirectory.h>
// Backend.
#include <RadeonGPUAnalyzerBackend/include/beStaticIsaAnalyzer.h>
// Local.
#include <RadeonGPUAnalyzerCLI/src/kcUtils.h>
#include <RadeonGPUAnalyzerCLI/src/kcCliStringConstants.h>
#include <RadeonGPUAnalyzerCLI/src/kcCLICommander.h>
using namespace beKA;
bool kcUtils::ValidateShaderFileName(const char* shaderType, const std::string& shaderFileName, std::stringstream& logMsg)
{
bool isShaderNameValid = true;
gtString shaderFileNameAsGtStr;
shaderFileNameAsGtStr << shaderFileName.c_str();
osFilePath shaderFile(shaderFileNameAsGtStr);
if (!shaderFile.exists())
{
isShaderNameValid = false;
logMsg << STR_ERR_CANNOT_FIND_SHADER_PREFIX << shaderType << STR_ERR_CANNOT_FIND_SHADER_SUFFIX << shaderFileName << std::endl;
}
return isShaderNameValid;
}
bool kcUtils::ValidateShaderOutputDir(const std::string& outputFileName, std::stringstream& logMsg)
{
bool isShaderOutputDirValid = true;
gtString shaderFileNameAsGtStr;
shaderFileNameAsGtStr << outputFileName.c_str();
osFilePath shaderFile(shaderFileNameAsGtStr);
osDirectory outputDir;
shaderFile.getFileDirectory(outputDir);
// If the directory is empty then we assume the output directory is the active directory which should exist.
isShaderOutputDirValid = outputDir.asString().isEmpty() || outputDir.exists();
if (!isShaderOutputDirValid)
{
logMsg << STR_ERR_CANNOT_FIND_OUTPUT_DIR << outputDir.directoryPath().asString().asASCIICharArray() << std::endl;
}
return isShaderOutputDirValid;
}
void kcUtils::AdjustRenderingPipelineOutputFileNames(const std::string& baseOutputFileName, const std::string& device, beProgramPipeline& pipelineFiles)
{
// Clear the existing pipeline.
pipelineFiles.ClearAll();
// Isolate the original file name.
gtString outputFileAsGtStr;
outputFileAsGtStr << baseOutputFileName.c_str();
osFilePath outputFilePath(outputFileAsGtStr);
// Directory.
osDirectory outputDir;
outputFilePath.getFileDirectory(outputDir);
// File name.
gtString originalFileName;
outputFilePath.getFileName(originalFileName);
// File extension.
gtString originalFileExtension;
outputFilePath.getFileExtension(originalFileExtension);
// Make the adjustments.
gtString fixedFileName;
fixedFileName << outputDir.directoryPath().asString(true) << device.c_str() << "_";
pipelineFiles.m_vertexShader << fixedFileName << KA_CLI_STR_VERTEX_ABBREVIATION;
pipelineFiles.m_tessControlShader << fixedFileName << KA_CLI_STR_TESS_CTRL_ABBREVIATION;
pipelineFiles.m_tessEvaluationShader << fixedFileName << KA_CLI_STR_TESS_EVAL_ABBREVIATION;
pipelineFiles.m_geometryShader << fixedFileName << KA_CLI_STR_GEOMETRY_ABBREVIATION;
pipelineFiles.m_fragmentShader << fixedFileName << KA_CLI_STR_FRAGMENT_ABBREVIATION;
pipelineFiles.m_computeShader << fixedFileName << KA_CLI_STR_COMPUTE_ABBREVIATION;
if (!originalFileName.isEmpty())
{
pipelineFiles.m_vertexShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_tessControlShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_tessEvaluationShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_geometryShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_fragmentShader << "_" << originalFileName.asASCIICharArray();
pipelineFiles.m_computeShader << "_" << originalFileName.asASCIICharArray();
}
if (!originalFileExtension.isEmpty())
{
pipelineFiles.m_vertexShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_tessControlShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_tessEvaluationShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_geometryShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_fragmentShader << "." << originalFileExtension.asASCIICharArray();
pipelineFiles.m_computeShader << "." << originalFileExtension.asASCIICharArray();
}
}
std::string kcUtils::DeviceStatisticsToCsvString(const Config& config, const std::string& device, const beKA::AnalysisData& statistics)
{
std::stringstream output;
// Device name.
char csvSeparator = GetCsvSeparator(config);
output << device << csvSeparator;
// Scratch registers.
output << statistics.maxScratchRegsNeeded << csvSeparator;
// Work-items per work-group.
output << statistics.numThreadPerGroup << csvSeparator;
// Wavefront size.
output << statistics.wavefrontSize << csvSeparator;
// LDS available bytes.
output << statistics.LDSSizeAvailable << csvSeparator;
// LDS actual bytes.
output << statistics.LDSSizeUsed << csvSeparator;
// Available SGPRs.
output << statistics.numSGPRsAvailable << csvSeparator;
// Used SGPRs.
output << statistics.numSGPRsUsed << csvSeparator;
// Available VGPRs.
output << statistics.numVGPRsAvailable << csvSeparator;
// Used VGPRs.
output << statistics.numVGPRsUsed << csvSeparator;
// CL Work-group dimensions (for a unified format, to be revisited).
output << statistics.numThreadPerGroupX << csvSeparator;
output << statistics.numThreadPerGroupY << csvSeparator;
output << statistics.numThreadPerGroupZ << csvSeparator;
// ISA size.
output << statistics.ISASize;
output << std::endl;
return output.str().c_str();
}
bool kcUtils::CreateStatisticsFile(const gtString& fileName, const Config& config,
const std::map<std::string, beKA::AnalysisData>& analysisData, LoggingCallBackFunc_t pLogCallback)
{
bool ret = false;
// Get the separator for CSV list items.
char csvSeparator = GetCsvSeparator(config);
// Open output file.
std::ofstream output;
output.open(fileName.asASCIICharArray());
if (output.is_open())
{
// Write the header.
output << GetStatisticsCsvHeaderString(csvSeparator) << std::endl;
// Write the device data.
for (const auto& deviceStatsPair : analysisData)
{
// Write a line of CSV.
output << DeviceStatisticsToCsvString(config, deviceStatsPair.first, deviceStatsPair.second);
}
output.close();
ret = true;
}
else if (pLogCallback != nullptr)
{
std::stringstream s_Log;
s_Log << STR_ERR_CANNOT_OPEN_FILE_FOR_WRITE_A << fileName.asASCIICharArray() <<
STR_ERR_CANNOT_OPEN_FILE_FOR_WRITE_B << std::endl;
pLogCallback(s_Log.str());
}
return ret;
}
std::string kcUtils::GetStatisticsCsvHeaderString(char csvSeparator)
{
std::stringstream output;
output << STR_CSV_HEADER_DEVICE << csvSeparator;
output << STR_CSV_HEADER_SCRATCH_REGS << csvSeparator;
output << STR_CSV_HEADER_THREADS_PER_WG << csvSeparator;
output << STR_CSV_HEADER_WAVEFRONT_SIZE << csvSeparator;
output << STR_CSV_HEADER_LDS_BYTES_MAX << csvSeparator;
output << STR_CSV_HEADER_LDS_BYTES_ACTUAL << csvSeparator;
output << STR_CSV_HEADER_SGPR_AVAILABLE << csvSeparator;
output << STR_CSV_HEADER_SGPR_USED << csvSeparator;
output << STR_CSV_HEADER_VGPR_AVAILABLE << csvSeparator;
output << STR_CSV_HEADER_VGPR_USED << csvSeparator;
output << STR_CSV_HEADER_CL_WORKGROUP_DIM_X << csvSeparator;
output << STR_CSV_HEADER_CL_WORKGROUP_DIM_Y << csvSeparator;
output << STR_CSV_HEADER_CL_WORKGROUP_DIM_Z << csvSeparator;
output << STR_CSV_HEADER_ISA_SIZE_BYTES;
return output.str().c_str();
}
void kcUtils::CreateStatisticsFile(const gtString& fileName, const Config& config, const std::string& device,
const beKA::AnalysisData& deviceStatistics, LoggingCallBackFunc_t pLogCallback)
{
// Create a temporary map and invoke the general routine.
std::map<std::string, beKA::AnalysisData> tmpMap;
tmpMap[device] = deviceStatistics;
CreateStatisticsFile(fileName, config, tmpMap, pLogCallback);
}
char kcUtils::GetCsvSeparator(const Config& config)
{
char csvSeparator;
if (!config.m_CSVSeparator.empty())
{
csvSeparator = config.m_CSVSeparator[0];
if (config.m_CSVSeparator[0] == '\\' && config.m_CSVSeparator.size() > 1)
{
switch (config.m_CSVSeparator[1])
{
case 'a': csvSeparator = '\a'; break;
case 'b': csvSeparator = '\b'; break;
case 'f': csvSeparator = '\f'; break;
case 'n': csvSeparator = '\n'; break;
case 'r': csvSeparator = '\r'; break;
case 't': csvSeparator = '\t'; break;
case 'v': csvSeparator = '\v'; break;
default:
csvSeparator = config.m_CSVSeparator[1];
break;
}
}
}
else
{
// The default separator.
csvSeparator = ',';
}
return csvSeparator;
}
bool kcUtils::DeleteFile(const gtString& fileFullPath)
{
bool ret = false;
osFilePath path(fileFullPath);
if (path.exists())
{
osFile file(path);
ret = file.deleteFile();
}
return ret;
}
void kcUtils::ReplaceStatisticsFile(const gtString& statisticsFile, const Config& config,
const std::string& device, IStatisticsParser& statsParser, LoggingCallBackFunc_t logCb)
{
// Parse the backend statistics.
beKA::AnalysisData statistics;
statsParser.ParseStatistics(statisticsFile, statistics);
// Delete the older statistics file.
kcUtils::DeleteFile(statisticsFile);
// Create a new statistics file in the CLI format.
kcUtils::CreateStatisticsFile(statisticsFile, config, device, statistics, logCb);
}
void kcUtils::PerformLiveRegisterAnalysis(const gtString& isaFileName,
const gtString& outputFileName, LoggingCallBackFunc_t pCallback)
{
// Call the backend.
beStatus rc = beStaticIsaAnalyzer::PerformLiveRegisterAnalysis(isaFileName, outputFileName);
if (rc != beStatus_SUCCESS && pCallback != nullptr)
{
// Inform the user in case of an error.
std::stringstream msg;
switch (rc)
{
case beKA::beStatus_shaeCannotLocateAnalyzer:
// Failed to locate the ISA analyzer.
msg << STR_ERR_CANNOT_LOCATE_LIVE_REG_ANALYZER << std::endl;
break;
case beKA::beStatus_shaeIsaFileNotFound:
// ISA file not found.
msg << STR_ERR_CANNOT_FIND_ISA_FILE << std::endl;
break;
case beKA::beStatus_shaeFailedToLaunch:
#ifndef __linux__
// Failed to launch the ISA analyzer.
// On Linux, there is an issue with this return code due to the
// executable format that we use for the backend.
msg << STR_ERR_CANNOT_LAUNCH_LIVE_REG_ANALYZER << std::endl;
#endif
break;
case beKA::beStatus_General_FAILED:
default:
// Generic error message.
msg << STR_ERR_CANNOT_PERFORM_LIVE_REG_ANALYSIS << std::endl;
break;
}
const std::string& errMsg = msg.str();
if (!errMsg.empty() && pCallback != nullptr)
{
pCallback(errMsg);
}
}
}
void kcUtils::GenerateControlFlowGraph(const gtString& isaFileName, const gtString& outputFileName, LoggingCallBackFunc_t pCallback)
{
// Call the backend.
beStatus rc = beStaticIsaAnalyzer::GenerateControlFlowGraph(isaFileName, outputFileName);
if (rc != beStatus_SUCCESS && pCallback != nullptr)
{
// Inform the user in case of an error.
std::stringstream msg;
switch (rc)
{
case beKA::beStatus_shaeCannotLocateAnalyzer:
// Failed to locate the ISA analyzer.
msg << STR_ERR_CANNOT_LOCATE_LIVE_REG_ANALYZER << std::endl;
break;
case beKA::beStatus_shaeIsaFileNotFound:
// ISA file not found.
msg << STR_ERR_CANNOT_FIND_ISA_FILE << std::endl;
break;
case beKA::beStatus_shaeFailedToLaunch:
// Failed to launch the ISA analyzer.
msg << STR_ERR_CANNOT_LAUNCH_CFG_ANALYZER << std::endl;
break;
case beKA::beStatus_General_FAILED:
default:
// Generic error message.
msg << STR_ERR_CANNOT_PERFORM_LIVE_REG_ANALYSIS << std::endl;
break;
}
const std::string& errMsg = msg.str();
if (!errMsg.empty() && pCallback != nullptr)
{
pCallback(errMsg);
}
}
}
void kcUtils::ConstructOutputFileName(const std::string& baseOutputFileName, const std::string& defaultExtension, const std::string& kernelName, const std::string& deviceName, gtString& generatedFileName)
{
// Convert the base output file name to gtString.
gtString baseOutputFileNameAsGtStr;
baseOutputFileNameAsGtStr << baseOutputFileName.c_str();
osFilePath outputFilePath(baseOutputFileNameAsGtStr);
// Extract the user's file name and extension.
gtString fileName;
if (!outputFilePath.isDirectory())
{
outputFilePath.getFileName(fileName);
}
else
{
osDirectory outputDir(baseOutputFileNameAsGtStr);
outputFilePath.setFileDirectory(outputDir);
}
// Fix the user's file name to generate a unique output file name in the Analyzer CLI format.
gtString fixedFileName;
fixedFileName << deviceName.c_str();
if (!kernelName.empty())
{
if (!fixedFileName.isEmpty())
{
fixedFileName << "_";
}
fixedFileName << kernelName.c_str();
}
if (!fileName.isEmpty())
{
if (!fixedFileName.isEmpty())
{
fixedFileName << "_";
}
fixedFileName << fileName;
}
outputFilePath.setFileName(fixedFileName);
// Handle the default extension (unless the user specified an extension).
gtString outputFileExtension;
outputFilePath.getFileExtension(outputFileExtension);
if (outputFileExtension.isEmpty())
{
outputFileExtension.fromASCIIString(defaultExtension.c_str());
outputFilePath.setFileExtension(outputFileExtension);
}
// Set the output string.
generatedFileName = outputFilePath.asString();
}
kcUtils::kcUtils()
{
}
kcUtils::~kcUtils()
{
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/all.hpp>
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/concept/printable/vast/uuid.hpp"
#include "vast/detail/assert.hpp"
#include "vast/event.hpp"
#include "vast/expression_visitors.hpp"
#include "vast/logger.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/atoms.hpp"
#include "vast/system/exporter.hpp"
#include "vast/detail/assert.hpp"
using namespace std::chrono;
using namespace std::string_literals;
using namespace caf;
namespace vast {
namespace system {
namespace {
void ship_results(stateful_actor<exporter_state>* self) {
VAST_TRACE("");
if (self->state.results.empty() || self->state.query.requested == 0) {
return;
}
VAST_INFO(self, "relays", self->state.results.size(), "events");
message msg;
if (self->state.results.size() <= self->state.query.requested) {
self->state.query.requested -= self->state.results.size();
self->state.query.shipped += self->state.results.size();
msg = make_message(std::move(self->state.results));
self->state.results = {};
} else {
std::vector<event> remainder;
remainder.reserve(self->state.results.size() - self->state.query.requested);
auto begin = self->state.results.begin() + self->state.query.requested;
auto end = self->state.results.end();
std::move(begin, end, std::back_inserter(remainder));
self->state.results.resize(self->state.query.requested);
msg = make_message(std::move(self->state.results));
self->state.results = std::move(remainder);
self->state.query.shipped += self->state.query.requested;
self->state.query.requested = 0;
}
self->send(self->state.sink, msg);
}
void report_statistics(stateful_actor<exporter_state>* self) {
timespan runtime = steady_clock::now() - self->state.start;
self->state.query.runtime = runtime;
VAST_INFO(self, "completed in", runtime);
self->send(self->state.sink, self->state.id, self->state.query);
if (self->state.accountant) {
auto hits = rank(self->state.hits);
auto processed = self->state.query.processed;
auto shipped = self->state.query.shipped;
auto results = shipped + self->state.results.size();
auto selectivity = double(results) / hits;
self->send(self->state.accountant, "exporter.hits", hits);
self->send(self->state.accountant, "exporter.processed", processed);
self->send(self->state.accountant, "exporter.results", results);
self->send(self->state.accountant, "exporter.shipped", shipped);
self->send(self->state.accountant, "exporter.selectivity", selectivity);
self->send(self->state.accountant, "exporter.runtime", runtime);
}
}
void shutdown(stateful_actor<exporter_state>* self, caf::error err) {
VAST_DEBUG(self, "initiates shutdown with error", self->system().render(err));
self->send_exit(self, std::move(err));
}
void shutdown(stateful_actor<exporter_state>* self) {
if (has_continuous_option(self->state.options))
return;
VAST_DEBUG(self, "initiates shutdown");
self->send_exit(self, exit_reason::normal);
}
void request_more_hits(stateful_actor<exporter_state>* self) {
const auto& st = self->state;
if (!has_historical_option(st.options))
return;
auto waiting_for_hits =
st.query.received == st.query.scheduled;
auto need_more_results = st.query.requested > 0;
auto have_no_inflight_requests =
st.query.lookups_issued == st.query.lookups_complete;
// If we're (1) no longer waiting for index hits, (2) still need more
// results, and (3) have no inflight requests to the archive, we ask
// the index for more hits.
if (!waiting_for_hits && need_more_results && have_no_inflight_requests) {
auto remaining = st.query.expected - st.query.received;
VAST_ASSERT(remaining > 0);
// TODO: Figure out right number of partitions to ask for. For now, we
// bound the number by an arbitrary constant.
auto n = std::min(remaining, size_t{2});
VAST_DEBUG(self, "asks index to process", n, "more partitions");
self->send(st.index, st.id, n);
}
}
} // namespace <anonymous>
behavior exporter(stateful_actor<exporter_state>* self, expression expr,
query_options options) {
auto eu = self->system().dummy_execution_unit();
self->state.sink = actor_pool::make(eu, actor_pool::broadcast());
if (auto a = self->system().registry().get(accountant_atom::value))
self->state.accountant = actor_cast<accountant_type>(a);
self->state.options = options;
if (has_continuous_option(options))
VAST_DEBUG(self, "has continuous query option");
self->set_exit_handler(
[=](const exit_msg& msg) {
VAST_DEBUG(self, "received exit from", msg.source, "with reason:", msg.reason);
self->send<message_priority::high>(self->state.index, self->state.id, 0);
self->send(self->state.sink, sys_atom::value, delete_atom::value);
self->send_exit(self->state.sink, msg.reason);
self->quit(msg.reason);
if (msg.reason != exit_reason::kill)
report_statistics(self);
}
);
self->set_down_handler(
[=](const down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
if (has_continuous_option(self->state.options)
&& (msg.source == self->state.archive
|| msg.source == self->state.index))
report_statistics(self);
}
);
auto finished = [&](const query_status& qs) -> bool {
return qs.received == qs.expected
&& qs.lookups_issued == qs.lookups_complete;
};
auto handle_batch = [=](std::vector<event> candidates) {
VAST_DEBUG(self, "got batch of", candidates.size(), "events");
auto sender = self->current_sender();
for (auto& candidate : candidates) {
auto& checker = self->state.checkers[candidate.type()];
// Construct a candidate checker if we don't have one for this type.
if (caf::holds_alternative<caf::none_t>(checker)) {
auto x = tailor(expr, candidate.type());
if (!x) {
VAST_ERROR(self, "failed to tailor expression:",
self->system().render(x.error()));
ship_results(self);
self->send_exit(self, exit_reason::normal);
return;
}
checker = std::move(*x);
VAST_DEBUG(self, "tailored AST to", candidate.type() << ':', checker);
}
// Perform candidate check and keep event as result on success.
if (caf::visit(event_evaluator{candidate}, checker))
self->state.results.push_back(std::move(candidate));
else
VAST_DEBUG(self, "ignores false positive:", candidate);
}
self->state.query.processed += candidates.size();
ship_results(self);
};
return {
// The INDEX (or the EVALUATOR, to be more precise) sends us a series of
// `ids` in response to an expression (query), terminated by 'done'.
[=](ids& hits) {
// Add `hits` to the total result set and update all stats.
auto& st = self->state;
timespan runtime = steady_clock::now() - st.start;
st.query.runtime = runtime;
auto count = rank(hits);
if (st.accountant) {
if (st.hits.empty())
self->send(st.accountant, "exporter.hits.first", runtime);
self->send(st.accountant, "exporter.hits.arrived", runtime);
self->send(st.accountant, "exporter.hits.count", count);
}
if (count == 0) {
VAST_WARNING(self, "got an empty delta from INDEX lookup");
} else {
VAST_DEBUG(self, "got", count, "index hits in [", (select(hits, 1)),
',', (select(hits, -1) + 1), ')');
st.hits |= hits;
VAST_DEBUG(self, "forwards hits to archive");
// FIXME: restrict according to configured limit.
++st.query.lookups_issued;
self->send(st.archive, std::move(hits));
}
},
[=](table_slice_ptr slice) {
handle_batch(to_events(*slice, self->state.hits));
},
[=](done_atom) {
// Figure out if we're done by bumping the counter for `received` and
// check whether it reaches `expected`.
auto& st = self->state;
timespan runtime = steady_clock::now() - st.start;
st.query.runtime = runtime;
st.query.received += st.query.scheduled;
if (st.query.received < st.query.expected) {
VAST_DEBUG(self, "received", st.query.received, '/',
st.query.expected, "ID sets");
request_more_hits(self);
} else {
VAST_DEBUG(self, "received all", st.query.expected,
"ID set(s) in", runtime);
if (st.accountant)
self->send(st.accountant, "exporter.hits.runtime", runtime);
if (finished(st.query))
shutdown(self);
}
},
[=](done_atom, const caf::error& err) {
auto& st = self->state;
auto sender = self->current_sender();
if (sender == st.archive) {
if (err)
VAST_DEBUG(self, "received error from archive:",
self->system().render(err));
++st.query.lookups_complete;
}
if (finished(st.query))
shutdown(self);
},
[=](extract_atom) {
if (self->state.query.requested == max_events) {
VAST_WARNING(self, "ignores extract request, already getting all");
return;
}
self->state.query.requested = max_events;
ship_results(self);
request_more_hits(self);
},
[=](extract_atom, uint64_t requested) {
if (self->state.query.requested == max_events) {
VAST_WARNING(self, "ignores extract request, already getting all");
return;
}
auto n = std::min(max_events - requested, requested);
self->state.query.requested += n;
VAST_DEBUG(self, "got request to extract", n, "new events in addition to",
self->state.query.requested, "pending results");
ship_results(self);
request_more_hits(self);
},
[=](const archive_type& archive) {
VAST_DEBUG(self, "registers archive", archive);
self->state.archive = archive;
if (has_continuous_option(self->state.options))
self->monitor(archive);
// Register self at the archive
if (has_historical_option(self->state.options))
self->send(archive, exporter_atom::value, self);
},
[=](index_atom, const actor& index) {
VAST_DEBUG(self, "registers index", index);
self->state.index = index;
if (has_continuous_option(self->state.options))
self->monitor(index);
},
[=](sink_atom, const actor& sink) {
VAST_DEBUG(self, "registers sink", sink);
self->send(self->state.sink, sys_atom::value, put_atom::value, sink);
self->monitor(self->state.sink);
},
[=](importer_atom, const std::vector<actor>& importers) {
// Register for events at running IMPORTERs.
if (has_continuous_option(self->state.options))
for (auto& x : importers)
self->send(x, exporter_atom::value, self);
},
[=](run_atom) {
VAST_INFO(self, "executes query", expr);
self->state.start = steady_clock::now();
if (!has_historical_option(self->state.options))
return;
self->request(self->state.index, infinite, expr).then(
[=](const uuid& lookup, size_t partitions, size_t scheduled) {
VAST_DEBUG(self, "got lookup handle", lookup << ", scheduled",
scheduled << '/' << partitions, "partitions");
self->state.id = lookup;
if (partitions > 0) {
self->state.query.expected = partitions;
self->state.query.scheduled = scheduled;
} else {
shutdown(self);
}
},
[=](const error& e) {
shutdown(self, e);
}
);
},
[=](caf::stream<table_slice_ptr> in) {
return self->make_sink(
in,
[](caf::unit_t&) {
// nop
},
[=](caf::unit_t&, const table_slice_ptr& slice) {
// TODO: port to new table slice API
auto candidates = to_events(*slice);
handle_batch(std::move(candidates));
},
[=](caf::unit_t&, const error& err) {
VAST_IGNORE_UNUSED(err);
VAST_ERROR(self, "got error during streaming: ", err);
}
);
},
};
}
} // namespace system
} // namespace vast
<commit_msg>Clarify log message text<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/all.hpp>
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/concept/printable/vast/uuid.hpp"
#include "vast/detail/assert.hpp"
#include "vast/event.hpp"
#include "vast/expression_visitors.hpp"
#include "vast/logger.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/atoms.hpp"
#include "vast/system/exporter.hpp"
#include "vast/detail/assert.hpp"
using namespace std::chrono;
using namespace std::string_literals;
using namespace caf;
namespace vast {
namespace system {
namespace {
void ship_results(stateful_actor<exporter_state>* self) {
VAST_TRACE("");
if (self->state.results.empty() || self->state.query.requested == 0) {
return;
}
VAST_INFO(self, "relays", self->state.results.size(), "events");
message msg;
if (self->state.results.size() <= self->state.query.requested) {
self->state.query.requested -= self->state.results.size();
self->state.query.shipped += self->state.results.size();
msg = make_message(std::move(self->state.results));
self->state.results = {};
} else {
std::vector<event> remainder;
remainder.reserve(self->state.results.size() - self->state.query.requested);
auto begin = self->state.results.begin() + self->state.query.requested;
auto end = self->state.results.end();
std::move(begin, end, std::back_inserter(remainder));
self->state.results.resize(self->state.query.requested);
msg = make_message(std::move(self->state.results));
self->state.results = std::move(remainder);
self->state.query.shipped += self->state.query.requested;
self->state.query.requested = 0;
}
self->send(self->state.sink, msg);
}
void report_statistics(stateful_actor<exporter_state>* self) {
timespan runtime = steady_clock::now() - self->state.start;
self->state.query.runtime = runtime;
VAST_INFO(self, "completed in", runtime);
self->send(self->state.sink, self->state.id, self->state.query);
if (self->state.accountant) {
auto hits = rank(self->state.hits);
auto processed = self->state.query.processed;
auto shipped = self->state.query.shipped;
auto results = shipped + self->state.results.size();
auto selectivity = double(results) / hits;
self->send(self->state.accountant, "exporter.hits", hits);
self->send(self->state.accountant, "exporter.processed", processed);
self->send(self->state.accountant, "exporter.results", results);
self->send(self->state.accountant, "exporter.shipped", shipped);
self->send(self->state.accountant, "exporter.selectivity", selectivity);
self->send(self->state.accountant, "exporter.runtime", runtime);
}
}
void shutdown(stateful_actor<exporter_state>* self, caf::error err) {
VAST_DEBUG(self, "initiates shutdown with error", self->system().render(err));
self->send_exit(self, std::move(err));
}
void shutdown(stateful_actor<exporter_state>* self) {
if (has_continuous_option(self->state.options))
return;
VAST_DEBUG(self, "initiates shutdown");
self->send_exit(self, exit_reason::normal);
}
void request_more_hits(stateful_actor<exporter_state>* self) {
const auto& st = self->state;
if (!has_historical_option(st.options))
return;
auto waiting_for_hits =
st.query.received == st.query.scheduled;
auto need_more_results = st.query.requested > 0;
auto have_no_inflight_requests =
st.query.lookups_issued == st.query.lookups_complete;
// If we're (1) no longer waiting for index hits, (2) still need more
// results, and (3) have no inflight requests to the archive, we ask
// the index for more hits.
if (!waiting_for_hits && need_more_results && have_no_inflight_requests) {
auto remaining = st.query.expected - st.query.received;
VAST_ASSERT(remaining > 0);
// TODO: Figure out right number of partitions to ask for. For now, we
// bound the number by an arbitrary constant.
auto n = std::min(remaining, size_t{2});
VAST_DEBUG(self, "asks index to process", n, "more partitions");
self->send(st.index, st.id, n);
}
}
} // namespace <anonymous>
behavior exporter(stateful_actor<exporter_state>* self, expression expr,
query_options options) {
auto eu = self->system().dummy_execution_unit();
self->state.sink = actor_pool::make(eu, actor_pool::broadcast());
if (auto a = self->system().registry().get(accountant_atom::value))
self->state.accountant = actor_cast<accountant_type>(a);
self->state.options = options;
if (has_continuous_option(options))
VAST_DEBUG(self, "has continuous query option");
self->set_exit_handler(
[=](const exit_msg& msg) {
VAST_DEBUG(self, "received exit from", msg.source, "with reason:", msg.reason);
self->send<message_priority::high>(self->state.index, self->state.id, 0);
self->send(self->state.sink, sys_atom::value, delete_atom::value);
self->send_exit(self->state.sink, msg.reason);
self->quit(msg.reason);
if (msg.reason != exit_reason::kill)
report_statistics(self);
}
);
self->set_down_handler(
[=](const down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
if (has_continuous_option(self->state.options)
&& (msg.source == self->state.archive
|| msg.source == self->state.index))
report_statistics(self);
}
);
auto finished = [&](const query_status& qs) -> bool {
return qs.received == qs.expected
&& qs.lookups_issued == qs.lookups_complete;
};
auto handle_batch = [=](std::vector<event> candidates) {
VAST_DEBUG(self, "got batch of", candidates.size(), "events");
auto sender = self->current_sender();
for (auto& candidate : candidates) {
auto& checker = self->state.checkers[candidate.type()];
// Construct a candidate checker if we don't have one for this type.
if (caf::holds_alternative<caf::none_t>(checker)) {
auto x = tailor(expr, candidate.type());
if (!x) {
VAST_ERROR(self, "failed to tailor expression:",
self->system().render(x.error()));
ship_results(self);
self->send_exit(self, exit_reason::normal);
return;
}
checker = std::move(*x);
VAST_DEBUG(self, "tailored AST to", candidate.type() << ':', checker);
}
// Perform candidate check and keep event as result on success.
if (caf::visit(event_evaluator{candidate}, checker))
self->state.results.push_back(std::move(candidate));
else
VAST_DEBUG(self, "ignores false positive:", candidate);
}
self->state.query.processed += candidates.size();
ship_results(self);
};
return {
// The INDEX (or the EVALUATOR, to be more precise) sends us a series of
// `ids` in response to an expression (query), terminated by 'done'.
[=](ids& hits) {
// Add `hits` to the total result set and update all stats.
auto& st = self->state;
timespan runtime = steady_clock::now() - st.start;
st.query.runtime = runtime;
auto count = rank(hits);
if (st.accountant) {
if (st.hits.empty())
self->send(st.accountant, "exporter.hits.first", runtime);
self->send(st.accountant, "exporter.hits.arrived", runtime);
self->send(st.accountant, "exporter.hits.count", count);
}
if (count == 0) {
VAST_WARNING(self, "got empty hits");
} else {
VAST_DEBUG(self, "got", count, "index hits in [", (select(hits, 1)),
',', (select(hits, -1) + 1), ')');
st.hits |= hits;
VAST_DEBUG(self, "forwards hits to archive");
// FIXME: restrict according to configured limit.
++st.query.lookups_issued;
self->send(st.archive, std::move(hits));
}
},
[=](table_slice_ptr slice) {
handle_batch(to_events(*slice, self->state.hits));
},
[=](done_atom) {
// Figure out if we're done by bumping the counter for `received` and
// check whether it reaches `expected`.
auto& st = self->state;
timespan runtime = steady_clock::now() - st.start;
st.query.runtime = runtime;
st.query.received += st.query.scheduled;
if (st.query.received < st.query.expected) {
VAST_DEBUG(self, "received", st.query.received, '/',
st.query.expected, "ID sets");
request_more_hits(self);
} else {
VAST_DEBUG(self, "received all", st.query.expected,
"ID set(s) in", runtime);
if (st.accountant)
self->send(st.accountant, "exporter.hits.runtime", runtime);
if (finished(st.query))
shutdown(self);
}
},
[=](done_atom, const caf::error& err) {
auto& st = self->state;
auto sender = self->current_sender();
if (sender == st.archive) {
if (err)
VAST_DEBUG(self, "received error from archive:",
self->system().render(err));
++st.query.lookups_complete;
}
if (finished(st.query))
shutdown(self);
},
[=](extract_atom) {
if (self->state.query.requested == max_events) {
VAST_WARNING(self, "ignores extract request, already getting all");
return;
}
self->state.query.requested = max_events;
ship_results(self);
request_more_hits(self);
},
[=](extract_atom, uint64_t requested) {
if (self->state.query.requested == max_events) {
VAST_WARNING(self, "ignores extract request, already getting all");
return;
}
auto n = std::min(max_events - requested, requested);
self->state.query.requested += n;
VAST_DEBUG(self, "got request to extract", n, "new events in addition to",
self->state.query.requested, "pending results");
ship_results(self);
request_more_hits(self);
},
[=](const archive_type& archive) {
VAST_DEBUG(self, "registers archive", archive);
self->state.archive = archive;
if (has_continuous_option(self->state.options))
self->monitor(archive);
// Register self at the archive
if (has_historical_option(self->state.options))
self->send(archive, exporter_atom::value, self);
},
[=](index_atom, const actor& index) {
VAST_DEBUG(self, "registers index", index);
self->state.index = index;
if (has_continuous_option(self->state.options))
self->monitor(index);
},
[=](sink_atom, const actor& sink) {
VAST_DEBUG(self, "registers sink", sink);
self->send(self->state.sink, sys_atom::value, put_atom::value, sink);
self->monitor(self->state.sink);
},
[=](importer_atom, const std::vector<actor>& importers) {
// Register for events at running IMPORTERs.
if (has_continuous_option(self->state.options))
for (auto& x : importers)
self->send(x, exporter_atom::value, self);
},
[=](run_atom) {
VAST_INFO(self, "executes query", expr);
self->state.start = steady_clock::now();
if (!has_historical_option(self->state.options))
return;
self->request(self->state.index, infinite, expr).then(
[=](const uuid& lookup, size_t partitions, size_t scheduled) {
VAST_DEBUG(self, "got lookup handle", lookup << ", scheduled",
scheduled << '/' << partitions, "partitions");
self->state.id = lookup;
if (partitions > 0) {
self->state.query.expected = partitions;
self->state.query.scheduled = scheduled;
} else {
shutdown(self);
}
},
[=](const error& e) {
shutdown(self, e);
}
);
},
[=](caf::stream<table_slice_ptr> in) {
return self->make_sink(
in,
[](caf::unit_t&) {
// nop
},
[=](caf::unit_t&, const table_slice_ptr& slice) {
// TODO: port to new table slice API
auto candidates = to_events(*slice);
handle_batch(std::move(candidates));
},
[=](caf::unit_t&, const error& err) {
VAST_IGNORE_UNUSED(err);
VAST_ERROR(self, "got error during streaming: ", err);
}
);
},
};
}
} // namespace system
} // namespace vast
<|endoftext|> |
<commit_before>//===-- Value.cpp - Implement the Value class -----------------------------===//
//
// This file implements the Value, User, and SymTabValue classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/ValueHolderImpl.h"
#include "llvm/InstrTypes.h"
#include "llvm/SymbolTable.h"
#include "llvm/SymTabValue.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/Type.h"
#ifndef NDEBUG // Only in -g mode...
#include "llvm/Assembly/Writer.h"
#endif
#include <algorithm>
//===----------------------------------------------------------------------===//
// Value Class
//===----------------------------------------------------------------------===//
Value::Value(const Type *ty, ValueTy vty, const string &name = "")
: Name(name), Ty(ty, this) {
VTy = vty;
}
Value::~Value() {
#ifndef NDEBUG // Only in -g mode...
// Check to make sure that there are no uses of this value that are still
// around when the value is destroyed. If there are, then we have a dangling
// reference and something is wrong. This code is here to print out what is
// still being referenced. The value in question should be printed as
// a <badref>
//
if (Uses.begin() != Uses.end()) {
for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)
cerr << "Use still stuck around after Def is destroyed:" << *I << endl;
}
#endif
assert(Uses.begin() == Uses.end());
}
void Value::replaceAllUsesWith(Value *D) {
assert(D && "Value::replaceAllUsesWith(<null>) is invalid!");
assert(D != this && "V->replaceAllUsesWith(V) is NOT valid!");
while (!Uses.empty()) {
User *Use = Uses.back();
#ifndef NDEBUG
unsigned NumUses = Uses.size();
#endif
Use->replaceUsesOfWith(this, D);
#ifndef NDEBUG // only in -g mode...
if (Uses.size() == NumUses)
cerr << "Use: " << Use << "replace with: " << D;
#endif
assert(Uses.size() != NumUses && "Didn't remove definition!");
}
}
// refineAbstractType - This function is implemented because we use
// potentially abstract types, and these types may be resolved to more
// concrete types after we are constructed. For the value class, we simply
// change Ty to point to the right type. :)
//
void Value::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
assert(Ty.get() == (const Type*)OldTy &&"Can't refine anything but my type!");
Ty = NewTy;
}
void Value::killUse(User *i) {
if (i == 0) return;
use_iterator I = find(Uses.begin(), Uses.end(), i);
assert(I != Uses.end() && "Use not in uses list!!");
Uses.erase(I);
}
User *Value::use_remove(use_iterator &I) {
assert(I != Uses.end() && "Trying to remove the end of the use list!!!");
User *i = *I;
I = Uses.erase(I);
return i;
}
//===----------------------------------------------------------------------===//
// User Class
//===----------------------------------------------------------------------===//
User::User(const Type *Ty, ValueTy vty, const string &name)
: Value(Ty, vty, name) {
}
// replaceUsesOfWith - Replaces all references to the "From" definition with
// references to the "To" definition.
//
void User::replaceUsesOfWith(Value *From, Value *To) {
if (From == To) return; // Duh what?
for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
if (getOperand(i) == From) { // Is This operand is pointing to oldval?
// The side effects of this setOperand call include linking to
// "To", adding "this" to the uses list of To, and
// most importantly, removing "this" from the use list of "From".
setOperand(i, To); // Fix it now...
}
}
//===----------------------------------------------------------------------===//
// SymTabValue Class
//===----------------------------------------------------------------------===//
SymTabValue::SymTabValue(Value *p) : ValueParent(p) {
assert(ValueParent && "SymTavValue without parent!?!");
ParentSymTab = SymTab = 0;
}
SymTabValue::~SymTabValue() {
delete SymTab;
}
void SymTabValue::setParentSymTab(SymbolTable *ST) {
ParentSymTab = ST;
if (SymTab)
SymTab->setParentSymTab(ST);
}
SymbolTable *SymTabValue::getSymbolTableSure() {
if (!SymTab) SymTab = new SymbolTable(ParentSymTab);
return SymTab;
}
// hasSymbolTable() - Returns true if there is a symbol table allocated to
// this object AND if there is at least one name in it!
//
bool SymTabValue::hasSymbolTable() const {
if (!SymTab) return false;
for (SymbolTable::const_iterator I = SymTab->begin();
I != SymTab->end(); ++I) {
if (I->second.begin() != I->second.end())
return true; // Found nonempty type plane!
}
return false;
}
<commit_msg>Added debugging support.<commit_after>//===-- Value.cpp - Implement the Value class -----------------------------===//
//
// This file implements the Value, User, and SymTabValue classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/ValueHolderImpl.h"
#include "llvm/InstrTypes.h"
#include "llvm/SymbolTable.h"
#include "llvm/SymTabValue.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/Type.h"
#ifndef NDEBUG // Only in -g mode...
#include "llvm/Assembly/Writer.h"
#endif
#include <algorithm>
//===----------------------------------------------------------------------===//
// Value Class
//===----------------------------------------------------------------------===//
Value::Value(const Type *ty, ValueTy vty, const string &name = "")
: Name(name), Ty(ty, this) {
VTy = vty;
}
Value::~Value() {
#ifndef NDEBUG // Only in -g mode...
// Check to make sure that there are no uses of this value that are still
// around when the value is destroyed. If there are, then we have a dangling
// reference and something is wrong. This code is here to print out what is
// still being referenced. The value in question should be printed as
// a <badref>
//
if (Uses.begin() != Uses.end()) {
for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)
cerr << "Use still stuck around after Def is destroyed:" << *I << endl;
}
#endif
assert(Uses.begin() == Uses.end());
}
void Value::replaceAllUsesWith(Value *D) {
assert(D && "Value::replaceAllUsesWith(<null>) is invalid!");
assert(D != this && "V->replaceAllUsesWith(V) is NOT valid!");
while (!Uses.empty()) {
User *Use = Uses.back();
#ifndef NDEBUG
unsigned NumUses = Uses.size();
#endif
Use->replaceUsesOfWith(this, D);
#ifndef NDEBUG // only in -g mode...
if (Uses.size() == NumUses)
cerr << "Use: " << Use << "replace with: " << D;
#endif
assert(Uses.size() != NumUses && "Didn't remove definition!");
}
}
// refineAbstractType - This function is implemented because we use
// potentially abstract types, and these types may be resolved to more
// concrete types after we are constructed. For the value class, we simply
// change Ty to point to the right type. :)
//
void Value::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
assert(Ty.get() == (const Type*)OldTy &&"Can't refine anything but my type!");
Ty = NewTy;
}
void Value::killUse(User *i) {
if (i == 0) return;
use_iterator I = find(Uses.begin(), Uses.end(), i);
assert(I != Uses.end() && "Use not in uses list!!");
Uses.erase(I);
}
User *Value::use_remove(use_iterator &I) {
assert(I != Uses.end() && "Trying to remove the end of the use list!!!");
User *i = *I;
I = Uses.erase(I);
return i;
}
void
Value::dump() const
{
DebugValue(*this);
}
ostream&
operator<<(ostream &o, const Value& I)
{
switch (I.getValueType()) {
case Value::TypeVal: return o << I.castTypeAsserting();
case Value::ConstantVal: WriteToAssembly((const ConstPoolVal*)&I,o);break;
case Value::MethodArgumentVal: return o << I.getType() << " "<< I.getName();
case Value::InstructionVal:WriteToAssembly((const Instruction *)&I, o);break;
case Value::BasicBlockVal: WriteToAssembly((const BasicBlock *)&I, o);break;
case Value::MethodVal: WriteToAssembly((const Method *)&I, o);break;
case Value::GlobalVal: WriteToAssembly((const GlobalVariable*)&I,o);break;
case Value::ModuleVal: WriteToAssembly((const Module *)&I,o); break;
default: return o << "<unknown value type: " << I.getValueType() << ">";
}
return o;
}
void
DebugValue(const Value* V)
{
if (V)
cerr << *V << endl;
else
cerr << "<NULL value>" << endl;
}
void
DebugValue(const Value& V)
{
cerr << V << endl;
}
//===----------------------------------------------------------------------===//
// User Class
//===----------------------------------------------------------------------===//
User::User(const Type *Ty, ValueTy vty, const string &name)
: Value(Ty, vty, name) {
}
// replaceUsesOfWith - Replaces all references to the "From" definition with
// references to the "To" definition.
//
void User::replaceUsesOfWith(Value *From, Value *To) {
if (From == To) return; // Duh what?
for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
if (getOperand(i) == From) { // Is This operand is pointing to oldval?
// The side effects of this setOperand call include linking to
// "To", adding "this" to the uses list of To, and
// most importantly, removing "this" from the use list of "From".
setOperand(i, To); // Fix it now...
}
}
//===----------------------------------------------------------------------===//
// SymTabValue Class
//===----------------------------------------------------------------------===//
SymTabValue::SymTabValue(Value *p) : ValueParent(p) {
assert(ValueParent && "SymTavValue without parent!?!");
ParentSymTab = SymTab = 0;
}
SymTabValue::~SymTabValue() {
delete SymTab;
}
void SymTabValue::setParentSymTab(SymbolTable *ST) {
ParentSymTab = ST;
if (SymTab)
SymTab->setParentSymTab(ST);
}
SymbolTable *SymTabValue::getSymbolTableSure() {
if (!SymTab) SymTab = new SymbolTable(ParentSymTab);
return SymTab;
}
// hasSymbolTable() - Returns true if there is a symbol table allocated to
// this object AND if there is at least one name in it!
//
bool SymTabValue::hasSymbolTable() const {
if (!SymTab) return false;
for (SymbolTable::const_iterator I = SymTab->begin();
I != SymTab->end(); ++I) {
if (I->second.begin() != I->second.end())
return true; // Found nonempty type plane!
}
return false;
}
<|endoftext|> |
<commit_before><commit_msg>Fix sign mismatch issues.<commit_after><|endoftext|> |
<commit_before>#include "acmacs-base/time-series.hh"
#include "acmacs-base/rjson-v3-helper.hh"
#include "acmacs-base/string-compare.hh"
#include "acmacs-map-draw/mapi-settings.hh"
#include "acmacs-map-draw/draw.hh"
// ----------------------------------------------------------------------
// "?start": "2019-01", "?end": "2019-11",
// "interval": {"month": 1}, "?": "month, week, year, day (interval: month also supported)",
// "output": "/path/name-{ts-name}.pdf",
// "shown-on-all": <Select Antigens>, -- reference antigens and sera are shown on all maps, select here other antigens to show on all the maps
// "report": true
bool acmacs::mapi::v1::Settings::apply_time_series()
{
using namespace std::string_view_literals;
auto ts_params = getenv("interval"sv).visit([]<typename Val>(const Val& val) -> acmacs::time_series::parameters {
if constexpr (std::is_same_v<Val, rjson::v3::detail::object>) {
for (const auto& interval_n : {"year"sv, "month"sv, "week"sv, "day"sv}) {
if (const auto& num = val[interval_n]; !num.is_null())
return {interval_n, num.template to<date::period_diff_t>()};
}
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
else if constexpr (std::is_same_v<Val, rjson::v3::detail::string>) {
return {val.template to<std::string_view>()};
}
else {
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
});
if (const auto& start = getenv("start"sv); !start.is_null())
ts_params.first = date::from_string(start.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
if (const auto& end = getenv("end"sv); !end.is_null())
ts_params.after_last = date::from_string(end.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
const auto& chart_access = chart_draw().chart(0); // can draw just the chart 0 // get_chart(getenv("chart"sv), 0);
const auto ts_stat = acmacs::time_series::stat(ts_params, chart_access.chart().antigens()->all_dates());
const auto [first, after_last] = acmacs::time_series::suggest_start_end(ts_params, ts_stat);
auto series = acmacs::time_series::make(ts_params);
if (!ts_stat.counter().empty())
AD_INFO("time series full range {} .. {}", ts_stat.counter().begin()->first, ts_stat.counter().rbegin()->first);
AD_INFO("time series suggested {} .. {}", first, after_last);
AD_INFO("time series used {} .. {}", ts_params.first, ts_params.after_last);
if (rjson::v3::read_bool(getenv("report"sv), false)) {
AD_INFO("time series report:\n{}", ts_stat.report(" {value} {counter:6d}\n"));
}
if (const auto filename_pattern = rjson::v3::read_string(getenv("output"sv, toplevel_only::no, throw_if_partial_substitution::no)); filename_pattern.has_value()) {
auto filename{substitute_chart_metadata(*filename_pattern, chart_access)};
if (!acmacs::string::endswith_ignore_case(filename, ".pdf"sv))
filename = fmt::format("{}.pdf", filename);
chart_draw().calculate_viewport();
chart_draw().draw(filename, rjson::v3::read_number(getenv("width"sv), 800.0), report_time::no);
}
else
AD_WARNING("Cannot make time series: no \"output\" in {}", getenv_toplevel());
return true;
} // acmacs::mapi::v1::Settings::apply_time_series
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>mapi: time series<commit_after>#include "acmacs-base/time-series.hh"
#include "acmacs-base/rjson-v3-helper.hh"
#include "acmacs-base/string-compare.hh"
#include "acmacs-map-draw/mapi-settings.hh"
#include "acmacs-map-draw/draw.hh"
// ----------------------------------------------------------------------
// "?start": "2019-01", "?end": "2019-11",
// "interval": {"month": 1}, "?": "month, week, year, day (interval: month also supported)",
// "output": "/path/name-{ts-name}.pdf",
// "shown-on-all": <Select Antigens>, -- reference antigens and sera are shown on all maps, select here other antigens to show on all the maps
// "report": true
bool acmacs::mapi::v1::Settings::apply_time_series()
{
using namespace std::string_view_literals;
auto ts_params = getenv("interval"sv).visit([]<typename Val>(const Val& val) -> acmacs::time_series::parameters {
if constexpr (std::is_same_v<Val, rjson::v3::detail::object>) {
for (const auto& interval_n : {"year"sv, "month"sv, "week"sv, "day"sv}) {
if (const auto& num = val[interval_n]; !num.is_null())
return {interval_n, num.template to<date::period_diff_t>()};
}
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
else if constexpr (std::is_same_v<Val, rjson::v3::detail::string>) {
return {val.template to<std::string_view>()};
}
else {
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
});
if (const auto& start = getenv("start"sv); !start.is_null())
ts_params.first = date::from_string(start.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
if (const auto& end = getenv("end"sv); !end.is_null())
ts_params.after_last = date::from_string(end.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
const auto& chart_access = chart_draw().chart(0); // can draw just the chart 0 // get_chart(getenv("chart"sv), 0);
const auto ts_stat = acmacs::time_series::stat(ts_params, chart_access.chart().antigens()->all_dates(acmacs::chart::Antigens::include_reference::no));
const auto [first, after_last] = acmacs::time_series::suggest_start_end(ts_params, ts_stat);
auto series = acmacs::time_series::make(ts_params);
if (!ts_stat.counter().empty())
AD_INFO("time series full range {} .. {}", ts_stat.counter().begin()->first, ts_stat.counter().rbegin()->first);
AD_INFO("time series suggested {} .. {}", first, after_last);
AD_INFO("time series used {} .. {}", ts_params.first, ts_params.after_last);
if (rjson::v3::read_bool(getenv("report"sv), false)) {
AD_INFO("time series report:\n{}", ts_stat.report(" {value} {counter:6d}\n"));
}
if (const auto filename_pattern = rjson::v3::read_string(getenv("output"sv, toplevel_only::no, throw_if_partial_substitution::no)); filename_pattern.has_value()) {
auto filename{substitute_chart_metadata(*filename_pattern, chart_access)};
if (!acmacs::string::endswith_ignore_case(filename, ".pdf"sv))
filename = fmt::format("{}.pdf", filename);
chart_draw().calculate_viewport();
chart_draw().draw(filename, rjson::v3::read_number(getenv("width"sv), 800.0), report_time::no);
}
else
AD_WARNING("Cannot make time series: no \"output\" in {}", getenv_toplevel());
return true;
} // acmacs::mapi::v1::Settings::apply_time_series
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <string.h>
#include "lexer.h"
using namespace v8;
/* Type Definitions */
#define STRINGTYPE 0x03
#define COMMENTTYPE 0x01
#define KEYTYPE 0x02
/* State definitions */
#define NONESTATE 0x01
#define COMMENTSTATE 0x02
#define KEYSTATE 0x03
#define STRINGSTATE 0x04
#define VALLENGTH 100
char *v8StrToCharStar(v8::Local<v8::Value> value) {
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
void parse(const FunctionCallbackInfo<Value>& args) {
bool escaped = false;
char chr;
int i;
int ntokens;
int state = NONESTATE;
struct Token * tokens;
char * po_string;
char * buffer;
buffer = NULL;
tokens = NULL;
ntokens = 0;
Isolate* isolate = Isolate::GetCurrent();
Local<Object> catalog_obj;
Local<String> catalog_str;
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Takes two arguments")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
catalog_obj = Object::New(isolate);
po_string = v8StrToCharStar(args[0]);
catalog_str = args[0]->ToString();
for (i = 0; i < catalog_str->Length(); i++) {
chr = po_string[i];
switch(state) {
case NONESTATE:
if (chr == '\'' || chr == '"') {
state = STRINGSTATE;
tokens = append(tokens, ntokens, STRINGTYPE, chr, NULL);
++ntokens;
} else if (chr == '#') {
state = COMMENTSTATE;
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', NULL);
++ntokens;
} else if (!isspace(chr)) {
state = KEYSTATE;
buffer = append_to_buffer(buffer, chr);
} else if (isspace(chr) && buffer != NULL) {
tokens = append(tokens, ntokens, KEYTYPE, '\0', buffer);
free(buffer);
buffer = NULL;
++ntokens;
}
break;
case COMMENTSTATE:
if (chr == '\n') {
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', buffer);
state = NONESTATE;
free(buffer);
buffer = NULL;
++ntokens;
} else if (chr != '\r') {
buffer = append_to_buffer(buffer, chr);
}
break;
case STRINGSTATE:
if(escaped) {
switch(chr) {
case 't':
buffer = append_to_buffer(buffer, '\t');
break;
case 'n':
buffer = append_to_buffer(buffer, '\n');
break;
case 'r':
buffer = append_to_buffer(buffer, '\r');
break;
}
escaped = false;
} else {
if(chr == quote) {
tokens = append(tokens, ntokens, STRINGTYPE, quote, buffer);
free(buffer);
buffer = NULL;
state = NONESTATE;
++ntokens;
} else if (chr == '\\') {
escaped = true;
break;
} else {
buffer = append_to_buffer(buffer, chr);
}
escaped = false;
}
break;
case KEYSTATE:
if(isalpha(chr) || chr == '-' || chr == '[' || chr == ']') {
buffer = append_to_buffer(buffer, chr);
} else {
state = NONESTATE;
--i;
}
break;
}
}
args.GetReturnValue().Set(catalog_obj);
print_token_array(tokens, ntokens);
free_token_array(tokens, ntokens);
free(po_string);
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "parse", parse);
}
NODE_MODULE(gettextlexer, Init)
<commit_msg>Record the quote type used in comments<commit_after>#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <string.h>
#include "lexer.h"
using namespace v8;
/* Type Definitions */
#define STRINGTYPE 0x03
#define COMMENTTYPE 0x01
#define KEYTYPE 0x02
/* State definitions */
#define NONESTATE 0x01
#define COMMENTSTATE 0x02
#define KEYSTATE 0x03
#define STRINGSTATE 0x04
#define VALLENGTH 100
char *v8StrToCharStar(v8::Local<v8::Value> value) {
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
void parse(const FunctionCallbackInfo<Value>& args) {
bool escaped = false;
char chr;
char quote;
int i;
int ntokens;
int state = NONESTATE;
struct Token * tokens;
char * po_string;
char * buffer;
buffer = NULL;
tokens = NULL;
ntokens = 0;
quote = '\0';
Isolate* isolate = Isolate::GetCurrent();
Local<Object> catalog_obj;
Local<String> catalog_str;
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Takes two arguments")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
catalog_obj = Object::New(isolate);
po_string = v8StrToCharStar(args[0]);
catalog_str = args[0]->ToString();
for (i = 0; i < catalog_str->Length(); i++) {
chr = po_string[i];
switch(state) {
case NONESTATE:
if (chr == '\'' || chr == '"') {
state = STRINGSTATE;
quote = chr;
} else if (chr == '#') {
state = COMMENTSTATE;
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', NULL);
++ntokens;
} else if (!isspace(chr)) {
state = KEYSTATE;
buffer = append_to_buffer(buffer, chr);
} else if (isspace(chr) && buffer != NULL) {
tokens = append(tokens, ntokens, KEYTYPE, '\0', buffer);
free(buffer);
buffer = NULL;
++ntokens;
}
break;
case COMMENTSTATE:
if (chr == '\n') {
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', buffer);
state = NONESTATE;
free(buffer);
buffer = NULL;
++ntokens;
} else if (chr != '\r') {
buffer = append_to_buffer(buffer, chr);
}
break;
case STRINGSTATE:
if(escaped) {
switch(chr) {
case 't':
buffer = append_to_buffer(buffer, '\t');
break;
case 'n':
buffer = append_to_buffer(buffer, '\n');
break;
case 'r':
buffer = append_to_buffer(buffer, '\r');
break;
}
escaped = false;
} else {
if(chr == quote) {
tokens = append(tokens, ntokens, STRINGTYPE, quote, buffer);
free(buffer);
buffer = NULL;
state = NONESTATE;
++ntokens;
} else if (chr == '\\') {
escaped = true;
break;
} else {
buffer = append_to_buffer(buffer, chr);
}
escaped = false;
}
break;
case KEYSTATE:
if(isalpha(chr) || chr == '-' || chr == '[' || chr == ']') {
buffer = append_to_buffer(buffer, chr);
} else {
state = NONESTATE;
--i;
}
break;
}
}
args.GetReturnValue().Set(catalog_obj);
print_token_array(tokens, ntokens);
free_token_array(tokens, ntokens);
free(po_string);
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "parse", parse);
}
NODE_MODULE(gettextlexer, Init)
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 "base/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
// WorkerFastLayoutTests works on the linux try servers.
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
// Disabled because cloning ports are too slow in Chromium to meet the
// thresholds in this test.
// http://code.google.com/p/chromium/issues/detail?id=22780
// "worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
// Disabled afer r27553 (WebKit merge), http://crbug.com/23391
// "worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
// http://code.google.com/p/chromium/issues/detail?id=23709
// "message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
// http://crbug.com/23597 (caused by http://trac.webkit.org/changeset/48978)
// "message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<commit_msg>Re-enable worker-script-error.html in ui_test now that r49408 form WebKit has been rolled in.<commit_after>// Copyright (c) 2009 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 "base/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
// WorkerFastLayoutTests works on the linux try servers.
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
// Disabled because cloning ports are too slow in Chromium to meet the
// thresholds in this test.
// http://code.google.com/p/chromium/issues/detail?id=22780
// "worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
// http://code.google.com/p/chromium/issues/detail?id=23709
// "message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
// http://crbug.com/23597 (caused by http://trac.webkit.org/changeset/48978)
// "message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<|endoftext|> |
<commit_before><commit_msg>Enable worker layout tests after the WebKit patch to fix an assert is landed.<commit_after><|endoftext|> |
<commit_before>//
// Created by jannis on 01.09.18.
//
#ifndef NOVA_RENDERER_X_11_WINDOW_HPP
#define NOVA_RENDERER_X_11_WINDOW_HPP
#ifdef NOVA_LINUX
#include <X11/Xlib.h>
#include <cstdint>
#include <nova_renderer/window.hpp>
namespace nova::renderer {
class x11_window : public iwindow {
private:
Window window;
Display* display;
bool should_window_close = false;
Atom wm_protocols;
Atom wm_delete_window;
public:
explicit x11_window(uint32_t width, uint32_t height, const std::string& title);
x11_window(x11_window&& other) noexcept = delete;
x11_window& operator=(x11_window&& other) noexcept = delete;
x11_window(const x11_window& other) = delete;
x11_window& operator=(const x11_window& other) = delete;
virtual ~x11_window();
Window& get_x11_window();
Display* get_display();
void on_frame_end() override;
[[nodiscard]] bool should_close() const override;
[[nodiscard]] glm::uvec2 get_window_size() const override;
};
} // namespace nova::renderer
#endif
// X11 macros that are bad
#ifdef Always
#undef Always
#endif
#ifdef None
#undef None
#endif
#ifdef Bool
#undef Bool
#endif
#endif // NOVA_RENDERER_X_11_WINDOW_HPP
<commit_msg>Include the thing properly I guess<commit_after>//
// Created by jannis on 01.09.18.
//
#ifndef NOVA_RENDERER_X_11_WINDOW_HPP
#define NOVA_RENDERER_X_11_WINDOW_HPP
#ifdef NOVA_LINUX
#include <X11/Xlib.h>
#include <cstdint>
#include "nova_renderer/window.hpp"
namespace nova::renderer {
class x11_window : public iwindow {
private:
Window window;
Display* display;
bool should_window_close = false;
Atom wm_protocols;
Atom wm_delete_window;
public:
explicit x11_window(uint32_t width, uint32_t height, const std::string& title);
x11_window(x11_window&& other) noexcept = delete;
x11_window& operator=(x11_window&& other) noexcept = delete;
x11_window(const x11_window& other) = delete;
x11_window& operator=(const x11_window& other) = delete;
virtual ~x11_window();
Window& get_x11_window();
Display* get_display();
void on_frame_end() override;
[[nodiscard]] bool should_close() const override;
[[nodiscard]] glm::uvec2 get_window_size() const override;
};
} // namespace nova::renderer
#endif
// X11 macros that are bad
#ifdef Always
#undef Always
#endif
#ifdef None
#undef None
#endif
#ifdef Bool
#undef Bool
#endif
#endif // NOVA_RENDERER_X_11_WINDOW_HPP
<|endoftext|> |
<commit_before>#include <string>
class Object
{
public:
virtual std::string toString() = 0;
};
#include <any.h>
#include <nullable.h>
#include <sequence.h>
#include <reflect.h>
#include <org/w3c/dom/NameList.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/css/CSSStyleDeclaration.h>
#include <org/w3c/dom/Document.h>
#include <org/w3c/dom/Element.h>
#include <org/w3c/dom/html/ApplicationCache.h>
#include <org/w3c/dom/html/BarProp.h>
#include <org/w3c/dom/html/Function.h>
#include <org/w3c/dom/html/History.h>
#include <org/w3c/dom/html/Location.h>
#include <org/w3c/dom/html/MessagePort.h>
#include <org/w3c/dom/html/Navigator.h>
#include <org/w3c/dom/html/Screen.h>
#include <org/w3c/dom/html/Selection.h>
#include <org/w3c/dom/html/StyleMedia.h>
#include <org/w3c/dom/html/UndoManager.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/webdatabase/Database.h>
#include <org/w3c/dom/webdatabase/DatabaseCallback.h>
#include <org/w3c/dom/webstorage/Storage.h>
#include <iostream>
#include <string>
using namespace std;
using namespace org::w3c::dom;
template<class B>
class Object_Bridge : public B
{
public:
virtual std::string toString()
{
return "";
}
};
Any invoke(Object* object, unsigned interfaceNumber, unsigned methodNumber,
const char* meta, unsigned offset,
unsigned paramCount, Any* arguments)
{
Reflect::Interface interface(meta);
cout << interface.getName() << endl;
Reflect::Method method(meta + offset);
cout << method.getName() << ':' << method.getParameterCount() << endl;
return Nullable<string>("Hi");
}
int main()
{
Object_Bridge<NameList_Bridge<Any, invoke> > nameList;
Nullable<string> name = nameList.getName(3);
cout << name.value() << endl;
name = nameList.getNamespaceURI(2);
cout << name.value() << endl;
Object_Bridge<html::Window_Bridge<Any, invoke> > window;
window.close();
window.setLength(100);
window.postMessage("hi", "hmm");
}
<commit_msg>(invoke) : Clean up.<commit_after>#include <string>
class Object
{
public:
virtual std::string toString() = 0;
};
#include <any.h>
#include <nullable.h>
#include <sequence.h>
#include <reflect.h>
#include <org/w3c/dom/NameList.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/css/CSSStyleDeclaration.h>
#include <org/w3c/dom/Document.h>
#include <org/w3c/dom/Element.h>
#include <org/w3c/dom/html/ApplicationCache.h>
#include <org/w3c/dom/html/BarProp.h>
#include <org/w3c/dom/html/Function.h>
#include <org/w3c/dom/html/History.h>
#include <org/w3c/dom/html/Location.h>
#include <org/w3c/dom/html/MessagePort.h>
#include <org/w3c/dom/html/Navigator.h>
#include <org/w3c/dom/html/Screen.h>
#include <org/w3c/dom/html/Selection.h>
#include <org/w3c/dom/html/StyleMedia.h>
#include <org/w3c/dom/html/UndoManager.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/webdatabase/Database.h>
#include <org/w3c/dom/webdatabase/DatabaseCallback.h>
#include <org/w3c/dom/webstorage/Storage.h>
#include <iostream>
#include <string>
using namespace std;
using namespace org::w3c::dom;
template<class B>
class Object_Bridge : public B
{
public:
virtual std::string toString()
{
return "";
}
};
Any invoke(Object* object, unsigned interfaceNumber, unsigned methodNumber,
const char* meta, unsigned offset,
unsigned argumentCount, Any* arguments)
{
Reflect::Interface interface(meta);
cout << interface.getName() << endl;
Reflect::Method method(meta + offset);
cout << method.getName() << ':' << method.getParameterCount() << endl;
return Nullable<string>("Hi");
}
int main()
{
Object_Bridge<NameList_Bridge<Any, invoke> > nameList;
Nullable<string> name = nameList.getName(3);
cout << name.value() << endl;
name = nameList.getNamespaceURI(2);
cout << name.value() << endl;
Object_Bridge<html::Window_Bridge<Any, invoke> > window;
window.close();
window.setLength(100);
window.postMessage("hi", "hmm");
}
<|endoftext|> |
<commit_before>
#include <cassert>
#include <QFileSystemWatcher>
#include <QTextStream>
#include <QFileInfo>
#include "FileAssociatedShader.h"
QMap<QString, QOpenGLShader *> FileAssociatedShader::s_shaderByFilePath;
QMultiMap<QOpenGLShader *, QOpenGLShaderProgram *> FileAssociatedShader::s_programsByShader;
FileAssociatedShader::FileAssociatedShader()
{}
FileAssociatedShader::~FileAssociatedShader()
{
s_shaderByFilePath.clear();
s_programsByShader.clear();
}
QOpenGLShader * FileAssociatedShader::getOrCreate(
QOpenGLShader::ShaderType type
, const QString & fileName
, QOpenGLShaderProgram & program)
{
QOpenGLShader * shader(nullptr);
QFileInfo fi(fileName);
if (!fi.exists())
{
qWarning() << fileName << " does not exist: shader is without source and associated file.";
return shader;
}
QString filePath(fi.absoluteFilePath());
if (s_shaderByFilePath.contains(filePath))
{
shader = s_shaderByFilePath[filePath];
}
else
{
instance()->addResourcePath(filePath);
shader = new QOpenGLShader(type);
shader->compileSourceFile(filePath);
connect(
shader,
&QOpenGLShader::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::shaderDestroyed);
s_shaderByFilePath.insert(filePath, shader);
}
if (!s_programsByShader.contains(shader, &program))
{
connect(
&program,
&QOpenGLShaderProgram::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::programDestroyed);
s_programsByShader.insert(shader, &program);
program.addShader(shader);
}
return shader;
}
void FileAssociatedShader::shaderDestroyed(QObject * object)
{
QOpenGLShader * shader = static_cast<QOpenGLShader*>(object);
const QString filePath(s_shaderByFilePath.key(shader));
assert(!filePath.isEmpty());
fileSystemWatcher()->removePath(filePath);
s_shaderByFilePath.remove(filePath);
const auto affectedPrograms = s_programsByShader.values(shader);
s_programsByShader.remove(shader);
// disconnect from all programs that have no file associated shaders anymore...
for (QOpenGLShaderProgram * program : affectedPrograms)
if (s_programsByShader.keys(program).isEmpty())
disconnect(
program,
&QOpenGLShaderProgram::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::programDestroyed);
}
void FileAssociatedShader::programDestroyed(QObject * object)
{
QOpenGLShaderProgram * program = static_cast<QOpenGLShaderProgram*>(object);
const auto affectedShaders = s_programsByShader.keys(program);
for (QOpenGLShader * shader : affectedShaders)
s_programsByShader.remove(shader, program);
for (QOpenGLShader * shader : affectedShaders)
if (s_programsByShader.values(shader).isEmpty())
{
const QString filePath(s_shaderByFilePath.key(shader));
assert(!filePath.isEmpty());
fileSystemWatcher()->removePath(filePath);
s_shaderByFilePath.remove(filePath);
disconnect(shader,
&QOpenGLShader::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::shaderDestroyed);
}
}
QList<QOpenGLShaderProgram *> FileAssociatedShader::process()
{
QList<QOpenGLShaderProgram *> programsWithInvalidatedUniforms;
while (!s_queue.isEmpty())
{
QString filePath = s_queue.first();
s_queue.removeFirst();
QOpenGLShader * shader(s_shaderByFilePath[filePath]);
assert(shader != nullptr);
qDebug() << "Recompiling" << filePath;
if (shader->isCompiled())
{
const QByteArray backup(shader->sourceCode());
// if current version works, use its source code as
// backup if new changes lead to uncompilable shader.
if (!shader->compileSourceFile(filePath))
shader->compileSourceCode(backup);
}
else
shader->compileSourceFile(filePath);
auto programs(s_programsByShader.values(shader));
assert(!programs.isEmpty());
programsWithInvalidatedUniforms << programs;
for (QOpenGLShaderProgram * program : programs)
if (!program->link())
qWarning() << program->log();
}
return programsWithInvalidatedUniforms;
}
<commit_msg>fixed FileAssociatedShader "incompatibility" with vim<commit_after>
#include <cassert>
#include <QFileSystemWatcher>
#include <QTextStream>
#include <QFileInfo>
#include <QStringList>
#include "FileAssociatedShader.h"
QMap<QString, QOpenGLShader *> FileAssociatedShader::s_shaderByFilePath;
QMultiMap<QOpenGLShader *, QOpenGLShaderProgram *> FileAssociatedShader::s_programsByShader;
FileAssociatedShader::FileAssociatedShader()
{}
FileAssociatedShader::~FileAssociatedShader()
{
s_shaderByFilePath.clear();
s_programsByShader.clear();
}
QOpenGLShader * FileAssociatedShader::getOrCreate(
QOpenGLShader::ShaderType type
, const QString & fileName
, QOpenGLShaderProgram & program)
{
QOpenGLShader * shader(nullptr);
QFileInfo fi(fileName);
if (!fi.exists())
{
qWarning() << fileName << " does not exist: shader is without source and associated file.";
return shader;
}
QString filePath(fi.absoluteFilePath());
if (s_shaderByFilePath.contains(filePath))
{
shader = s_shaderByFilePath[filePath];
}
else
{
instance()->addResourcePath(filePath);
shader = new QOpenGLShader(type);
shader->compileSourceFile(filePath);
connect(
shader,
&QOpenGLShader::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::shaderDestroyed);
s_shaderByFilePath.insert(filePath, shader);
}
if (!s_programsByShader.contains(shader, &program))
{
connect(
&program,
&QOpenGLShaderProgram::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::programDestroyed);
s_programsByShader.insert(shader, &program);
program.addShader(shader);
}
return shader;
}
void FileAssociatedShader::shaderDestroyed(QObject * object)
{
QOpenGLShader * shader = static_cast<QOpenGLShader*>(object);
const QString filePath(s_shaderByFilePath.key(shader));
assert(!filePath.isEmpty());
fileSystemWatcher()->removePath(filePath);
s_shaderByFilePath.remove(filePath);
const auto affectedPrograms = s_programsByShader.values(shader);
s_programsByShader.remove(shader);
// disconnect from all programs that have no file associated shaders anymore...
for (QOpenGLShaderProgram * program : affectedPrograms)
if (s_programsByShader.keys(program).isEmpty())
disconnect(
program,
&QOpenGLShaderProgram::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::programDestroyed);
}
void FileAssociatedShader::programDestroyed(QObject * object)
{
QOpenGLShaderProgram * program = static_cast<QOpenGLShaderProgram*>(object);
const auto affectedShaders = s_programsByShader.keys(program);
for (QOpenGLShader * shader : affectedShaders)
s_programsByShader.remove(shader, program);
for (QOpenGLShader * shader : affectedShaders)
if (s_programsByShader.values(shader).isEmpty())
{
const QString filePath(s_shaderByFilePath.key(shader));
assert(!filePath.isEmpty());
fileSystemWatcher()->removePath(filePath);
s_shaderByFilePath.remove(filePath);
disconnect(shader,
&QOpenGLShader::destroyed,
static_cast<FileAssociatedShader*>(instance()),
&FileAssociatedShader::shaderDestroyed);
}
}
QList<QOpenGLShaderProgram *> FileAssociatedShader::process()
{
QList<QOpenGLShaderProgram *> programsWithInvalidatedUniforms;
{
auto inst = static_cast<FileAssociatedShader*>(instance());
auto watchedFiles = inst->fileSystemWatcher()->files();
if (watchedFiles.count() != inst->s_shaderByFilePath.count())
{
for (auto path : inst->s_shaderByFilePath.keys())
{
if (!watchedFiles.contains(path) && QFileInfo(path).exists())
{
inst->m_fileSystemWatcher->addPath(path);
}
}
}
}
while (!s_queue.isEmpty())
{
QString filePath = s_queue.first();
s_queue.removeFirst();
QOpenGLShader * shader(s_shaderByFilePath[filePath]);
assert(shader != nullptr);
qDebug() << "Recompiling" << filePath;
if (shader->isCompiled())
{
const QByteArray backup(shader->sourceCode());
// if current version works, use its source code as
// backup if new changes lead to uncompilable shader.
if (!shader->compileSourceFile(filePath))
shader->compileSourceCode(backup);
}
else
shader->compileSourceFile(filePath);
auto programs(s_programsByShader.values(shader));
assert(!programs.isEmpty());
programsWithInvalidatedUniforms << programs;
for (QOpenGLShaderProgram * program : programs)
if (!program->link())
qWarning() << program->log();
}
return programsWithInvalidatedUniforms;
}
<|endoftext|> |
<commit_before><commit_msg>Marking rejected satellites with a negative id is a bad idea.<commit_after><|endoftext|> |
<commit_before><commit_msg>JO:fin journée vendredi<commit_after><|endoftext|> |
<commit_before>//===--- RequestedInformation.cpp - Requested Information Utilities ---===//
//
// This file is part of the Election Method Mathematics Application (EMMA) project.
//
// Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors
// Licensed under the GNU Affero General Public License, version 3.0.
//
// See the file called "LICENSE" included with this distribution for license information.
//
//===----------------------------------------------------------------------===//
//
// Functionality related to determining requested information.
// Analyzes information passed to the application and determines
// how the application should act.
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include "RequestedInformation.h"
#include "docopt/docopt.h"
namespace RequestedInformation {
typedef std::map<std::string, docopt::value> RawParsedOptions;
// Parses given options; `argc` and `argv` are the arguments
// from `main()`.
RawParsedOptions parseOptions(int argc, char **argv);
// Determines the mode in which to run based on the parsed
// options
void determineMode();
// Determines the statistics to collect based on the parsed
// options
void determineStatisticsToCollect();
void determine(int argc, char **argv) {
std::cout << "determine what is requested from simulations" << std::endl;
parseOptions(argc, argv);
determineMode();
determineStatisticsToCollect();
}
void determineMode() {
std::cout << "\tdetermine the mode to run in based on such parsing" << std::endl;
}
void determineStatisticsToCollect() {
std::cout << "\tdetermine what statistics to collect based on such parsing" << std::endl;
}
RawParsedOptions parseOptions(int argc, char **argv) {
const std::string usage =
R"(Usage:
emma (-h | --help)
emma options...
Options:
-h --help Show this screen.
--use-seed=<#> The seed to pass to the PRNG function [default: a number representing the current time].
--number-of-elections=<#> Number of elections to simulate [default: 1].
--number-of-candidates=<#> Number of Candidates in each election [default: 3].
--number-of-voters=<#> Number of Voters in each election [default: 64].
--check-condorcet-agreement=yes|no Check each method for agreement with the Condorcet Candidate [default: yes].
--check-true-condorcet-agreement=<yes|no> Check each method for agreement with the True Condorcet Candidate [default: yes].
--test Perform diagnostic testing.
--verbose Activate verbosity.
)";
RawParsedOptions raw_options = docopt::docopt(usage,
{ argv + 1, argv + argc },
true);
if (raw_options["--verbose"].asLong() == 1) {
std::cout << "parsing given options: success" << std::endl;
}
return raw_options;
}
}
<commit_msg>Distributing the parsed option information<commit_after>//===--- RequestedInformation.cpp - Requested Information Utilities ---===//
//
// This file is part of the Election Method Mathematics Application (EMMA) project.
//
// Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors
// Licensed under the GNU Affero General Public License, version 3.0.
//
// See the file called "LICENSE" included with this distribution for license information.
//
//===----------------------------------------------------------------------===//
//
// Functionality related to determining requested information.
// Analyzes information passed to the application and determines
// how the application should act.
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include "RequestedInformation.h"
#include "docopt/docopt.h"
namespace RequestedInformation {
typedef std::map<std::string, docopt::value> RawParsedOptions;
// Parses given options; `argc` and `argv` are the arguments
// from `main()`.
RawParsedOptions parseOptions(int argc, char **argv);
// Determines the mode in which to run based on the parsed
// options
void determineMode(RawParsedOptions raw_parsed_options);
// Determines the statistics to collect based on the parsed
// options
void determineStatisticsToCollect(RawParsedOptions raw_parsed_options);
void determine(int argc, char **argv) {
std::cout << "determine what is requested from simulations" << std::endl;
RawParsedOptions raw_options = parseOptions(argc, argv);
determineMode(raw_options);
determineStatisticsToCollect();
}
void determineMode(RawParsedOptions raw_parsed_options) {
std::cout << "\tdetermine the mode to run in based on such parsing" << std::endl;
}
void determineStatisticsToCollect(RawParsedOptions raw_parsed_options) {
std::cout << "\tdetermine what statistics to collect based on such parsing" << std::endl;
}
RawParsedOptions parseOptions(int argc, char **argv) {
const std::string usage =
R"(Usage:
emma (-h | --help)
emma options...
Options:
-h --help Show this screen.
--use-seed=<#> The seed to pass to the PRNG function [default: a number representing the current time].
--number-of-elections=<#> Number of elections to simulate [default: 1].
--number-of-candidates=<#> Number of Candidates in each election [default: 3].
--number-of-voters=<#> Number of Voters in each election [default: 64].
--check-condorcet-agreement=yes|no Check each method for agreement with the Condorcet Candidate [default: yes].
--check-true-condorcet-agreement=<yes|no> Check each method for agreement with the True Condorcet Candidate [default: yes].
--test Perform diagnostic testing.
--verbose Activate verbosity.
)";
RawParsedOptions raw_options = docopt::docopt(usage,
{ argv + 1, argv + argc },
true);
if (raw_options["--verbose"].asLong() == 1) {
std::cout << "parsing given options: success" << std::endl;
}
return raw_options;
}
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* Variable.tcc : implement long template functions
*
* Created on: Jan 31, 2019
* Author: William F Godoy
*/
#ifndef ADIOS2_CORE_VARIABLE_TCC_
#define ADIOS2_CORE_VARIABLE_TCC_
#include "Variable.h"
#include "adios2/core/Engine.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace core
{
template <class T>
Dims Variable<T>::DoShape(const size_t step) const
{
if (m_DebugMode)
{
if (!m_FirstStreamingStep && step != DefaultSizeT)
{
throw std::invalid_argument("ERROR: can't pass a step input in "
"streaming (BeginStep/EndStep)"
"mode for variable " +
m_Name +
", in call to Variable<T>::Shape\n");
}
}
if (m_FirstStreamingStep && step == DefaultSizeT)
{
return m_Shape;
}
if (m_Engine != nullptr && m_ShapeID == ShapeID::GlobalArray)
{
const size_t stepInput =
!m_FirstStreamingStep ? m_Engine->CurrentStep() : step;
const std::vector<typename Variable<T>::Info> blocksInfo =
m_Engine->BlocksInfo<T>(*this, stepInput);
if (blocksInfo.size() == 0)
{
return Dims();
}
if (blocksInfo.front().Shape.size() == 1 &&
blocksInfo.front().Shape.front() == LocalValueDim)
{
return Dims{blocksInfo.size()};
}
return blocksInfo.front().Shape;
}
return m_Shape;
}
template <class T>
std::pair<T, T> Variable<T>::DoMinMax(const size_t step) const
{
if (m_DebugMode && !m_FirstStreamingStep && step != DefaultSizeT)
{
throw std::invalid_argument(
"ERROR: can't pass a step input in streaming (BeginStep/EndStep)"
"mode for variable " +
m_Name + ", in call to Variable<T>:: Min Max or MinMax\n");
}
std::pair<T, T> minMax;
minMax.first = {};
minMax.second = {};
if (m_Engine != nullptr && !m_FirstStreamingStep)
{
const size_t stepInput =
(step == DefaultSizeT) ? m_Engine->CurrentStep() : step;
const std::vector<typename Variable<T>::Info> blocksInfo =
m_Engine->BlocksInfo<T>(*this, stepInput);
if (blocksInfo.size() == 0)
{
return minMax;
}
if (m_ShapeID == ShapeID::LocalArray)
{
if (m_DebugMode && m_BlockID >= blocksInfo.size())
{
throw std::invalid_argument(
"ERROR: BlockID " + std::to_string(m_BlockID) +
" does not exist for LocalArray variable " + m_Name +
", in call to MinMax, Min or Maxn");
}
minMax.first = blocksInfo[m_BlockID].Min;
minMax.second = blocksInfo[m_BlockID].Max;
return minMax;
}
const bool isValue =
((blocksInfo.front().Shape.size() == 1 &&
blocksInfo.front().Shape.front() == LocalValueDim) ||
m_ShapeID == ShapeID::GlobalValue)
? true
: false;
minMax.first =
isValue ? blocksInfo.front().Value : blocksInfo.front().Min;
minMax.second =
isValue ? blocksInfo.front().Value : blocksInfo.front().Max;
for (const typename Variable<T>::Info &blockInfo : blocksInfo)
{
const T minValue = isValue ? blockInfo.Value : blockInfo.Min;
if (helper::LessThan<T>(minValue, minMax.first))
{
minMax.first = minValue;
continue;
}
const T maxValue = isValue ? blockInfo.Value : blockInfo.Max;
if (helper::GreaterThan<T>(maxValue, minMax.second))
{
minMax.second = maxValue;
}
}
}
else
{
minMax.first = m_Min;
minMax.second = m_Max;
}
return minMax;
}
} // end namespace core
} // end namespace adios2
#endif /* ADIOS2_CORE_VARIABLE_TCC_ */
<commit_msg>Calculate min/max of blocks at read time correctly<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* Variable.tcc : implement long template functions
*
* Created on: Jan 31, 2019
* Author: William F Godoy
*/
#ifndef ADIOS2_CORE_VARIABLE_TCC_
#define ADIOS2_CORE_VARIABLE_TCC_
#include "Variable.h"
#include "adios2/core/Engine.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace core
{
template <class T>
Dims Variable<T>::DoShape(const size_t step) const
{
if (m_DebugMode)
{
if (!m_FirstStreamingStep && step != DefaultSizeT)
{
throw std::invalid_argument("ERROR: can't pass a step input in "
"streaming (BeginStep/EndStep)"
"mode for variable " +
m_Name +
", in call to Variable<T>::Shape\n");
}
}
if (m_FirstStreamingStep && step == DefaultSizeT)
{
return m_Shape;
}
if (m_Engine != nullptr && m_ShapeID == ShapeID::GlobalArray)
{
const size_t stepInput =
!m_FirstStreamingStep ? m_Engine->CurrentStep() : step;
const std::vector<typename Variable<T>::Info> blocksInfo =
m_Engine->BlocksInfo<T>(*this, stepInput);
if (blocksInfo.size() == 0)
{
return Dims();
}
if (blocksInfo.front().Shape.size() == 1 &&
blocksInfo.front().Shape.front() == LocalValueDim)
{
return Dims{blocksInfo.size()};
}
return blocksInfo.front().Shape;
}
return m_Shape;
}
template <class T>
std::pair<T, T> Variable<T>::DoMinMax(const size_t step) const
{
if (m_DebugMode && !m_FirstStreamingStep && step != DefaultSizeT)
{
throw std::invalid_argument(
"ERROR: can't pass a step input in streaming (BeginStep/EndStep)"
"mode for variable " +
m_Name + ", in call to Variable<T>:: Min Max or MinMax\n");
}
std::pair<T, T> minMax;
minMax.first = {};
minMax.second = {};
if (m_Engine != nullptr && !m_FirstStreamingStep)
{
const size_t stepInput =
(step == DefaultSizeT) ? m_Engine->CurrentStep() : step;
const std::vector<typename Variable<T>::Info> blocksInfo =
m_Engine->BlocksInfo<T>(*this, stepInput);
if (blocksInfo.size() == 0)
{
return minMax;
}
if (m_ShapeID == ShapeID::LocalArray)
{
if (m_DebugMode && m_BlockID >= blocksInfo.size())
{
throw std::invalid_argument(
"ERROR: BlockID " + std::to_string(m_BlockID) +
" does not exist for LocalArray variable " + m_Name +
", in call to MinMax, Min or Maxn");
}
minMax.first = blocksInfo[m_BlockID].Min;
minMax.second = blocksInfo[m_BlockID].Max;
return minMax;
}
const bool isValue =
((blocksInfo.front().Shape.size() == 1 &&
blocksInfo.front().Shape.front() == LocalValueDim) ||
m_ShapeID == ShapeID::GlobalValue)
? true
: false;
minMax.first =
isValue ? blocksInfo.front().Value : blocksInfo.front().Min;
minMax.second =
isValue ? blocksInfo.front().Value : blocksInfo.front().Max;
for (const typename Variable<T>::Info &blockInfo : blocksInfo)
{
const T minValue = isValue ? blockInfo.Value : blockInfo.Min;
if (helper::LessThan<T>(minValue, minMax.first))
{
minMax.first = minValue;
}
const T maxValue = isValue ? blockInfo.Value : blockInfo.Max;
if (helper::GreaterThan<T>(maxValue, minMax.second))
{
minMax.second = maxValue;
}
}
}
else
{
minMax.first = m_Min;
minMax.second = m_Max;
}
return minMax;
}
} // end namespace core
} // end namespace adios2
#endif /* ADIOS2_CORE_VARIABLE_TCC_ */
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
* Copyright (C) 2008 Charles Huet <packadal@gmail.com>
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
*
* 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 "item.h"
#include <QtGui/QMatrix4x4>
#include <core/debughelper.h>
#include "mesh.h"
#include "camera.h"
#include "frustrum.h"
#include "engine.h"
#include "math.h"
#include "materialinstance.h"
#include "material.h"
using namespace GluonGraphics;
class Item::ItemPrivate
{
public:
ItemPrivate() { materialInstance = 0; }
Mesh * mesh;
QMatrix4x4 transform;
MaterialInstance* materialInstance;
};
Item::Item(QObject * parent)
: QObject(parent),
d(new ItemPrivate)
{
d->materialInstance = Engine::instance()->material("default")->instance("default");
}
Item::~Item()
{
delete d;
}
Mesh*
Item::mesh()
{
return d->mesh;
}
QMatrix4x4
Item::transform()
{
return d->transform;
}
MaterialInstance*
Item::materialInstance()
{
return d->materialInstance;
}
void
Item::render()
{
Camera* activeCam = Engine::instance()->activeCamera();
#ifdef __GNUC__
#warning ToDo: Implement view frustum culling. After all, that is what that damn class is for... ;)
#endif
QMatrix4x4 modelViewProj = Math::calculateModelViewProj(d->transform, activeCam->viewMatrix(), activeCam->frustrum()->projectionMatrix());
d->materialInstance->bind();
d->materialInstance->setModelViewProjectionMatrix(modelViewProj);
d->mesh->render(modelViewProj);
d->materialInstance->release();
}
void
Item::setTransform( const QMatrix4x4 transform )
{
d->transform = transform;
}
void
Item::setMesh( Mesh* mesh )
{
d->mesh = mesh;
}
MaterialInstance*
Item::setMaterialInstance(MaterialInstance * instance)
{
d->materialInstance = instance;
}
#include "item.moc"
<commit_msg>Why were you returning MaterialInstance*?<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
* Copyright (C) 2008 Charles Huet <packadal@gmail.com>
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
*
* 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 "item.h"
#include <QtGui/QMatrix4x4>
#include <core/debughelper.h>
#include "mesh.h"
#include "camera.h"
#include "frustrum.h"
#include "engine.h"
#include "math.h"
#include "materialinstance.h"
#include "material.h"
using namespace GluonGraphics;
class Item::ItemPrivate
{
public:
ItemPrivate() { materialInstance = 0; }
Mesh * mesh;
QMatrix4x4 transform;
MaterialInstance* materialInstance;
};
Item::Item(QObject * parent)
: QObject(parent),
d(new ItemPrivate)
{
d->materialInstance = Engine::instance()->material("default")->instance("default");
}
Item::~Item()
{
delete d;
}
Mesh*
Item::mesh()
{
return d->mesh;
}
QMatrix4x4
Item::transform()
{
return d->transform;
}
MaterialInstance*
Item::materialInstance()
{
return d->materialInstance;
}
void
Item::render()
{
Camera* activeCam = Engine::instance()->activeCamera();
#ifdef __GNUC__
#warning ToDo: Implement view frustum culling. After all, that is what that damn class is for... ;)
#endif
QMatrix4x4 modelViewProj = Math::calculateModelViewProj(d->transform, activeCam->viewMatrix(), activeCam->frustrum()->projectionMatrix());
d->materialInstance->bind();
d->materialInstance->setModelViewProjectionMatrix(modelViewProj);
d->mesh->render();
d->materialInstance->release();
}
void
Item::setTransform( const QMatrix4x4 transform )
{
d->transform = transform;
}
void
Item::setMesh( Mesh* mesh )
{
d->mesh = mesh;
}
void
Item::setMaterialInstance(MaterialInstance * instance)
{
d->materialInstance = instance;
}
#include "item.moc"
<|endoftext|> |
<commit_before>#pragma once
// std
#include <vector>
// libraries
#include <nlohmann/json.hpp>
// project
#include "NeuralNetworkProperties.hpp"
#include "depthai-shared/common/DetectionNetworkType.hpp"
#include "depthai-shared/common/optional.hpp"
namespace dai {
/**
* Properties for DetectionNetwork
*/
struct DetectionNetworkProperties : NeuralNetworkProperties {
/// Generic Neural Network properties
DetectionNetworkType nnFamily;
float confidenceThreshold;
/// YOLO specific network properties
int classes;
int coordinates;
std::vector<float> anchors;
std::map<std::string, std::vector<int>> anchorMasks;
float iouThreshold;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
DetectionNetworkProperties, nnFamily, blobSize, blobUri, numFrames, numThreads, confidenceThreshold, classes, coordinates, anchors, anchorMasks, iouThreshold)
} // namespace dai
<commit_msg>Apply formatting<commit_after>#pragma once
// std
#include <vector>
// libraries
#include <nlohmann/json.hpp>
// project
#include "NeuralNetworkProperties.hpp"
#include "depthai-shared/common/DetectionNetworkType.hpp"
#include "depthai-shared/common/optional.hpp"
namespace dai {
/**
* Properties for DetectionNetwork
*/
struct DetectionNetworkProperties : NeuralNetworkProperties {
/// Generic Neural Network properties
DetectionNetworkType nnFamily;
float confidenceThreshold;
/// YOLO specific network properties
int classes;
int coordinates;
std::vector<float> anchors;
std::map<std::string, std::vector<int>> anchorMasks;
float iouThreshold;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(DetectionNetworkProperties,
nnFamily,
blobSize,
blobUri,
numFrames,
numThreads,
confidenceThreshold,
classes,
coordinates,
anchors,
anchorMasks,
iouThreshold)
} // namespace dai
<|endoftext|> |
<commit_before>// this thing is somehow required to be able to initialise OLE
#define _WIN32_DCOM
#include "../common/common.h"
#include "../common/CException.h"
#include "../graysvr/graysvr.h"
#include "threads.h"
// #include "mutex.h"
// number of exceptions after which we restart thread and think that the thread have gone in exceptioning loops
#define EXCEPTIONS_ALLOWED 10
// Normal Buffer
// SimpleMutex g_tmpStringMutex;
volatile long g_tmpStringIndex = 0;
char g_tmpStrings[THREAD_TSTRING_STORAGE][THREAD_STRING_LENGTH];
// TemporaryString Buffer
// SimpleMutex g_tmpTemporaryStringMutex;
volatile long g_tmpTemporaryStringIndex = 0;
char g_tmpTemporaryStringUsed[THREAD_STRING_STORAGE];
char g_tmpTemporaryStrings[THREAD_STRING_STORAGE][THREAD_STRING_LENGTH];
/**
* ThreadHolder
* NOTE: due to it is difficult to create a good sync on this level, instead of storying a list of threads
* we store an array and mark records being removed, which is absolutely thread-safe
**/
IThread *ThreadHolder::m_threads[MAX_THREADS];
int ThreadHolder::m_threadCount = 0;
bool ThreadHolder::m_inited = false;
IThread *ThreadHolder::current()
{
init();
#ifdef _WIN32
unsigned id = ::GetCurrentThreadId();
#else
unsigned id = (unsigned)pthread_self();
#endif
for( int i = 0; i < MAX_THREADS; i++ )
{
if( m_threads[i] != NULL )
{
if( m_threads[i]->getId() == id )
{
return m_threads[i];
}
}
}
return DummySphereThread::getInstance();
}
void ThreadHolder::push(IThread *thread)
{
init();
if( m_threadCount >= MAX_THREADS-1 )
{
throw new CException(LOGL_FATAL, 0, "Too many opened threads");
}
for( int i = 0; i < MAX_THREADS; i++ )
{
if( m_threads[i] == NULL )
{
m_threads[i] = thread;
m_threadCount++;
return;
}
}
throw new CException(LOGL_FATAL, 0, "Unable to find an empty slot for thread");
}
void ThreadHolder::pop(IThread *thread)
{
init();
if( m_threadCount <= 0 )
{
throw new CException(LOGL_ERROR, 0, "Trying to dequeue thread while no threads are active");
}
for( int i = 0; i < MAX_THREADS; i++ )
{
if( m_threads[i] != NULL )
{
if( m_threads[i]->getId() == thread->getId() )
{
m_threads[i] = NULL;
m_threadCount--;
return;
}
}
}
throw new CException(LOGL_ERROR, 0, "Unable to dequeue a thread (not registered)");
}
int ThreadHolder::getActiveThreads()
{
return m_threadCount;
}
void ThreadHolder::init()
{
if( !m_inited )
{
for( int i = 0; i < MAX_THREADS; i++ )
{
m_threads[i] = NULL;
}
memset(g_tmpStrings, 0, sizeof(g_tmpStrings));
memset(g_tmpTemporaryStringUsed, 0, sizeof(g_tmpTemporaryStringUsed));
memset(g_tmpTemporaryStrings, 0, sizeof(g_tmpTemporaryStrings));
m_inited = true;
}
}
/*
* AbstractThread
*/
int AbstractThread::m_threadsAvailable = 0;
AbstractThread::AbstractThread(const char *name, IThread::Priority priority)
{
if( AbstractThread::m_threadsAvailable == 0 )
{
// no threads were started before - initialise thread subsystem
#ifdef _WIN32
if( CoInitializeEx(NULL, COINIT_MULTITHREADED) != S_OK )
{
throw new CException(LOGL_FATAL, 0, "OLE is not available, threading model unimplementable");
}
#endif
AbstractThread::m_threadsAvailable++;
}
m_id = 0;
m_name = name;
m_handle = NULL;
m_hangCheck = 0;
m_priority = priority;
}
AbstractThread::~AbstractThread()
{
terminate();
AbstractThread::m_threadsAvailable--;
if( AbstractThread::m_threadsAvailable == 0 )
{
// all running threads have gone, the thread subsystem is no longer needed
#ifdef _WIN32
CoUninitialize();
#else
// No pthread equivalent
#endif
}
}
unsigned AbstractThread::getId()
{
return m_id;
}
const char *AbstractThread::getName()
{
return m_name;
}
void AbstractThread::start()
{
#ifdef _WIN32
m_handle = (spherethread_t) _beginthreadex(NULL, 0, &runner, this, 0, &m_id);
#else
// pthread_create doesn't return the new thread id, so we set it in runner?
if ( pthread_create( &m_handle, NULL, &runner, this ) )
{
m_handle = (spherethread_t) NULL;
throw new CException(LOGL_FATAL, 0, "Unable to spawn a new thread");
}
else
m_id = (unsigned) m_handle; //pthread_self() and m_handle should be the same
#endif
push(this);
}
void AbstractThread::terminate()
{
if( isActive() )
{
#ifdef _WIN32
if( getId() == ::GetCurrentThreadId() )
{
_endthreadex(0);
}
else
{
TerminateThread(m_handle, 0);
}
CloseHandle(m_handle);
#else
if( pthread_equal(m_handle,pthread_self()) )
{
pthread_exit(0);
}
else
{
pthread_cancel(m_handle); // IBM say it so
}
#endif
// Common things
pop(this);
m_id = 0;
m_handle = NULL;
}
}
void AbstractThread::run()
{
// is the very first since there is a possibility of something being altered there
onStart();
// detect a sleep period for thread depending on priority
int tickPeriod;
switch( m_priority )
{
case IThread::Idle:
tickPeriod = 1000;
break;
case IThread::Low:
tickPeriod = 200;
break;
case IThread::Normal:
tickPeriod = 100;
break;
case IThread::High:
tickPeriod = 50;
break;
case IThread::Highest:
tickPeriod = 25;
break;
case IThread::RealTime:
tickPeriod = 0;
break;
default:
throw new CException(LOGL_FATAL, 0, "Unable to determine thread priority");
}
int exceptions = 0;
bool lastWasException = false;
while( true )
{
bool gotException = false;
// report me being alive if I am being checked for status
if( m_hangCheck != 0 )
{
m_hangCheck = 0;
}
try
{
tick();
}
catch( CException e )
{
gotException = true;
// TODO: notify of exceptions
}
catch( ... )
{
gotException = true;
// TODO: notify of exceptions
}
if( gotException )
{
if( lastWasException )
{
exceptions++;
}
else
{
lastWasException = true;
exceptions = 0;
}
if( exceptions >= EXCEPTIONS_ALLOWED )
{
// a bad thing really happened. ALL previous EXCEPTIONS_ALLOWED ticks resulted in exception
// almost for sure we have looped somewhere and have no way to get out from this situation
// probably a thread restart can fix the problems
// but there is no real need to restart a thread, we will just simulate a thread restart,
// notifying a subclass like we have been just restarted, so it will restart it's operations
// TODO: notify the logger
onStart();
lastWasException = false;
}
}
else
{
lastWasException = false;
}
if( shouldExit() )
{
terminate();
}
Sleep(tickPeriod);
}
}
SPHERE_THREADENTRY_RETNTYPE AbstractThread::runner(void *callerThread)
{
AbstractThread *caller = (AbstractThread*)callerThread;
caller->run();
#ifdef _WIN32
_endthreadex(0);
#else
pthread_exit(0);
#endif
return 0;
}
bool AbstractThread::isActive()
{
return m_handle != NULL;
}
void AbstractThread::waitForClose()
{
int count = 150; // 15 seconds = 15000ms
while( isActive() && count-- )
{
Sleep(100);
}
terminate();
}
void AbstractThread::checkStuck()
{
if( isActive() )
{
if( m_hangCheck == 0 )
{
// initiate hang check
m_hangCheck = 0xDEAD;
}
else if( m_hangCheck == 0xDEAD )
{
// one time period was not answered, wait a bit more
m_hangCheck = 0xDEADDEADl;
// TODO:
//g_Log.Event(LOGL_CRIT, "'%s' thread seems being hang (frozen) at '%s'?\n", m_name, m_action);
}
else if( m_hangCheck == 0xDEADDEADl )
{
// TODO:
//g_Log.Event(LOGL_CRIT, "'%s' thread hang, restarting...\n", m_name);
terminate();
start();
}
}
}
void AbstractThread::onStart()
{
// empty. override if need in subclass
}
bool AbstractThread::shouldExit()
{
return false;
}
/*
* AbstractSphereThread
*/
AbstractSphereThread::AbstractSphereThread(const char *name, Priority priority)
: AbstractThread(name, priority)
{
}
// IMHO we need a lock on allocateBuffer and allocateStringBuffer
char *AbstractSphereThread::allocateBuffer()
{
// SimpleThreadLock stlBuffer(g_tmpStringMutex);
char * buffer = NULL;
g_tmpStringIndex++;
if( g_tmpStringIndex >= THREAD_TSTRING_STORAGE )
{
g_tmpStringIndex %= THREAD_TSTRING_STORAGE;
}
buffer = g_tmpStrings[g_tmpStringIndex];
*buffer = '\0';
return buffer;
}
char *AbstractSphereThread::allocateStringBuffer()
{
// SimpleThreadLock stlBuffer(g_tmpTemporaryStringMutex);
long initialPosition = g_tmpTemporaryStringIndex;
while( true )
{
long index = ++g_tmpTemporaryStringIndex;
if( g_tmpTemporaryStringIndex >= THREAD_STRING_STORAGE )
{
index = g_tmpTemporaryStringIndex %= THREAD_STRING_STORAGE;
}
if( g_tmpTemporaryStringUsed[index] == 0 )
{
char *buffer = g_tmpTemporaryStrings[index];
*buffer = '\0';
return buffer;
}
// a protection against deadlock. All string buffers are marked as being used somewhere, so we
// have few possibilities (the case shows that we have a bug and temporary strings used not such):
// a) return NULL and wait for exceptions in the program
// b) allocate a string from a heap
if( initialPosition == index )
{
// but the best is to throw an exception to give better formed information for end users
// rather than access violations
DEBUG_WARN(( "Thread temporary string buffer is full.\n" ));
throw new CException(LOGL_FATAL, 0, "Thread temporary string buffer is full");
}
}
}
String AbstractSphereThread::allocateString()
{
TemporaryString s(allocateStringBuffer(), &g_tmpTemporaryStringUsed[g_tmpTemporaryStringIndex]);
return s;
}
void AbstractSphereThread::allocateString(TemporaryString &string)
{
string.init(allocateStringBuffer(), &g_tmpTemporaryStringUsed[g_tmpTemporaryStringIndex]);
}
bool AbstractSphereThread::shouldExit()
{
if( g_Serv.m_iModeCode == SERVMODE_Exiting )
{
return true;
}
return false;
}
/*
* DummySphereThread
*/
DummySphereThread *DummySphereThread::instance = NULL;
DummySphereThread::DummySphereThread()
: AbstractSphereThread("dummy", IThread::Normal)
{
}
DummySphereThread *DummySphereThread::getInstance()
{
if( instance == NULL )
{
instance = new DummySphereThread();
}
return instance;
}
void DummySphereThread::tick()
{
}
<commit_msg>_USESTRINGMUTEX For string mutex<commit_after>// this thing is somehow required to be able to initialise OLE
#define _WIN32_DCOM
#include "../common/common.h"
#include "../common/CException.h"
#include "../graysvr/graysvr.h"
#include "threads.h"
// #include "mutex.h"
// number of exceptions after which we restart thread and think that the thread have gone in exceptioning loops
#define EXCEPTIONS_ALLOWED 10
// Normal Buffer
#ifdef _USESTRINGMUTEX
SimpleMutex g_tmpStringMutex;
#endif
volatile long g_tmpStringIndex = 0;
char g_tmpStrings[THREAD_TSTRING_STORAGE][THREAD_STRING_LENGTH];
// TemporaryString Buffer
#ifdef _USESTRINGMUTEX
SimpleMutex g_tmpTemporaryStringMutex;
#endif
volatile long g_tmpTemporaryStringIndex = 0;
char g_tmpTemporaryStringUsed[THREAD_STRING_STORAGE];
char g_tmpTemporaryStrings[THREAD_STRING_STORAGE][THREAD_STRING_LENGTH];
/**
* ThreadHolder
* NOTE: due to it is difficult to create a good sync on this level, instead of storying a list of threads
* we store an array and mark records being removed, which is absolutely thread-safe
**/
IThread *ThreadHolder::m_threads[MAX_THREADS];
int ThreadHolder::m_threadCount = 0;
bool ThreadHolder::m_inited = false;
IThread *ThreadHolder::current()
{
init();
#ifdef _WIN32
unsigned id = ::GetCurrentThreadId();
#else
unsigned id = (unsigned)pthread_self();
#endif
for( int i = 0; i < MAX_THREADS; i++ )
{
if( m_threads[i] != NULL )
{
if( m_threads[i]->getId() == id )
{
return m_threads[i];
}
}
}
return DummySphereThread::getInstance();
}
void ThreadHolder::push(IThread *thread)
{
init();
if( m_threadCount >= MAX_THREADS-1 )
{
throw new CException(LOGL_FATAL, 0, "Too many opened threads");
}
for( int i = 0; i < MAX_THREADS; i++ )
{
if( m_threads[i] == NULL )
{
m_threads[i] = thread;
m_threadCount++;
return;
}
}
throw new CException(LOGL_FATAL, 0, "Unable to find an empty slot for thread");
}
void ThreadHolder::pop(IThread *thread)
{
init();
if( m_threadCount <= 0 )
{
throw new CException(LOGL_ERROR, 0, "Trying to dequeue thread while no threads are active");
}
for( int i = 0; i < MAX_THREADS; i++ )
{
if( m_threads[i] != NULL )
{
if( m_threads[i]->getId() == thread->getId() )
{
m_threads[i] = NULL;
m_threadCount--;
return;
}
}
}
throw new CException(LOGL_ERROR, 0, "Unable to dequeue a thread (not registered)");
}
int ThreadHolder::getActiveThreads()
{
return m_threadCount;
}
void ThreadHolder::init()
{
if( !m_inited )
{
for( int i = 0; i < MAX_THREADS; i++ )
{
m_threads[i] = NULL;
}
memset(g_tmpStrings, 0, sizeof(g_tmpStrings));
memset(g_tmpTemporaryStringUsed, 0, sizeof(g_tmpTemporaryStringUsed));
memset(g_tmpTemporaryStrings, 0, sizeof(g_tmpTemporaryStrings));
m_inited = true;
}
}
/*
* AbstractThread
*/
int AbstractThread::m_threadsAvailable = 0;
AbstractThread::AbstractThread(const char *name, IThread::Priority priority)
{
if( AbstractThread::m_threadsAvailable == 0 )
{
// no threads were started before - initialise thread subsystem
#ifdef _WIN32
if( CoInitializeEx(NULL, COINIT_MULTITHREADED) != S_OK )
{
throw new CException(LOGL_FATAL, 0, "OLE is not available, threading model unimplementable");
}
#endif
AbstractThread::m_threadsAvailable++;
}
m_id = 0;
m_name = name;
m_handle = NULL;
m_hangCheck = 0;
m_priority = priority;
}
AbstractThread::~AbstractThread()
{
terminate();
AbstractThread::m_threadsAvailable--;
if( AbstractThread::m_threadsAvailable == 0 )
{
// all running threads have gone, the thread subsystem is no longer needed
#ifdef _WIN32
CoUninitialize();
#else
// No pthread equivalent
#endif
}
}
unsigned AbstractThread::getId()
{
return m_id;
}
const char *AbstractThread::getName()
{
return m_name;
}
void AbstractThread::start()
{
#ifdef _WIN32
m_handle = (spherethread_t) _beginthreadex(NULL, 0, &runner, this, 0, &m_id);
#else
// pthread_create doesn't return the new thread id, so we set it in runner?
if ( pthread_create( &m_handle, NULL, &runner, this ) )
{
m_handle = (spherethread_t) NULL;
throw new CException(LOGL_FATAL, 0, "Unable to spawn a new thread");
}
else
m_id = (unsigned) m_handle; //pthread_self() and m_handle should be the same
#endif
push(this);
}
void AbstractThread::terminate()
{
if( isActive() )
{
#ifdef _WIN32
if( getId() == ::GetCurrentThreadId() )
{
_endthreadex(0);
}
else
{
TerminateThread(m_handle, 0);
}
CloseHandle(m_handle);
#else
if( pthread_equal(m_handle,pthread_self()) )
{
pthread_exit(0);
}
else
{
pthread_cancel(m_handle); // IBM say it so
}
#endif
// Common things
pop(this);
m_id = 0;
m_handle = NULL;
}
}
void AbstractThread::run()
{
// is the very first since there is a possibility of something being altered there
onStart();
// detect a sleep period for thread depending on priority
int tickPeriod;
switch( m_priority )
{
case IThread::Idle:
tickPeriod = 1000;
break;
case IThread::Low:
tickPeriod = 200;
break;
case IThread::Normal:
tickPeriod = 100;
break;
case IThread::High:
tickPeriod = 50;
break;
case IThread::Highest:
tickPeriod = 25;
break;
case IThread::RealTime:
tickPeriod = 0;
break;
default:
throw new CException(LOGL_FATAL, 0, "Unable to determine thread priority");
}
int exceptions = 0;
bool lastWasException = false;
while( true )
{
bool gotException = false;
// report me being alive if I am being checked for status
if( m_hangCheck != 0 )
{
m_hangCheck = 0;
}
try
{
tick();
}
catch( CException e )
{
gotException = true;
// TODO: notify of exceptions
}
catch( ... )
{
gotException = true;
// TODO: notify of exceptions
}
if( gotException )
{
if( lastWasException )
{
exceptions++;
}
else
{
lastWasException = true;
exceptions = 0;
}
if( exceptions >= EXCEPTIONS_ALLOWED )
{
// a bad thing really happened. ALL previous EXCEPTIONS_ALLOWED ticks resulted in exception
// almost for sure we have looped somewhere and have no way to get out from this situation
// probably a thread restart can fix the problems
// but there is no real need to restart a thread, we will just simulate a thread restart,
// notifying a subclass like we have been just restarted, so it will restart it's operations
// TODO: notify the logger
onStart();
lastWasException = false;
}
}
else
{
lastWasException = false;
}
if( shouldExit() )
{
terminate();
}
Sleep(tickPeriod);
}
}
SPHERE_THREADENTRY_RETNTYPE AbstractThread::runner(void *callerThread)
{
AbstractThread *caller = (AbstractThread*)callerThread;
caller->run();
#ifdef _WIN32
_endthreadex(0);
#else
pthread_exit(0);
#endif
return 0;
}
bool AbstractThread::isActive()
{
return m_handle != NULL;
}
void AbstractThread::waitForClose()
{
int count = 150; // 15 seconds = 15000ms
while( isActive() && count-- )
{
Sleep(100);
}
terminate();
}
void AbstractThread::checkStuck()
{
if( isActive() )
{
if( m_hangCheck == 0 )
{
// initiate hang check
m_hangCheck = 0xDEAD;
}
else if( m_hangCheck == 0xDEAD )
{
// one time period was not answered, wait a bit more
m_hangCheck = 0xDEADDEADl;
// TODO:
//g_Log.Event(LOGL_CRIT, "'%s' thread seems being hang (frozen) at '%s'?\n", m_name, m_action);
}
else if( m_hangCheck == 0xDEADDEADl )
{
// TODO:
//g_Log.Event(LOGL_CRIT, "'%s' thread hang, restarting...\n", m_name);
terminate();
start();
}
}
}
void AbstractThread::onStart()
{
// empty. override if need in subclass
}
bool AbstractThread::shouldExit()
{
return false;
}
/*
* AbstractSphereThread
*/
AbstractSphereThread::AbstractSphereThread(const char *name, Priority priority)
: AbstractThread(name, priority)
{
}
// IMHO we need a lock on allocateBuffer and allocateStringBuffer
char *AbstractSphereThread::allocateBuffer()
{
#ifdef _USESTRINGMUTEX
SimpleThreadLock stlBuffer(g_tmpStringMutex);
#endif
char * buffer = NULL;
g_tmpStringIndex++;
if( g_tmpStringIndex >= THREAD_TSTRING_STORAGE )
{
g_tmpStringIndex %= THREAD_TSTRING_STORAGE;
}
buffer = g_tmpStrings[g_tmpStringIndex];
*buffer = '\0';
return buffer;
}
char *AbstractSphereThread::allocateStringBuffer()
{
long initialPosition = g_tmpTemporaryStringIndex;
while( true )
{
long index = ++g_tmpTemporaryStringIndex;
if( g_tmpTemporaryStringIndex >= THREAD_STRING_STORAGE )
{
index = g_tmpTemporaryStringIndex %= THREAD_STRING_STORAGE;
}
if( g_tmpTemporaryStringUsed[index] == 0 )
{
char *buffer = g_tmpTemporaryStrings[index];
*buffer = '\0';
return buffer;
}
// a protection against deadlock. All string buffers are marked as being used somewhere, so we
// have few possibilities (the case shows that we have a bug and temporary strings used not such):
// a) return NULL and wait for exceptions in the program
// b) allocate a string from a heap
if( initialPosition == index )
{
// but the best is to throw an exception to give better formed information for end users
// rather than access violations
DEBUG_WARN(( "Thread temporary string buffer is full.\n" ));
throw new CException(LOGL_FATAL, 0, "Thread temporary string buffer is full");
}
}
}
String AbstractSphereThread::allocateString()
{
#ifdef _USESTRINGMUTEX
SimpleThreadLock stlBuffer(g_tmpTemporaryStringMutex);
#endif
TemporaryString s(allocateStringBuffer(), &g_tmpTemporaryStringUsed[g_tmpTemporaryStringIndex]);
return s;
}
void AbstractSphereThread::allocateString(TemporaryString &string)
{
#ifdef _USESTRINGMUTEX
SimpleThreadLock stlBuffer(g_tmpTemporaryStringMutex);
#endif
string.init(allocateStringBuffer(), &g_tmpTemporaryStringUsed[g_tmpTemporaryStringIndex]);
}
bool AbstractSphereThread::shouldExit()
{
if( g_Serv.m_iModeCode == SERVMODE_Exiting )
{
return true;
}
return false;
}
/*
* DummySphereThread
*/
DummySphereThread *DummySphereThread::instance = NULL;
DummySphereThread::DummySphereThread()
: AbstractSphereThread("dummy", IThread::Normal)
{
}
DummySphereThread *DummySphereThread::getInstance()
{
if( instance == NULL )
{
instance = new DummySphereThread();
}
return instance;
}
void DummySphereThread::tick()
{
}
<|endoftext|> |
<commit_before>/*
* converts meshalyzer mesh files to vtk unstructured data
*/
#include <cmath>
#include <fstream>
#include <ios>
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <boost/tuple/tuple.hpp>
#include "vtkXMLUnstructuredGridReader.h"
#include "vtkXMLUnstructuredGridWriter.h"
#include "vtkXMLPUnstructuredGridWriter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkGenericGeometryFilter.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkConfigure.h"
#include "vtkFloatArray.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
using namespace boost;
namespace po = boost::program_options;
/**
* Reads a .pts file and adds the points to the given grid
*/
void create_points(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .tris file and adds the triangles to the given grid
*/
void create_tris(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .elem file and adds the triangles to the given grid
*/
void create_elem(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .cnnx file and adds the lines to the given grid;
*/
void create_lines(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .lon file and adds the vectors to the given elements;
*/
void create_vectors(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
int main(int argc, char *argv[])
{
//Process command line
//set up possible options
po::options_description desc("Command line arguments");
desc.add_options()
("help", "produce help message")
("pts", po::value<std::string>(), "name of input pts file")
("tris", po::value<std::string>(), "name of input tris file")
("elem", po::value<std::string>(), "name of input elem file")
("cnnx", po::value<std::string>(), "name of input cnnx file")
("lon", po::value<std::string>(), "name of input lon file")
("output", po::value<std::string>(), "name of output file")
;
//Parse command line
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return EXIT_FAILURE;
}
if (!vm.count("pts"))
{
std::cout << "Input was not set.\n";
return EXIT_FAILURE;
}
if (!vm.count("output"))
{
std::cout << "Output was not set.\n";
return EXIT_FAILURE;
}
//Create vtk data structure and writer
vtkSmartPointer<vtkUnstructuredGrid> grid = vtkSmartPointer<vtkUnstructuredGrid>::New();
create_points(vm["pts"].as<std::string>(),
grid);
if(vm.count("tris"))
{
create_tris(vm["tris"].as<std::string>(),
grid);
}
if(vm.count("elem"))
{
create_elem(vm["elem"].as<std::string>(),
grid);
}
if(vm.count("cnnx"))
{
create_lines(vm["cnnx"].as<std::string>(),
grid);
}
if(vm.count("cnnx"))
{
create_vectors(vm["lon"].as<std::string>(),
grid);
}
vtkXMLUnstructuredGridWriter* writer= vtkXMLUnstructuredGridWriter::New();
writer->SetInput(grid);
//writer->SetDataModeToAscii();
writer->SetFileName(vm["output"].as<std::string>().c_str());
writer->Write();
writer->Delete();
}
//
//
//
void create_points(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//parse file and simultaneously output to vtk
std::ifstream pts_file(file_name.c_str());
if (!pts_file)
{
std::cerr << "Failed to read pts file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(pts_file, line); //Skip over the first line
//Create Vertices
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
unsigned vertex_index = 0;
while(std::getline(pts_file, line))
{
double coords[3];
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> coords[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> coords[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> coords[2];
points->InsertPoint(vertex_index, coords);
++vertex_index;
}
grid->SetPoints(points);
}
//
//
//
void create_tris(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create tris
std::ifstream tris_file(file_name.c_str());
if (!tris_file)
{
std::cerr << "Failed to read tris file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(tris_file, line); //Skip over the first line
//Create Vertices
unsigned tri_index = 0;
while(std::getline(tris_file, line))
{
std::vector<unsigned int> conn(3);
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> conn[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> conn[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> conn[2];
++beg;
vtkIdList *pts = vtkIdList::New();
pts->SetNumberOfIds(3);
for(unsigned int i=0;i<conn.size();++i)
{
pts->SetId(i,conn[i]);
}
grid->InsertNextCell(VTK_TRIANGLE,pts);
pts->Delete();
++tri_index;
}
}
//
//
//
void create_elem(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create elem
std::ifstream elem_file(file_name.c_str());
if (!elem_file)
{
std::cerr << "Failed to read elem file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(elem_file, line); //Skip over the first line
//Create Vertices
unsigned elem_index = 0;
while(std::getline(elem_file, line))
{
std::vector<unsigned int> conn(4);
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
++beg; //Throw away Tt first entry
std::istringstream iss(*beg);
iss >> conn[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> conn[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> conn[2];
++beg;
std::istringstream iss4(*beg);
iss4 >> conn[3];
++beg;
vtkIdList *pts = vtkIdList::New();
pts->SetNumberOfIds(4);
for(unsigned int i=0;i<conn.size();++i)
{
//std::cout << i << " " << conn[i] << std::endl;
pts->SetId(i,conn[i]);
//std::cout << pts->GetId(i) << std::endl;
}
grid->InsertNextCell(VTK_TETRA,pts);
pts->Delete();
++elem_index;
}
}
/**
* Reads a .cnnx file and adds the lines to the given grid;
*/
void create_lines(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create tris
std::ifstream cnnx_file(file_name.c_str());
if (!cnnx_file)
{
std::cerr << "Failed to read cnnx file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(cnnx_file, line); //Skip over the first line
//Create Vertices
unsigned cnnx_index = 0;
while(std::getline(cnnx_file, line))
{
std::vector<unsigned int> conn(2);
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> conn[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> conn[1];
++beg;
vtkIdList *pts = vtkIdList::New();
pts->SetNumberOfIds(2);
for(unsigned int i=0;i<conn.size();++i)
{
pts->SetId(i,conn[i]);
}
grid->InsertNextCell(VTK_LINE,pts);
pts->Delete();
++cnnx_index;
}
}
/**
* Reads a .lon file and adds the vectors to the given elements;
* Code assumes that the file has a first line to ignore.
*/
void create_vectors(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create tris
std::ifstream lon_file(file_name.c_str());
if (!lon_file)
{
std::cerr << "Failed to read lon file" << std::endl;
abort();
}
//
//Read the pts file
std::string line;
std::getline(lon_file, line); //Skip over the first line
// quick and dirty way to check if there is a one-line header
// if there is, ignore it
// if (found!=string::npos)
//
vtkCellData* cellData = grid->GetCellData();
vtkSmartPointer< vtkFloatArray > vectors = vtkSmartPointer< vtkFloatArray >::New();
vectors->SetName("lon");
cellData->AddArray(vectors);
//Create Vertices
while(std::getline(lon_file, line))
{
double lon[3];
// >> lon[0] >> lon[1] >> lon[2];
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> lon[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> lon[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> lon[2];
++beg;
vectors->InsertNextTuple(lon);
//
// vtkIdList *pts = vtkIdList::New();
// pts->SetNumberOfIds(2);
//
// for(unsigned int i=0;i<lon.size();++i)
// {
// pts->SetId(i,lon[i]);
// }
//
// grid->InsertNextCell(VTK_LINE,pts);
// pts->Delete();
}
}
<commit_msg>Fixed bugs in convert_carp_to_vtk.cpp<commit_after>/*
* converts meshalyzer mesh files to vtk unstructured data
*/
#include <cmath>
#include <fstream>
#include <ios>
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <boost/tuple/tuple.hpp>
#include "vtkXMLUnstructuredGridReader.h"
#include "vtkXMLUnstructuredGridWriter.h"
#include "vtkXMLPUnstructuredGridWriter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkGenericGeometryFilter.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkConfigure.h"
#include "vtkFloatArray.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
using namespace boost;
namespace po = boost::program_options;
/**
* Reads a .pts file and adds the points to the given grid
*/
void create_points(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .tris file and adds the triangles to the given grid
*/
void create_tris(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .elem file and adds the triangles to the given grid
*/
void create_elem(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .cnnx file and adds the lines to the given grid;
*/
void create_lines(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
/**
* Reads a .lon file and adds the vectors to the given elements;
*/
void create_vectors(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid);
int main(int argc, char *argv[])
{
//Process command line
//set up possible options
po::options_description desc("Command line arguments");
desc.add_options()
("help", "produce help message")
("pts", po::value<std::string>(), "name of input pts file")
("tris", po::value<std::string>(), "name of input tris file")
("elem", po::value<std::string>(), "name of input elem file")
("cnnx", po::value<std::string>(), "name of input cnnx file")
("lon", po::value<std::string>(), "name of input lon file")
("output", po::value<std::string>(), "name of output file")
;
//Parse command line
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return EXIT_FAILURE;
}
if (!vm.count("pts"))
{
std::cout << "Input was not set.\n";
return EXIT_FAILURE;
}
if (!vm.count("output"))
{
std::cout << "Output was not set.\n";
return EXIT_FAILURE;
}
//Create vtk data structure and writer
vtkSmartPointer<vtkUnstructuredGrid> grid = vtkSmartPointer<vtkUnstructuredGrid>::New();
create_points(vm["pts"].as<std::string>(),
grid);
if(vm.count("tris"))
{
create_tris(vm["tris"].as<std::string>(),
grid);
}
if(vm.count("elem"))
{
create_elem(vm["elem"].as<std::string>(),
grid);
}
if(vm.count("cnnx"))
{
create_lines(vm["cnnx"].as<std::string>(),
grid);
}
if(vm.count("lon"))
{
create_vectors(vm["lon"].as<std::string>(),
grid);
}
vtkXMLUnstructuredGridWriter* writer= vtkXMLUnstructuredGridWriter::New();
writer->SetInput(grid);
//writer->SetDataModeToAscii();
writer->SetFileName(vm["output"].as<std::string>().c_str());
writer->Write();
writer->Delete();
}
//
//
//
void create_points(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//parse file and simultaneously output to vtk
std::ifstream pts_file(file_name.c_str());
if (!pts_file)
{
std::cerr << "Failed to read pts file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(pts_file, line); //Skip over the first line
//Create Vertices
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
unsigned vertex_index = 0;
while(std::getline(pts_file, line))
{
double coords[3];
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> coords[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> coords[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> coords[2];
points->InsertPoint(vertex_index, coords);
++vertex_index;
}
grid->SetPoints(points);
}
//
//
//
void create_tris(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create tris
std::ifstream tris_file(file_name.c_str());
if (!tris_file)
{
std::cerr << "Failed to read tris file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(tris_file, line); //Skip over the first line
//Create Vertices
unsigned tri_index = 0;
while(std::getline(tris_file, line))
{
std::vector<unsigned int> conn(3);
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> conn[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> conn[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> conn[2];
++beg;
vtkIdList *pts = vtkIdList::New();
pts->SetNumberOfIds(3);
for(unsigned int i=0;i<conn.size();++i)
{
pts->SetId(i,conn[i]);
}
grid->InsertNextCell(VTK_TRIANGLE,pts);
pts->Delete();
++tri_index;
}
}
//
//
//
void create_elem(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create elem
std::ifstream elem_file(file_name.c_str());
if (!elem_file)
{
std::cerr << "Failed to read elem file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(elem_file, line); //Skip over the first line
//Create Vertices
unsigned elem_index = 0;
while(std::getline(elem_file, line))
{
std::vector<unsigned int> conn(4);
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
++beg; //Throw away Tt first entry
std::istringstream iss(*beg);
iss >> conn[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> conn[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> conn[2];
++beg;
std::istringstream iss4(*beg);
iss4 >> conn[3];
++beg;
vtkIdList *pts = vtkIdList::New();
pts->SetNumberOfIds(4);
for(unsigned int i=0;i<conn.size();++i)
{
//std::cout << i << " " << conn[i] << std::endl;
pts->SetId(i,conn[i]);
//std::cout << pts->GetId(i) << std::endl;
}
grid->InsertNextCell(VTK_TETRA,pts);
pts->Delete();
++elem_index;
}
}
/**
* Reads a .cnnx file and adds the lines to the given grid;
*/
void create_lines(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create tris
std::ifstream cnnx_file(file_name.c_str());
if (!cnnx_file)
{
std::cerr << "Failed to read cnnx file" << std::endl;
abort();
}
//Read the pts file
std::string line;
std::getline(cnnx_file, line); //Skip over the first line
//Create Vertices
unsigned cnnx_index = 0;
while(std::getline(cnnx_file, line))
{
std::vector<unsigned int> conn(2);
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> conn[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> conn[1];
++beg;
vtkIdList *pts = vtkIdList::New();
pts->SetNumberOfIds(2);
for(unsigned int i=0;i<conn.size();++i)
{
pts->SetId(i,conn[i]);
}
grid->InsertNextCell(VTK_LINE,pts);
pts->Delete();
++cnnx_index;
}
}
/**
* Reads a .lon file and adds the vectors to the given elements;
* Code assumes that the file has a first line to ignore.
*/
void create_vectors(const std::string& file_name,
vtkSmartPointer<vtkUnstructuredGrid> grid)
{
//Create tris
std::ifstream lon_file(file_name.c_str());
if (!lon_file)
{
std::cerr << "Failed to read lon file" << std::endl;
abort();
}
//
//Read the pts file
std::string line;
// std::getline(lon_file, line); //Skip over the first line
// quick and dirty way to check if there is a one-line header
// if there is, ignore it
// if (found!=string::npos)
//
vtkCellData* cellData = grid->GetCellData();
vtkSmartPointer< vtkFloatArray > vectors = vtkSmartPointer< vtkFloatArray >::New();
vectors->SetName("lon");
cellData->AddArray(vectors);
//Create Vertices
while(std::getline(lon_file, line))
{
double lon[3];
// >> lon[0] >> lon[1] >> lon[2];
char_delimiters_separator<char> sep(false, "", " ");
tokenizer<> line_toks(line, sep);
std::stringstream vertex_coords;
tokenizer<>::iterator beg=line_toks.begin();
std::istringstream iss(*beg);
iss >> lon[0];
++beg;
std::istringstream iss2(*beg);
iss2 >> lon[1];
++beg;
std::istringstream iss3(*beg);
iss3 >> lon[2];
++beg;
vectors->SetNumberOfComponents(3);
vectors->InsertNextTuple3(lon[0],lon[1],lon[2]);
// vectors->InsertNextTuple(lon[0]);
//
// vtkIdList *pts = vtkIdList::New();
// pts->SetNumberOfIds(2);
//
// for(unsigned int i=0;i<lon.size();++i)
// {
// pts->SetId(i,lon[i]);
// }
//
// grid->InsertNextCell(VTK_LINE,pts);
// pts->Delete();
}
}
<|endoftext|> |
<commit_before>//
// Created by vincent on 13/06/17.
//
#include "Game.hpp"
#include "Bomb.hpp"
unsigned int is::Bomb::ID = 0;
is::Bomb::Bomb(is::map &map, irr::video::ITexture *texture, irr::scene::IAnimatedMesh *bombMesh, const irr::core::vector3df &posMap, int power,
irr::video::IVideoDriver &videoDriver, irr::scene::ISceneManager &sceneManager) :
_id(ID++),
_posMap(posMap),
_posSpace(posMap.Y * SCALE - SCALE / 2, 0.55 * SCALE, posMap.X * SCALE + SCALE / 2),
_power(power),
_map(map),
_videoDriver(videoDriver),
_sceneManager(sceneManager),
_alreadyBlowUp(false),
_start_clock(std::clock()),
_state(BOMB_PLANTED),
_fires()
{
if (!(this->_node = this->_sceneManager.addAnimatedMeshSceneNode(bombMesh)))
throw is::IndieStudioException("Error on loading bomb.");
this->_node->setPosition(this->_posSpace);
this->_node->setScale({0.5f * SCALE, 0.5f * SCALE, 0.5f * SCALE});
this->_map.addObject(Type::BOMB, {(int)posMap.X, (int)posMap.Y, (int)posMap.Z});
std::cerr << "Bomb() id = " << this->_id << std::endl;
std::cout << "Bomb pos.x = " << posMap.X << " pos.y = " << posMap.Y << " pos.Z = " << posMap.Z << std::endl;
}
is::Bomb::~Bomb()
{
this->_map.delObject({(int)this->_posMap.X, (int)this->_posMap.Y, (int)this->_posMap.Z});
std::cerr << "~Bomb() id = " << this->_id << std::endl;
}
void is::Bomb::draw()
{
this->_node->render();
}
void is::Bomb::remove()
{
this->_node->remove();
}
bool is::Bomb::blowUp(std::list<std::shared_ptr<is::Bomb>> bombs)
{
std::clock_t end_clock = std::clock();
int duration = static_cast<int>((std::clock() - _start_clock) / CLOCKS_PER_SEC);
if (this->_state == BOMB_PLANTED && duration == ((_id == 0) ? (2) : (5)))
{
this->_explosion(bombs);
}
else if (this->_state == FIRE && duration == 2)
{
this->_stopFires();
return (true);
}
return (false);
}
int is::Bomb::_reducePower(std::list<std::shared_ptr<is::Bomb>> bombs,
irr::core::vector3df pos,
int power,
const std::function<void(irr::core::vector3df &)> &callback)
{
int ret = 0;
const Block *b;
//std::cerr << "_reducPower" << std::endl;
callback(pos);
//std::cout << "pos.x = " << pos.X << " pos.y = " << pos.Y << " pos.z = " << pos.Z<< std::endl;
while (this->_map.canIMoove(is::Vector3d(pos.X, pos.Y, pos.Z)) && ret < power)
{
callback(pos);
ret += 1;
}
if ((b = this->_map.findBlock({(int)pos.X, (int)pos.Y, (int)pos.Z}))->getType() == is::Type::BREAK)
{
this->_blocksToDelete.emplace_back(pos.X, pos.Y, pos.Z);
ret += 1;
}
else if (b->getType() == Type::BOMB)
{
auto it = std::find_if(bombs.begin(), bombs.end(), [pos](auto bomb) { return pos == bomb->getPos(); });
std::cout << std::boolalpha << _alreadyBlowUp << std::endl;
if ((*it)->_alreadyBlowUp == false)
(*it)->_explosion(bombs);
ret += 1;
//std::cout << "DESTRUIT UNE AUTRE BOMBE" << std::endl;
}
//std::cout << "ret = " << ret << std::endl;
//std::cerr << "_reducPower" << std::endl;
return (ret);
}
is::Bomb &is::Bomb::operator=(const Bomb &o)
{
this->_posMap = o._posMap;
this->_posSpace = o._posSpace;
this->_power = o._power;
this->_node = o._node;
}
bool is::Bomb::operator==(const is::Bomb &other) const
{
return (this == &other);
}
bool is::Bomb::operator!=(const is::Bomb &rhs) const
{
return !(rhs == *this);
}
void is::Bomb::_startFires(std::list<std::shared_ptr<is::Bomb>> bombs)
{
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::FORWARD,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.X += 1; }));
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::BACKWARD,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.X -= 1; }));
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::RIGHT,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.Y += 1; }));
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::LEFT,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.Y -= 1; }));
std::for_each(this->_fires.begin(), this->_fires.end(), [](Fire &fire) {
fire.startFire();
});
std::for_each(this->_blocksToDelete.begin(), this->_blocksToDelete.end(), [&](auto pos) {
this->_map.delObject(pos);
});
}
void is::Bomb::_stopFires()
{
std::for_each(this->_fires.begin(), this->_fires.end(), [](Fire &fire) {
fire.stopFire();
});
}
const irr::core::vector3df &is::Bomb::getPos() const
{
return (this->_posMap);
}
void is::Bomb::_explosion(std::list<std::shared_ptr<is::Bomb>> bombs)
{
this->_alreadyBlowUp = true;
this->_state = FIRE;
this->_startFires(bombs);
this->_node->remove();
this->_start_clock = std::clock();
}
<commit_msg>MAJ Bomb<commit_after>//
// Created by vincent on 13/06/17.
//
#include "Game.hpp"
#include "Bomb.hpp"
unsigned int is::Bomb::ID = 0;
is::Bomb::Bomb(is::map &map, irr::video::ITexture *texture, irr::scene::IAnimatedMesh *bombMesh, const irr::core::vector3df &posMap, int power,
irr::video::IVideoDriver &videoDriver, irr::scene::ISceneManager &sceneManager) :
_id(ID++),
_posMap(posMap),
_posSpace(posMap.Y * SCALE - SCALE / 2, 0.55 * SCALE, posMap.X * SCALE + SCALE / 2),
_power(power),
_map(map),
_videoDriver(videoDriver),
_sceneManager(sceneManager),
_alreadyBlowUp(false),
_start_clock(std::clock()),
_state(BOMB_PLANTED),
_fires()
{
if (!(this->_node = this->_sceneManager.addAnimatedMeshSceneNode(bombMesh)))
throw is::IndieStudioException("Error on loading bomb.");
this->_node->setPosition(this->_posSpace);
this->_node->setScale({0.5f * SCALE, 0.5f * SCALE, 0.5f * SCALE});
this->_map.addObject(Type::BOMB, {(int)posMap.X, (int)posMap.Y, (int)posMap.Z});
std::cerr << "Bomb() id = " << this->_id << std::endl;
std::cout << "Bomb pos.x = " << posMap.X << " pos.y = " << posMap.Y << " pos.Z = " << posMap.Z << std::endl;
}
is::Bomb::~Bomb()
{
this->_map.delObject({(int)this->_posMap.X, (int)this->_posMap.Y, (int)this->_posMap.Z});
std::cerr << "~Bomb() id = " << this->_id << std::endl;
}
void is::Bomb::draw()
{
this->_node->render();
}
void is::Bomb::remove()
{
this->_node->remove();
}
bool is::Bomb::blowUp(std::list<std::shared_ptr<is::Bomb>> bombs)
{
std::clock_t end_clock = std::clock();
int duration = static_cast<int>((std::clock() - _start_clock) / CLOCKS_PER_SEC);
if (this->_state == BOMB_PLANTED && duration == ((_id == 0) ? (2) : (5)))
{
this->_explosion(bombs);
}
else if (this->_state == FIRE && duration == 2)
{
this->_stopFires();
return (true);
}
return (false);
}
int is::Bomb::_reducePower(std::list<std::shared_ptr<is::Bomb>> bombs,
irr::core::vector3df pos,
int power,
const std::function<void(irr::core::vector3df &)> &callback)
{
int ret = 0;
const Block *b;
//std::cerr << "_reducPower" << std::endl;
callback(pos);
//std::cout << "pos.x = " << pos.X << " pos.y = " << pos.Y << " pos.z = " << pos.Z<< std::endl;
while (this->_map.canIMoove(is::Vector3d(pos.X, pos.Y, pos.Z)) && ret < power)
{
callback(pos);
ret += 1;
}
if ((b = this->_map.findBlock({(int)pos.X, (int)pos.Y, (int)pos.Z}))->getType() == is::Type::BREAK)
{
this->_blocksToDelete.emplace_back(pos.X, pos.Y, pos.Z);
ret += 1;
}
else if (b->getType() == Type::BOMB)
{
ret += 1;
auto it = std::find_if(bombs.begin(),
bombs.end(),
[pos](auto bomb) { return pos.X == bomb->getPos().X && pos.Y == bomb->getPos().Y && pos.Z == bomb->getPos().Z; });
if (it == bombs.end())
return (ret);
std::cout << std::boolalpha << _alreadyBlowUp << std::endl;
if ((*it)->_alreadyBlowUp == false)
(*it)->_explosion(bombs);
//std::cout << "DESTRUIT UNE AUTRE BOMBE" << std::endl;
}
//std::cout << "ret = " << ret << std::endl;
//std::cerr << "_reducPower" << std::endl;
return (ret);
}
is::Bomb &is::Bomb::operator=(const Bomb &o)
{
this->_posMap = o._posMap;
this->_posSpace = o._posSpace;
this->_power = o._power;
this->_node = o._node;
}
bool is::Bomb::operator==(const is::Bomb &other) const
{
return (this == &other);
}
bool is::Bomb::operator!=(const is::Bomb &rhs) const
{
return !(rhs == *this);
}
void is::Bomb::_startFires(std::list<std::shared_ptr<is::Bomb>> bombs)
{
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::FORWARD,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.X += 1; }));
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::BACKWARD,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.X -= 1; }));
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::RIGHT,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.Y += 1; }));
this->_fires.emplace_back(&this->_sceneManager, &this->_videoDriver, this->_posSpace, FireDirection::LEFT,
this->_reducePower(bombs, this->_posMap, this->_power, [&](irr::core::vector3df &pos) { pos.Y -= 1; }));
std::for_each(this->_fires.begin(), this->_fires.end(), [](Fire &fire) {
fire.startFire();
});
std::for_each(this->_blocksToDelete.begin(), this->_blocksToDelete.end(), [&](auto pos) {
this->_map.delObject(pos);
});
}
void is::Bomb::_stopFires()
{
std::for_each(this->_fires.begin(), this->_fires.end(), [](Fire &fire) {
fire.stopFire();
});
}
const irr::core::vector3df &is::Bomb::getPos() const
{
return (this->_posMap);
}
void is::Bomb::_explosion(std::list<std::shared_ptr<is::Bomb>> bombs)
{
this->_alreadyBlowUp = true;
this->_state = FIRE;
this->_startFires(bombs);
this->_node->remove();
this->_start_clock = std::clock();
}
<|endoftext|> |
<commit_before>#include "medToolBoxDiffusionTensorView.h"
class medToolBoxDiffusionTensorViewPrivate
{
public:
QComboBox* glyphShape;
QSlider* sampleRate;
QCheckBox* flipX;
QCheckBox* flipY;
QCheckBox* flipZ;
QRadioButton* eigenVectorV1;
QRadioButton* eigenVectorV2;
QRadioButton* eigenVectorV3;
QCheckBox* reverseBackgroundColor;
QSlider* glyphResolution;
// labels for showing the slider's actual value
QLabel* sampleRateLabel;
};
medToolBoxDiffusionTensorView::medToolBoxDiffusionTensorView(QWidget *parent) : medToolBox(parent), d(new medToolBoxDiffusionTensorViewPrivate)
{
QWidget* displayWidget = new QWidget(this);
// combobox to control the glyph shape
d->glyphShape = new QComboBox(displayWidget);
d->glyphShape->addItem("Lines");
d->glyphShape->addItem("Arrows");
d->glyphShape->addItem("Disks");
d->glyphShape->addItem("Cylinders");
d->glyphShape->addItem("Cubes");
d->glyphShape->addItem("Ellipsoids");
d->glyphShape->addItem("Superquadrics");
QHBoxLayout* glyphShapeLayout = new QHBoxLayout;
glyphShapeLayout->addWidget(new QLabel("Shape: "));
glyphShapeLayout->addWidget(d->glyphShape);
// slider to control sample rate
d->sampleRate = new QSlider(Qt::Horizontal, displayWidget);
d->sampleRate->setMinimum(1);
d->sampleRate->setMaximum(10);
d->sampleRate->setSingleStep(1);
d->sampleRate->setValue(1);
d->sampleRateLabel = new QLabel("1", displayWidget);
QHBoxLayout* sampleRateLayout = new QHBoxLayout;
sampleRateLayout->addWidget(new QLabel("Sample rate: "));
sampleRateLayout->addWidget(d->sampleRate);
sampleRateLayout->addWidget(d->sampleRateLabel);
connect(d->sampleRate, SIGNAL(valueChanged(int)), d->sampleRateLabel, SLOT(setNum(int)));
// flipX, flipY and flipZ checkboxes
d->flipX = new QCheckBox("Flip X", displayWidget);
d->flipY = new QCheckBox("Flip Y", displayWidget);
d->flipZ = new QCheckBox("Flip Z", displayWidget);
QHBoxLayout* flipAxesLayout = new QHBoxLayout;
flipAxesLayout->addWidget(d->flipX);
flipAxesLayout->addWidget(d->flipY);
flipAxesLayout->addWidget(d->flipZ);
// eigen vectors
d->eigenVectorV1 = new QRadioButton("v1", displayWidget);
d->eigenVectorV2 = new QRadioButton("v2", displayWidget);
d->eigenVectorV3 = new QRadioButton("v3", displayWidget);
QButtonGroup *eigenVectorRadioGroup = new QButtonGroup(displayWidget);
eigenVectorRadioGroup->addButton(d->eigenVectorV1);
eigenVectorRadioGroup->addButton(d->eigenVectorV2);
eigenVectorRadioGroup->addButton(d->eigenVectorV3);
eigenVectorRadioGroup->setExclusive(true);
QHBoxLayout *eigenVectorGroupLayout = new QHBoxLayout;
eigenVectorGroupLayout->addWidget(d->eigenVectorV1);
eigenVectorGroupLayout->addWidget(d->eigenVectorV2);
eigenVectorGroupLayout->addWidget(d->eigenVectorV3);
//eigenVectorGroupLayout->addStretch(1);
QVBoxLayout* eigenLayout = new QVBoxLayout;
eigenLayout->addWidget(new QLabel("Eigen Vector for color-coding:"));
eigenLayout->addLayout(eigenVectorGroupLayout);
d->eigenVectorV1->setChecked(true);
// reverse background color
d->reverseBackgroundColor = new QCheckBox("Reverse Background Color", displayWidget);
// slider to control glyph resolution
d->glyphResolution = new QSlider(Qt::Horizontal, displayWidget);
d->glyphResolution->setMinimum(2);
d->glyphResolution->setMaximum(20);
d->glyphResolution->setSingleStep(1);
d->glyphResolution->setValue(6);
//d->glyphResolution->setTickPosition(QSlider::TicksAbove);
QHBoxLayout* glyphResolutionLayout = new QHBoxLayout;
glyphResolutionLayout->addWidget(new QLabel("Glyph resolution: "));
glyphResolutionLayout->addWidget(d->glyphResolution);
// layout all the controls in the toolbox
QVBoxLayout* layout = new QVBoxLayout(displayWidget);
layout->addLayout(glyphShapeLayout);
layout->addLayout(sampleRateLayout);
layout->addLayout(flipAxesLayout);
layout->addLayout(eigenLayout);
layout->addWidget(d->reverseBackgroundColor);
layout->addLayout(glyphResolutionLayout);
// connect all the signals
connect(d->glyphShape, SIGNAL(currentIndexChanged(const QString&)), this, SIGNAL(glyphShapeChanged(const QString&)));
connect(d->sampleRate, SIGNAL(valueChanged(int)), this, SIGNAL(sampleRateChanged(int)));
connect(d->reverseBackgroundColor, SIGNAL(stateChanged(int)), this, SIGNAL(reverseBackgroundColor(bool)));
connect(d->glyphResolution, SIGNAL(valueChanged(int)), this, SIGNAL(glyphResolutionChanged(int)));
// the axes signals require one more step to translate from Qt::CheckState to bool
connect(d->flipX, SIGNAL(stateChanged(int)), this, SLOT(onFlipXCheckBoxStateChanged(int)));
connect(d->flipY, SIGNAL(stateChanged(int)), this, SLOT(onFlipYCheckBoxStateChanged(int)));
connect(d->flipZ, SIGNAL(stateChanged(int)), this, SLOT(onFlipZCheckBoxStateChanged(int)));
// we also need to translate radio buttons boolean states to an eigen vector
connect(d->eigenVectorV1, SIGNAL(toggled(bool)), this, SLOT(onEigenVectorV1Toggled(bool)));
connect(d->eigenVectorV2, SIGNAL(toggled(bool)), this, SLOT(onEigenVectorV2Toggled(bool)));
connect(d->eigenVectorV3, SIGNAL(toggled(bool)), this, SLOT(onEigenVectorV3Toggled(bool)));
this->setTitle("Tensor View");
this->addWidget(displayWidget);
}
medToolBoxDiffusionTensorView::~medToolBoxDiffusionTensorView()
{
delete d;
d = NULL;
}
void medToolBoxDiffusionTensorView::update (dtkAbstractView *view)
{
}
void medToolBoxDiffusionTensorView::onFlipXCheckBoxStateChanged(int checkBoxState)
{
if (checkBoxState == Qt::Unchecked)
emit flipX(false);
else if (checkBoxState == Qt::Checked)
emit flipX(true);
}
void medToolBoxDiffusionTensorView::onFlipYCheckBoxStateChanged(int checkBoxState)
{
if (checkBoxState == Qt::Unchecked)
emit flipY(false);
else if (checkBoxState == Qt::Checked)
emit flipY(true);
}
void medToolBoxDiffusionTensorView::onFlipZCheckBoxStateChanged(int checkBoxState)
{
if (checkBoxState == Qt::Unchecked)
emit flipZ(false);
else if (checkBoxState == Qt::Checked)
emit flipZ(true);
}
void medToolBoxDiffusionTensorView::onEigenVectorV1Toggled(bool isSelected)
{
if (isSelected)
emit eigenVectorChanged(1);
}
void medToolBoxDiffusionTensorView::onEigenVectorV2Toggled(bool isSelected)
{
if (isSelected)
emit eigenVectorChanged(2);
}
void medToolBoxDiffusionTensorView::onEigenVectorV3Toggled(bool isSelected)
{
if (isSelected)
emit eigenVectorChanged(3);
}
<commit_msg>Added label next to the glyph resolution slider in the tensor toolbox to show the actual value.<commit_after>#include "medToolBoxDiffusionTensorView.h"
class medToolBoxDiffusionTensorViewPrivate
{
public:
QComboBox* glyphShape;
QSlider* sampleRate;
QCheckBox* flipX;
QCheckBox* flipY;
QCheckBox* flipZ;
QRadioButton* eigenVectorV1;
QRadioButton* eigenVectorV2;
QRadioButton* eigenVectorV3;
QCheckBox* reverseBackgroundColor;
QSlider* glyphResolution;
// labels for showing the slider's actual value
QLabel* sampleRateLabel;
QLabel* glyphResolutionLabel;
};
medToolBoxDiffusionTensorView::medToolBoxDiffusionTensorView(QWidget *parent) : medToolBox(parent), d(new medToolBoxDiffusionTensorViewPrivate)
{
QWidget* displayWidget = new QWidget(this);
// combobox to control the glyph shape
d->glyphShape = new QComboBox(displayWidget);
d->glyphShape->addItem("Lines");
d->glyphShape->addItem("Arrows");
d->glyphShape->addItem("Disks");
d->glyphShape->addItem("Cylinders");
d->glyphShape->addItem("Cubes");
d->glyphShape->addItem("Ellipsoids");
d->glyphShape->addItem("Superquadrics");
QHBoxLayout* glyphShapeLayout = new QHBoxLayout;
glyphShapeLayout->addWidget(new QLabel("Shape: "));
glyphShapeLayout->addWidget(d->glyphShape);
// slider to control sample rate
d->sampleRate = new QSlider(Qt::Horizontal, displayWidget);
d->sampleRate->setMinimum(1);
d->sampleRate->setMaximum(10);
d->sampleRate->setSingleStep(1);
d->sampleRate->setValue(1);
d->sampleRateLabel = new QLabel("1", displayWidget);
QHBoxLayout* sampleRateLayout = new QHBoxLayout;
sampleRateLayout->addWidget(new QLabel("Sample rate: "));
sampleRateLayout->addWidget(d->sampleRate);
sampleRateLayout->addWidget(d->sampleRateLabel);
connect(d->sampleRate, SIGNAL(valueChanged(int)), d->sampleRateLabel, SLOT(setNum(int)));
// flipX, flipY and flipZ checkboxes
d->flipX = new QCheckBox("Flip X", displayWidget);
d->flipY = new QCheckBox("Flip Y", displayWidget);
d->flipZ = new QCheckBox("Flip Z", displayWidget);
QHBoxLayout* flipAxesLayout = new QHBoxLayout;
flipAxesLayout->addWidget(d->flipX);
flipAxesLayout->addWidget(d->flipY);
flipAxesLayout->addWidget(d->flipZ);
// eigen vectors
d->eigenVectorV1 = new QRadioButton("v1", displayWidget);
d->eigenVectorV2 = new QRadioButton("v2", displayWidget);
d->eigenVectorV3 = new QRadioButton("v3", displayWidget);
QButtonGroup *eigenVectorRadioGroup = new QButtonGroup(displayWidget);
eigenVectorRadioGroup->addButton(d->eigenVectorV1);
eigenVectorRadioGroup->addButton(d->eigenVectorV2);
eigenVectorRadioGroup->addButton(d->eigenVectorV3);
eigenVectorRadioGroup->setExclusive(true);
QHBoxLayout *eigenVectorGroupLayout = new QHBoxLayout;
eigenVectorGroupLayout->addWidget(d->eigenVectorV1);
eigenVectorGroupLayout->addWidget(d->eigenVectorV2);
eigenVectorGroupLayout->addWidget(d->eigenVectorV3);
//eigenVectorGroupLayout->addStretch(1);
QVBoxLayout* eigenLayout = new QVBoxLayout;
eigenLayout->addWidget(new QLabel("Eigen Vector for color-coding:"));
eigenLayout->addLayout(eigenVectorGroupLayout);
d->eigenVectorV1->setChecked(true);
// reverse background color
d->reverseBackgroundColor = new QCheckBox("Reverse Background Color", displayWidget);
// slider to control glyph resolution
d->glyphResolution = new QSlider(Qt::Horizontal, displayWidget);
d->glyphResolution->setMinimum(2);
d->glyphResolution->setMaximum(20);
d->glyphResolution->setSingleStep(1);
d->glyphResolution->setValue(6);
d->glyphResolutionLabel = new QLabel("6", displayWidget);
QHBoxLayout* glyphResolutionLayout = new QHBoxLayout;
glyphResolutionLayout->addWidget(new QLabel("Glyph resolution: "));
glyphResolutionLayout->addWidget(d->glyphResolution);
glyphResolutionLayout->addWidget(d->glyphResolutionLabel);
connect(d->glyphResolution, SIGNAL(valueChanged(int)), d->glyphResolutionLabel, SLOT(setNum(int)));
// layout all the controls in the toolbox
QVBoxLayout* layout = new QVBoxLayout(displayWidget);
layout->addLayout(glyphShapeLayout);
layout->addLayout(sampleRateLayout);
layout->addLayout(flipAxesLayout);
layout->addLayout(eigenLayout);
layout->addWidget(d->reverseBackgroundColor);
layout->addLayout(glyphResolutionLayout);
// connect all the signals
connect(d->glyphShape, SIGNAL(currentIndexChanged(const QString&)), this, SIGNAL(glyphShapeChanged(const QString&)));
connect(d->sampleRate, SIGNAL(valueChanged(int)), this, SIGNAL(sampleRateChanged(int)));
connect(d->reverseBackgroundColor, SIGNAL(stateChanged(int)), this, SIGNAL(reverseBackgroundColor(bool)));
connect(d->glyphResolution, SIGNAL(valueChanged(int)), this, SIGNAL(glyphResolutionChanged(int)));
// the axes signals require one more step to translate from Qt::CheckState to bool
connect(d->flipX, SIGNAL(stateChanged(int)), this, SLOT(onFlipXCheckBoxStateChanged(int)));
connect(d->flipY, SIGNAL(stateChanged(int)), this, SLOT(onFlipYCheckBoxStateChanged(int)));
connect(d->flipZ, SIGNAL(stateChanged(int)), this, SLOT(onFlipZCheckBoxStateChanged(int)));
// we also need to translate radio buttons boolean states to an eigen vector
connect(d->eigenVectorV1, SIGNAL(toggled(bool)), this, SLOT(onEigenVectorV1Toggled(bool)));
connect(d->eigenVectorV2, SIGNAL(toggled(bool)), this, SLOT(onEigenVectorV2Toggled(bool)));
connect(d->eigenVectorV3, SIGNAL(toggled(bool)), this, SLOT(onEigenVectorV3Toggled(bool)));
this->setTitle("Tensor View");
this->addWidget(displayWidget);
}
medToolBoxDiffusionTensorView::~medToolBoxDiffusionTensorView()
{
delete d;
d = NULL;
}
void medToolBoxDiffusionTensorView::update (dtkAbstractView *view)
{
}
void medToolBoxDiffusionTensorView::onFlipXCheckBoxStateChanged(int checkBoxState)
{
if (checkBoxState == Qt::Unchecked)
emit flipX(false);
else if (checkBoxState == Qt::Checked)
emit flipX(true);
}
void medToolBoxDiffusionTensorView::onFlipYCheckBoxStateChanged(int checkBoxState)
{
if (checkBoxState == Qt::Unchecked)
emit flipY(false);
else if (checkBoxState == Qt::Checked)
emit flipY(true);
}
void medToolBoxDiffusionTensorView::onFlipZCheckBoxStateChanged(int checkBoxState)
{
if (checkBoxState == Qt::Unchecked)
emit flipZ(false);
else if (checkBoxState == Qt::Checked)
emit flipZ(true);
}
void medToolBoxDiffusionTensorView::onEigenVectorV1Toggled(bool isSelected)
{
if (isSelected)
emit eigenVectorChanged(1);
}
void medToolBoxDiffusionTensorView::onEigenVectorV2Toggled(bool isSelected)
{
if (isSelected)
emit eigenVectorChanged(2);
}
void medToolBoxDiffusionTensorView::onEigenVectorV3Toggled(bool isSelected)
{
if (isSelected)
emit eigenVectorChanged(3);
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------
//
// Copyright (C) 2015 by the deal2lkit authors
//
// This file is part of the deal2lkit library.
//
// The deal2lkit library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal2lkit distribution.
//
//-----------------------------------------------------------
#include <deal2lkit/parsed_finite_element.h>
#include <deal2lkit/utilities.h>
#include <deal.II/fe/fe_tools.h>
#include <algorithm> // std::find
D2K_NAMESPACE_OPEN
template <int dim, int spacedim>
ParsedFiniteElement<dim, spacedim>::ParsedFiniteElement(const std::string &name,
const std::string &default_name,
const std::string &default_component_names,
const unsigned int n_components) :
ParameterAcceptor(name),
_n_components(n_components),
fe_name(default_name),
default_component_names(default_component_names)
{
component_names = Utilities::split_string_list(default_component_names);
parse_parameters_call_back();
}
template <int dim, int spacedim>
void ParsedFiniteElement<dim, spacedim>::declare_parameters(ParameterHandler &prm)
{
add_parameter(prm, &fe_name,
"Finite element space", fe_name,
Patterns::Anything(),
"The finite element space to use. For vector "
"finite elements use the notation "
"FESystem[FE_Q(2)^2-FE_DGP(1)] (e.g. Navier-Stokes). ");
add_parameter(prm, &component_names,
"Blocking of the finite element", default_component_names,
// This ensures that an assert is thrown if you try to
// read something with the wrong number of components
Patterns::List(Patterns::Anything(),
(_n_components ? _n_components: 1),
(_n_components ? _n_components: numbers::invalid_unsigned_int)),
"How to partition the finite element. This information can be used "
"to construct block matrices and vectors, as well as to create "
"names for solution vectors, or error tables. A repeated component "
"is interpreted as a vector field, with dimension equal to the "
"number of repetitions (up to 3). This is used in conjunction "
"with a ParsedFiniteElement class, to generate arbitrary "
"finite dimensional spaces.");
}
template <int dim, int spacedim>
FiniteElement<dim,spacedim> *
ParsedFiniteElement<dim, spacedim>::operator()() const
{
return FETools::get_fe_by_name<dim,spacedim>(fe_name);
}
template<int dim, int spacedim>
void ParsedFiniteElement<dim,spacedim>::parse_parameters_call_back()
{
component_blocks.resize(component_names.size());
block_names.resize(component_names.size());
unsigned int j=0;
for (unsigned int i=0; i<component_names.size(); ++i)
{
if ( (i>0) && (component_names[i-1] != component_names[i]) )
j++;
component_blocks[i] = j;
block_names[j] = component_names[i];
}
block_names.resize(j+1);
FiniteElement<dim,spacedim> *fe = (*this)();
const unsigned int nc = fe->n_components();
delete fe;
AssertThrow(component_names.size() == nc,
ExcInternalError("Generated FE has the wrong number of components."));
}
template<int dim, int spacedim>
unsigned int ParsedFiniteElement<dim,spacedim>::n_components() const
{
return component_names.size();
}
template<int dim, int spacedim>
unsigned int ParsedFiniteElement<dim,spacedim>::n_blocks() const
{
return block_names.size();
}
template<int dim, int spacedim>
std::string ParsedFiniteElement<dim,spacedim>::get_component_names() const
{
return print(component_names);
}
template<int dim, int spacedim>
std::string ParsedFiniteElement<dim,spacedim>::get_block_names() const
{
return print(block_names);
}
template<int dim, int spacedim>
std::vector<unsigned int> ParsedFiniteElement<dim,spacedim>::get_component_blocks() const
{
return component_blocks;
}
template<int dim, int spacedim>
unsigned int ParsedFiniteElement<dim,spacedim>::get_first_occurence(const std::string &var) const
{
unsigned int pos_counter = 0;
auto pos_it = std::find (component_names.begin(), component_names.end(), var);
Assert(pos_it != component_names.end(),
ExcInternalError("Component not found!"));
return pos_it - component_names.begin();
}
template<int dim, int spacedim>
bool ParsedFiniteElement<dim,spacedim>::is_vector(const std::string &var) const
{
auto pos_it = std::find (component_names.begin(), component_names.end(), var);
Assert(pos_it != component_names.end(),
ExcInternalError("Component not found!"));
pos_it++;
if (pos_it == component_names.end())
return false;
return (*pos_it == var);
}
D2K_NAMESPACE_CLOSE
template class deal2lkit::ParsedFiniteElement<1,1>;
template class deal2lkit::ParsedFiniteElement<1,2>;
template class deal2lkit::ParsedFiniteElement<1,3>;
template class deal2lkit::ParsedFiniteElement<2,2>;
template class deal2lkit::ParsedFiniteElement<2,3>;
template class deal2lkit::ParsedFiniteElement<3,3>;
<commit_msg>silence<commit_after>//-----------------------------------------------------------
//
// Copyright (C) 2015 by the deal2lkit authors
//
// This file is part of the deal2lkit library.
//
// The deal2lkit library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal2lkit distribution.
//
//-----------------------------------------------------------
#include <deal2lkit/parsed_finite_element.h>
#include <deal2lkit/utilities.h>
#include <deal.II/fe/fe_tools.h>
#include <algorithm> // std::find
D2K_NAMESPACE_OPEN
template <int dim, int spacedim>
ParsedFiniteElement<dim, spacedim>::ParsedFiniteElement(const std::string &name,
const std::string &default_name,
const std::string &default_component_names,
const unsigned int n_components) :
ParameterAcceptor(name),
_n_components(n_components),
fe_name(default_name),
default_component_names(default_component_names)
{
component_names = Utilities::split_string_list(default_component_names);
parse_parameters_call_back();
}
template <int dim, int spacedim>
void ParsedFiniteElement<dim, spacedim>::declare_parameters(ParameterHandler &prm)
{
add_parameter(prm, &fe_name,
"Finite element space", fe_name,
Patterns::Anything(),
"The finite element space to use. For vector "
"finite elements use the notation "
"FESystem[FE_Q(2)^2-FE_DGP(1)] (e.g. Navier-Stokes). ");
add_parameter(prm, &component_names,
"Blocking of the finite element", default_component_names,
// This ensures that an assert is thrown if you try to
// read something with the wrong number of components
Patterns::List(Patterns::Anything(),
(_n_components ? _n_components: 1),
(_n_components ? _n_components: numbers::invalid_unsigned_int)),
"How to partition the finite element. This information can be used "
"to construct block matrices and vectors, as well as to create "
"names for solution vectors, or error tables. A repeated component "
"is interpreted as a vector field, with dimension equal to the "
"number of repetitions (up to 3). This is used in conjunction "
"with a ParsedFiniteElement class, to generate arbitrary "
"finite dimensional spaces.");
}
template <int dim, int spacedim>
FiniteElement<dim,spacedim> *
ParsedFiniteElement<dim, spacedim>::operator()() const
{
return FETools::get_fe_by_name<dim,spacedim>(fe_name);
}
template<int dim, int spacedim>
void ParsedFiniteElement<dim,spacedim>::parse_parameters_call_back()
{
component_blocks.resize(component_names.size());
block_names.resize(component_names.size());
unsigned int j=0;
for (unsigned int i=0; i<component_names.size(); ++i)
{
if ( (i>0) && (component_names[i-1] != component_names[i]) )
j++;
component_blocks[i] = j;
block_names[j] = component_names[i];
}
block_names.resize(j+1);
FiniteElement<dim,spacedim> *fe = (*this)();
const unsigned int nc = fe->n_components();
delete fe;
AssertThrow(component_names.size() == nc,
ExcInternalError("Generated FE has the wrong number of components."));
}
template<int dim, int spacedim>
unsigned int ParsedFiniteElement<dim,spacedim>::n_components() const
{
return component_names.size();
}
template<int dim, int spacedim>
unsigned int ParsedFiniteElement<dim,spacedim>::n_blocks() const
{
return block_names.size();
}
template<int dim, int spacedim>
std::string ParsedFiniteElement<dim,spacedim>::get_component_names() const
{
return print(component_names);
}
template<int dim, int spacedim>
std::string ParsedFiniteElement<dim,spacedim>::get_block_names() const
{
return print(block_names);
}
template<int dim, int spacedim>
std::vector<unsigned int> ParsedFiniteElement<dim,spacedim>::get_component_blocks() const
{
return component_blocks;
}
template<int dim, int spacedim>
unsigned int ParsedFiniteElement<dim,spacedim>::get_first_occurence(const std::string &var) const
{
auto pos_it = std::find (component_names.begin(), component_names.end(), var);
Assert(pos_it != component_names.end(),
ExcInternalError("Component not found!"));
return pos_it - component_names.begin();
}
template<int dim, int spacedim>
bool ParsedFiniteElement<dim,spacedim>::is_vector(const std::string &var) const
{
auto pos_it = std::find (component_names.begin(), component_names.end(), var);
Assert(pos_it != component_names.end(),
ExcInternalError("Component not found!"));
pos_it++;
if (pos_it == component_names.end())
return false;
return (*pos_it == var);
}
D2K_NAMESPACE_CLOSE
template class deal2lkit::ParsedFiniteElement<1,1>;
template class deal2lkit::ParsedFiniteElement<1,2>;
template class deal2lkit::ParsedFiniteElement<1,3>;
template class deal2lkit::ParsedFiniteElement<2,2>;
template class deal2lkit::ParsedFiniteElement<2,3>;
template class deal2lkit::ParsedFiniteElement<3,3>;
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W;
ll A, B;
bool f[210][210];
ll solve() {
bool x[110][110][4];
for (auto i = 1; i < H/2+1; ++i) {
for (auto j = 1; j < W/2+1; ++j) {
x[i][j][0] = f[i-1][j-1];
x[i][j][1] = f[H-1-i+1][j-1];
x[i][j][2] = f[i-1][W-1-j+1];
x[i][j][3] = f[H-1-i+1][W-1-j+1];
}
}
for (auto k = 0; k < 4; ++k) {
cerr << "k = " << k << endl;
for (auto i = 1; i < H/2+1; ++i) {
for (auto j = 1; j < W/2+1; ++j) {
cerr << (x[i][j][k] ? 'S' : '.');
}
cerr << endl;
}
}
ll ryoho = 0;
ll yobi = 0;
ll tate = 0;
ll yoko = 0;
for (auto i = 1; i < H/2+1; ++i) {
for (auto j = 1; j < W/2+1; ++j) {
int cnt = 0;
for (auto k = 0; k < 4; ++k) {
if (x[i][j][k]) cnt++;
}
if (cnt == 4) ryoho++;
if (cnt == 3) yobi++;
if (cnt == 2) {
if (x[i][j][0] == x[i][j][1] && x[i][j][2] == x[i][j][3]) {
tate++;
} else if (x[i][j][0] == x[i][j][2] && x[i][j][1] == x[i][j][3]) {
yoko++;
}
}
}
}
ll ans = 0;
ans = max(ans, ryoho * (A + B + A) + (yobi + tate) * A);
ans = max(ans, ryoho * (A + B + B) + (yobi + yoko) * B);
return ans;
}
int main () {
cin >> H >> W >> A >> B;
string m[210];
for (auto i = 0; i < H; ++i) {
cin >> m[i];
}
fill(&f[0][0], &f[0][0]+210*210, false);
for (auto i = 0; i < H; ++i) {
for (auto j = 0; j < W; ++j) {
f[i][j] = (m[i][j] == 'S');
}
}
ll ans = solve();
cout << ans << endl;
}
<commit_msg>tried D3.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W;
ll A, B;
bool f[210][210];
ll solve() {
bool x[110][110][4];
for (auto i = 1; i < H/2+1; ++i) {
for (auto j = 1; j < W/2+1; ++j) {
x[i][j][0] = f[i-1][j-1];
x[i][j][1] = f[H-1-i+1][j-1];
x[i][j][2] = f[i-1][W-1-j+1];
x[i][j][3] = f[H-1-i+1][W-1-j+1];
}
}
for (auto k = 0; k < 4; ++k) {
cerr << "k = " << k << endl;
for (auto i = 1; i < H/2+1; ++i) {
for (auto j = 1; j < W/2+1; ++j) {
cerr << (x[i][j][k] ? 'S' : '.');
}
cerr << endl;
}
}
ll ryoho = 0;
ll yobi = 0;
ll tate = 0;
ll yoko = 0;
for (auto i = 1; i < H/2+1; ++i) {
for (auto j = 1; j < W/2+1; ++j) {
int cnt = 0;
for (auto k = 0; k < 4; ++k) {
if (x[i][j][k]) cnt++;
}
if (cnt == 4) ryoho++;
if (cnt == 3) yobi++;
if (cnt == 2) {
if (x[i][j][0] == x[i][j][1] && x[i][j][2] == x[i][j][3]) {
tate++;
} else if (x[i][j][0] == x[i][j][2] && x[i][j][1] == x[i][j][3]) {
yoko++;
}
}
}
}
ll ans = 0;
ans = max(ans, ryoho * (A + B + A) + (yobi + tate) * A);
ans = max(ans, ryoho * (A + B + B) + (yobi + yoko) * B);
return ans + A + B;
}
int main () {
cin >> H >> W >> A >> B;
string m[210];
for (auto i = 0; i < H; ++i) {
cin >> m[i];
}
fill(&f[0][0], &f[0][0]+210*210, false);
for (auto i = 0; i < H; ++i) {
for (auto j = 0; j < W; ++j) {
f[i][j] = (m[i][j] == 'S');
}
}
ll ans = solve();
cout << ans << endl;
}
<|endoftext|> |
<commit_before>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2018-6-2 21:08:42
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
ll N, D;
ll X[100010];
ll L[100010];
ll R[100010];
ll sumR[100010];
ll sumL[100010];
ll cnt[100010];
int main()
{
cin >> N >> D;
for (auto i = 0; i < N; i++)
{
cin >> X[i];
}
for (auto i = 0; i < N; i++)
{
R[i] = i;
L[i] = i;
}
ll l = 0, r = 0;
while (r < N)
{
if (X[r] - X[l] <= D)
{
R[l] = r;
r++;
}
else
{
l++;
}
}
r = N - 1;
while (l < N)
{
if (X[r] - X[l] <= D)
{
R[l] = r;
l++;
}
else
{
l++;
}
}
l = N - 1;
while (l >= 0)
{
if (X[r] - X[l] <= D)
{
L[r] = l;
l--;
}
else
{
r--;
}
}
l = 0;
while (r >= 0)
{
if (X[r] - X[l] <= D)
{
L[r] = l;
r--;
}
else
{
r--;
}
}
sumR[0] = sumL[0] = 0;
for (auto i = 1; i <= N; i++)
{
sumR[i] = sumR[i - 1] + (R[i - 1] - (i - 1));
cerr << "sumR[" << i << "] = " << sumR[i] << endl;
}
for (auto i = 1; i <= N; i++)
{
sumL[i] = sumL[i - 1] + (i - 1 - L[i - 1]);
cerr << "sumL[" << i << "] = " << sumL[i] << endl;
}
for (auto j = 0; j < N; j++)
{
ll n = R[j] - (L[j] - 1) - 1;
cerr << "j = " << j << ", n = " << n << endl;
cnt[j] = n * (n - 1) / 2;
ll ext = sumR[R[j] + 1] - sumL[L[j]] - n;
cerr << "ext = " << ext << endl;
cnt[j] -= ext;
}
ll ans = 0;
for (auto i = 0; i < N; i++)
{
ans += cnt[i];
}
cout << ans << endl;
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2018-6-2 21:08:42
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
ll N, D;
ll X[100010];
ll L[100010];
ll R[100010];
ll sumR[100010];
ll sumL[100010];
ll cnt[100010];
int main()
{
cin >> N >> D;
for (auto i = 0; i < N; i++)
{
cin >> X[i];
}
for (auto i = 0; i < N; i++)
{
R[i] = i;
L[i] = i;
}
ll l = 0, r = 0;
while (r < N)
{
if (X[r] - X[l] <= D)
{
R[l] = r;
r++;
}
else
{
l++;
}
}
r = N - 1;
while (l < N)
{
if (X[r] - X[l] <= D)
{
R[l] = r;
l++;
}
else
{
l++;
}
}
l = N - 1;
while (l >= 0)
{
if (X[r] - X[l] <= D)
{
L[r] = l;
l--;
}
else
{
r--;
}
}
l = 0;
while (r >= 0)
{
if (X[r] - X[l] <= D)
{
L[r] = l;
r--;
}
else
{
r--;
}
}
sumR[0] = sumL[0] = 0;
for (auto i = 1; i <= N; i++)
{
sumR[i] = sumR[i - 1] + (R[i - 1] - (i - 1));
// cerr << "sumR[" << i << "] = " << sumR[i] << endl;
}
for (auto i = 1; i <= N; i++)
{
sumL[i] = sumL[i - 1] + (i - 1 - L[i - 1]);
// cerr << "sumL[" << i << "] = " << sumL[i] << endl;
}
for (auto j = 0; j < N; j++)
{
ll n = R[j] - (L[j] - 1) - 1;
// cerr << "j = " << j << ", n = " << n << endl;
cnt[j] = n * (n - 1) / 2;
ll ext = sumL[R[j] + 1] - sumR[L[j]] - n;
// cerr << "ext = " << ext << endl;
cnt[j] -= ext;
}
ll ans = 0;
for (auto i = 0; i < N; i++)
{
ans += cnt[i];
}
cout << ans << endl;
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 Google Inc. 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 Google Inc. 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 "config.h"
#include "WebScrollbarTheme.h"
#include "platform/scroll/ScrollbarThemeMacCommon.h"
using namespace WebCore;
namespace blink {
#if defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
COMPILE_ASSERT(ScrollerStyleLegacy == NSScrollerStyleLegacy, ScrollerStyle_Legacy_must_be_equal);
COMPILE_ASSERT(ScrollerStyleOverlay == NSScrollerStyleOverlay, ScrollerStyle_Overlay_must_be_equal);
#endif
void WebScrollbarTheme::updateScrollbars(
float initialButtonDelay, float autoscrollButtonDelay,
bool jumpOnTrackClick, bool redraw)
{
ScrollbarTheme* theme = ScrollbarTheme::theme();
if (theme->isMockTheme())
return;
static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged(
initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}
void WebScrollbarTheme::updateScrollbars(
float initialButtonDelay, float autoscrollButtonDelay,
bool jumpOnTrackClick, ScrollerStyle preferredScrollerStyle, bool redraw)
{
updateScrollbars(initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}
} // namespace blink
<commit_msg>mac: Fix build with 10.7+ sdk.<commit_after>/*
* Copyright (C) 2013 Google Inc. 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 Google Inc. 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 "config.h"
#include "WebScrollbarTheme.h"
#include "platform/scroll/ScrollbarThemeMacCommon.h"
using namespace WebCore;
namespace blink {
#if defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
// TODO(rsesek): Reenable this after making sure it actually builds.
//COMPILE_ASSERT(ScrollerStyleLegacy == NSScrollerStyleLegacy, ScrollerStyle_Legacy_must_be_equal);
//COMPILE_ASSERT(ScrollerStyleOverlay == NSScrollerStyleOverlay, ScrollerStyle_Overlay_must_be_equal);
#endif
void WebScrollbarTheme::updateScrollbars(
float initialButtonDelay, float autoscrollButtonDelay,
bool jumpOnTrackClick, bool redraw)
{
ScrollbarTheme* theme = ScrollbarTheme::theme();
if (theme->isMockTheme())
return;
static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged(
initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}
void WebScrollbarTheme::updateScrollbars(
float initialButtonDelay, float autoscrollButtonDelay,
bool jumpOnTrackClick, ScrollerStyle preferredScrollerStyle, bool redraw)
{
updateScrollbars(initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}
} // namespace blink
<|endoftext|> |
<commit_before>5e589383-2d16-11e5-af21-0401358ea401<commit_msg>5e589384-2d16-11e5-af21-0401358ea401<commit_after>5e589384-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>841fc4b0-2e4f-11e5-8248-28cfe91dbc4b<commit_msg>84291dd9-2e4f-11e5-894c-28cfe91dbc4b<commit_after>84291dd9-2e4f-11e5-894c-28cfe91dbc4b<|endoftext|> |
<commit_before>09d66a92-2f67-11e5-9987-6c40088e03e4<commit_msg>09dd503a-2f67-11e5-8a9a-6c40088e03e4<commit_after>09dd503a-2f67-11e5-8a9a-6c40088e03e4<|endoftext|> |
<commit_before>e7bd4607-2e4e-11e5-b183-28cfe91dbc4b<commit_msg>e7c3e659-2e4e-11e5-8e6d-28cfe91dbc4b<commit_after>e7c3e659-2e4e-11e5-8e6d-28cfe91dbc4b<|endoftext|> |
<commit_before>bf814330-2e4f-11e5-adf2-28cfe91dbc4b<commit_msg>bf8807f5-2e4f-11e5-8be2-28cfe91dbc4b<commit_after>bf8807f5-2e4f-11e5-8be2-28cfe91dbc4b<|endoftext|> |
<commit_before>5bf6735c-2d16-11e5-af21-0401358ea401<commit_msg>5bf6735d-2d16-11e5-af21-0401358ea401<commit_after>5bf6735d-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5f894998-2d16-11e5-af21-0401358ea401<commit_msg>5f894999-2d16-11e5-af21-0401358ea401<commit_after>5f894999-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <iostream>
#include <list>
#include <sstream>
#include <Ptakopysk/System/Assets.h>
#include <Ptakopysk/System/Events.h>
#include <Ptakopysk/System/GameManager.h>
#include <Ptakopysk/System/GameObject.h>
#include <Ptakopysk/Components/Transform.h>
#include <Ptakopysk/Components/SpriteRenderer.h>
#include <XeCore/Common/Logger.h>
#include <XeCore/Common/Concurrent/Thread.h>
using namespace Ptakopysk;
const int WINDOW_WIDTH = 1024;
const int WINDOW_HEIGHT = 574;
const sf::Color WINDOW_COLOR = sf::Color( 128, 128, 128, 255 );
void onEvent( Events::Event* ev )
{
}
int main()
{
/// initialization
LOG_SETUP( "log.log" );
Events::use().setCallback( &onEvent );
GameManager::initialize();
/// scene
sf::RenderWindow* window = xnew sf::RenderWindow(
sf::VideoMode( WINDOW_WIDTH, WINDOW_HEIGHT ),
"Floppy Disk",
sf::Style::Titlebar | sf::Style::Close
);
/// game manager
GameManager* gameManager = xnew GameManager();
gameManager->jsonToScene( gameManager->loadJson( "assets/scenes/game.json" ) );
gameManager->saveJson( "assets/scenes/_game.json", gameManager->sceneToJson() );
/// main loop
srand( time( 0 ) );
sf::Clock timer;
sf::Clock deltaTimer;
while( window->isOpen() )
{
sf::Event event;
while( window->pollEvent( event ) )
{
if( event.type == sf::Event::Closed )
{
window->close();
}
else if( event.type == sf::Event::KeyPressed )
{
if( event.key.code == sf::Keyboard::Escape )
window->close();
}
}
/// timers update
float dt = deltaTimer.getElapsedTime().asSeconds();
deltaTimer.restart();
/// process frame
Events::use().dispatch();
gameManager->processPhysics( dt );
gameManager->processUpdate( dt );
window->clear( WINDOW_COLOR );
gameManager->processRender( window );
window->display();
XeCore::Common::Concurrent::Thread::sleep( 1000 / 30 );
}
DELETE_OBJECT( window );
DELETE_OBJECT( gameManager );
Assets::destroy();
Events::destroy();
return 0;
}
<commit_msg>main.cpp includes cleanup<commit_after>#include <iostream>
#include <Ptakopysk/System/Assets.h>
#include <Ptakopysk/System/Events.h>
#include <Ptakopysk/System/GameManager.h>
#include <XeCore/Common/Logger.h>
#include <XeCore/Common/Concurrent/Thread.h>
using namespace Ptakopysk;
const int WINDOW_WIDTH = 1024;
const int WINDOW_HEIGHT = 574;
const sf::Color WINDOW_COLOR = sf::Color( 128, 128, 128, 255 );
void onEvent( Events::Event* ev )
{
}
int main()
{
/// initialization
LOG_SETUP( "log.log" );
Events::use().setCallback( &onEvent );
GameManager::initialize();
/// scene
sf::RenderWindow* window = xnew sf::RenderWindow(
sf::VideoMode( WINDOW_WIDTH, WINDOW_HEIGHT ),
"Floppy Disk",
sf::Style::Titlebar | sf::Style::Close
);
/// game manager
GameManager* gameManager = xnew GameManager();
gameManager->jsonToScene( gameManager->loadJson( "assets/scenes/game.json" ) );
gameManager->saveJson( "assets/scenes/_game.json", gameManager->sceneToJson() );
/// main loop
srand( time( 0 ) );
sf::Clock timer;
sf::Clock deltaTimer;
while( window->isOpen() )
{
sf::Event event;
while( window->pollEvent( event ) )
{
if( event.type == sf::Event::Closed )
{
window->close();
}
else if( event.type == sf::Event::KeyPressed )
{
if( event.key.code == sf::Keyboard::Escape )
window->close();
}
}
/// timers update
float dt = deltaTimer.getElapsedTime().asSeconds();
deltaTimer.restart();
/// process frame
Events::use().dispatch();
gameManager->processPhysics( dt );
gameManager->processUpdate( dt );
window->clear( WINDOW_COLOR );
gameManager->processRender( window );
window->display();
XeCore::Common::Concurrent::Thread::sleep( 1000 / 30 );
}
DELETE_OBJECT( window );
DELETE_OBJECT( gameManager );
Assets::destroy();
Events::destroy();
return 0;
}
<|endoftext|> |
<commit_before>84afb521-2e4f-11e5-b42d-28cfe91dbc4b<commit_msg>84b6e03d-2e4f-11e5-b17e-28cfe91dbc4b<commit_after>84b6e03d-2e4f-11e5-b17e-28cfe91dbc4b<|endoftext|> |
<commit_before>9101ae0c-2d14-11e5-af21-0401358ea401<commit_msg>9101ae0d-2d14-11e5-af21-0401358ea401<commit_after>9101ae0d-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5f8949b8-2d16-11e5-af21-0401358ea401<commit_msg>5f8949b9-2d16-11e5-af21-0401358ea401<commit_after>5f8949b9-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>1562f7b6-585b-11e5-b039-6c40088e03e4<commit_msg>156a8bdc-585b-11e5-860b-6c40088e03e4<commit_after>156a8bdc-585b-11e5-860b-6c40088e03e4<|endoftext|> |
<commit_before>8f4c3ad2-35ca-11e5-8bb0-6c40088e03e4<commit_msg>8f52bb12-35ca-11e5-a959-6c40088e03e4<commit_after>8f52bb12-35ca-11e5-a959-6c40088e03e4<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Ethereum client.
*/
#include <fstream>
#include <iostream>
#include <liblll/Compiler.h>
#include <libethsupport/CommonIO.h>
#include <libethsupport/CommonData.h>
#include "BuildInfo.h"
using namespace std;
using namespace eth;
void help()
{
cout
<< "Usage lllc [OPTIONS] <file>" << endl
<< "Options:" << endl
<< " -h,--help Show this help message and exit." << endl
<< " -V,--version Show the version and exit." << endl;
exit(0);
}
void version()
{
cout << "LLLC, the Lovely Little Language Compiler " << ETH_QUOTED(ETH_VERSION) << endl;
cout << " By Gav Wood, (c) 2014." << endl;
cout << "Build: " << ETH_QUOTED(ETH_BUILD_PLATFORM) << "/" << ETH_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
enum Mode { Binary, Hex, ParseTree };
int main(int argc, char** argv)
{
string infile;
Mode mode = Hex;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-b" || arg == "--binary")
mode = Binary;
else if (arg == "-h" || arg == "--hex")
mode = Hex;
else if (arg == "-t" || arg == "--parse-tree")
mode = ParseTree;
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
string src;
if (infile.empty())
{
string s;
while (!cin.eof())
{
getline(cin, s);
src.append(s);
}
}
else
src = asString(contents(infile));
if (src.empty())
cerr << "Empty file." << endl;
else if (mode == Binary || mode == Hex)
{
vector<string> errors;
auto bs = compileLLL(src, &errors);
if (mode == Hex)
cout << toHex(bs) << endl;
else if (mode == Binary)
cout.write((char const*)bs.data(), bs.size());
for (auto const& i: errors)
cerr << i << endl;
}
else if (mode == ParseTree)
{
cout << parseLLL(src) << endl;
}
return 0;
}
<commit_msg>Ever more repotting.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Ethereum client.
*/
#include <fstream>
#include <iostream>
#include <liblll/Compiler.h>
#include <libethsupport/CommonIO.h>
#include <libethsupport/CommonData.h>
#include "BuildInfo.h"
using namespace std;
using namespace eth;
void help()
{
cout
<< "Usage lllc [OPTIONS] <file>" << endl
<< "Options:" << endl
<< " -b,--binary Parse, compile and assemble; output byte code in binary." << endl
<< " -x,--hex Parse, compile and assemble; output byte code in hex." << endl
// << " -a,--assembly Only parse and compile; show assembly." << endl
<< " -t,--parse-tree Only parse; show parse tree." << endl
<< " -h,--help Show this help message and exit." << endl
<< " -V,--version Show the version and exit." << endl;
exit(0);
}
void version()
{
cout << "LLLC, the Lovely Little Language Compiler " << ETH_QUOTED(ETH_VERSION) << endl;
cout << " By Gav Wood, (c) 2014." << endl;
cout << "Build: " << ETH_QUOTED(ETH_BUILD_PLATFORM) << "/" << ETH_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
enum Mode { Binary, Hex, ParseTree };
int main(int argc, char** argv)
{
string infile;
Mode mode = Hex;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-b" || arg == "--binary")
mode = Binary;
else if (arg == "-x" || arg == "--hex")
mode = Hex;
else if (arg == "-t" || arg == "--parse-tree")
mode = ParseTree;
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
string src;
if (infile.empty())
{
string s;
while (!cin.eof())
{
getline(cin, s);
src.append(s);
}
}
else
src = asString(contents(infile));
if (src.empty())
cerr << "Empty file." << endl;
else if (mode == Binary || mode == Hex)
{
vector<string> errors;
auto bs = compileLLL(src, &errors);
if (mode == Hex)
cout << toHex(bs) << endl;
else if (mode == Binary)
cout.write((char const*)bs.data(), bs.size());
for (auto const& i: errors)
cerr << i << endl;
}
else if (mode == ParseTree)
{
cout << parseLLL(src) << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>8c3d2137-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2138-2d14-11e5-af21-0401358ea401<commit_after>8c3d2138-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>bae95bb0-4b02-11e5-a0b9-28cfe9171a43<commit_msg>Initial commit.13<commit_after>baf77d8c-4b02-11e5-a923-28cfe9171a43<|endoftext|> |
<commit_before>bb0fd712-35ca-11e5-9319-6c40088e03e4<commit_msg>bb166906-35ca-11e5-b6f5-6c40088e03e4<commit_after>bb166906-35ca-11e5-b6f5-6c40088e03e4<|endoftext|> |
<commit_before>a31ba507-4b02-11e5-8213-28cfe9171a43<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>a32d318a-4b02-11e5-a4c5-28cfe9171a43<|endoftext|> |
<commit_before>4b7d13cf-2e4f-11e5-bd5d-28cfe91dbc4b<commit_msg>4b83d2ae-2e4f-11e5-bf6a-28cfe91dbc4b<commit_after>4b83d2ae-2e4f-11e5-bf6a-28cfe91dbc4b<|endoftext|> |
<commit_before>c7198982-327f-11e5-a35c-9cf387a8033e<commit_msg>c720571e-327f-11e5-8d13-9cf387a8033e<commit_after>c720571e-327f-11e5-8d13-9cf387a8033e<|endoftext|> |
<commit_before>53c2ed4a-ad5c-11e7-bac2-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>5453138f-ad5c-11e7-be2f-ac87a332f658<|endoftext|> |
<commit_before>9861c56e-327f-11e5-96b2-9cf387a8033e<commit_msg>9867a128-327f-11e5-b2e6-9cf387a8033e<commit_after>9867a128-327f-11e5-b2e6-9cf387a8033e<|endoftext|> |
<commit_before>d0b7332e-327f-11e5-a919-9cf387a8033e<commit_msg>d0bd624c-327f-11e5-a331-9cf387a8033e<commit_after>d0bd624c-327f-11e5-a331-9cf387a8033e<|endoftext|> |
<commit_before>92323afd-2d14-11e5-af21-0401358ea401<commit_msg>92323afe-2d14-11e5-af21-0401358ea401<commit_after>92323afe-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7ccf7b94-2749-11e6-bab1-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>7ce0528f-2749-11e6-9980-e0f84713e7b8<|endoftext|> |
<commit_before>4723a7ee-2e3a-11e5-8024-c03896053bdd<commit_msg>473425b0-2e3a-11e5-950f-c03896053bdd<commit_after>473425b0-2e3a-11e5-950f-c03896053bdd<|endoftext|> |
<commit_before>ce560d34-35ca-11e5-b2a0-6c40088e03e4<commit_msg>ce5d6b5e-35ca-11e5-b152-6c40088e03e4<commit_after>ce5d6b5e-35ca-11e5-b152-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include "Coordinate.h"
#include "Maze.h"
using std::vector;
using std::string;
const Coordinate dirs[] = {
Coordinate( -1, 0 ),
Coordinate( 0, 1 ),
Coordinate( 0, -1 ),
Coordinate( 1, 0 )
};
const char left[] = { 'a', 'h' };
const char down[] = { 's', 'j' };
const char up[] = { 'w', 'k' };
const char right[] = { 'd', 'l' };
bool isPartOf( const char arr[], char val ){
return arr[0] == val || arr[1] == val;
}
int main(){
std::cout << "program begin" << std::endl << std::endl;
int w = 21, h = 21;
string inputW, inputH;
std::cout << "maze width (20): ";
std::getline( std::cin, inputW );
if( !inputW.empty() )
w = std::stoi( inputW );
std::cout << "maze height (20): ";
std::getline( std::cin, inputH );
if( !inputH.empty() )
h = std::stoi( inputH );
if( w % 2 == 0 )
w += 1;
if( h % 2 == 0 )
h += 1;
Maze maze( w, h );
vector<vector<char>> map;
Coordinate player( 1, 1 );
string dir;
int round = 0;
int security = 1000;
while( --security > 0 && !( player.x == maze.goal.x && player.y == maze.goal.y ) ){
std::cout << "start frame" << std::endl;
maze.fillPrintMap( map );
map[ player.x ][ player.y ] = 'o';
std::system( "clear" );
std::cout << std::endl << " Round: " << ++round << "\t pos: [" << player.x << "," << player.y << "]" << std::endl << std::endl;
for( int i = 0; i < h; ++i ){
std::cout << " ";
for( int j = 0; j < w; ++j ){
std::cout << map[j][i];
}
std::cout << std::endl;
}
std::cout << std::endl << " next moves (hjkl/aswd+ENTER): ";
std::cin >> dir;
unsigned int dirIndex = -1;
while( ++dirIndex < dir.length() ){
if( isPartOf( left, dir[ dirIndex ] ) && !maze.getCell( player + dirs[0] ) ){
player = player + dirs[ 0 ];
}
if( isPartOf( down, dir[ dirIndex ] ) && !maze.getCell( player + dirs[1] ) ){
player = player + dirs[ 1 ];
}
if( isPartOf( up, dir[ dirIndex ] ) && !maze.getCell( player + dirs[2] ) ){
player = player + dirs[ 2 ];
}
if( isPartOf( right, dir[ dirIndex ] ) && !maze.getCell( player + dirs[3] ) ){
player = player + dirs[ 3 ];
}
}
}
if( security == 0 )
std::cout << "took too much, we were afraid the program broke" << std::endl;
else
std::cout << "YOU WIN!" << std::endl;
std::cout << std::endl << "program end" << std::endl;
return 0;
}
<commit_msg>changed `isPartOf` to `arrayContains`<commit_after>#include <iostream>
#include <vector>
#include <string>
#include "Coordinate.h"
#include "Maze.h"
using std::vector;
using std::string;
const Coordinate dirs[] = {
Coordinate( -1, 0 ),
Coordinate( 0, 1 ),
Coordinate( 0, -1 ),
Coordinate( 1, 0 )
};
const char left[] = { 'a', 'h' };
const char down[] = { 's', 'j' };
const char up[] = { 'w', 'k' };
const char right[] = { 'd', 'l' };
bool arrayContains( const char arr[], char val ){
return arr[0] == val || arr[1] == val;
}
int main(){
std::cout << "program begin" << std::endl << std::endl;
int w = 21, h = 21;
string inputW, inputH;
std::cout << "maze width (20): ";
std::getline( std::cin, inputW );
if( !inputW.empty() )
w = std::stoi( inputW );
std::cout << "maze height (20): ";
std::getline( std::cin, inputH );
if( !inputH.empty() )
h = std::stoi( inputH );
if( w % 2 == 0 )
w += 1;
if( h % 2 == 0 )
h += 1;
Maze maze( w, h );
vector<vector<char>> map;
Coordinate player( 1, 1 );
string dir;
int round = 0;
int security = 1000;
while( --security > 0 && !( player.x == maze.goal.x && player.y == maze.goal.y ) ){
std::cout << "start frame" << std::endl;
maze.fillPrintMap( map );
map[ player.x ][ player.y ] = 'o';
std::system( "clear" );
std::cout << std::endl << " Round: " << ++round << "\t pos: [" << player.x << "," << player.y << "]" << std::endl << std::endl;
for( int i = 0; i < h; ++i ){
std::cout << " ";
for( int j = 0; j < w; ++j ){
std::cout << map[j][i];
}
std::cout << std::endl;
}
std::cout << std::endl << " next moves (hjkl/aswd+ENTER): ";
std::cin >> dir;
unsigned int dirIndex = -1;
while( ++dirIndex < dir.length() ){
if( arrayContains( left, dir[ dirIndex ] ) && !maze.getCell( player + dirs[0] ) ){
player = player + dirs[ 0 ];
}
if( arrayContains( down, dir[ dirIndex ] ) && !maze.getCell( player + dirs[1] ) ){
player = player + dirs[ 1 ];
}
if( arrayContains( up, dir[ dirIndex ] ) && !maze.getCell( player + dirs[2] ) ){
player = player + dirs[ 2 ];
}
if( arrayContains( right, dir[ dirIndex ] ) && !maze.getCell( player + dirs[3] ) ){
player = player + dirs[ 3 ];
}
}
}
if( security == 0 )
std::cout << "took too much, we were afraid the program broke" << std::endl;
else
std::cout << "YOU WIN!" << std::endl;
std::cout << std::endl << "program end" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>2e9a7538-2e4f-11e5-b2dc-28cfe91dbc4b<commit_msg>2ea182ee-2e4f-11e5-9771-28cfe91dbc4b<commit_after>2ea182ee-2e4f-11e5-9771-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include "camera.h"
#include "scene.h"
#include "sphere.h"
#include "bsdf.h"
#include "integrator.h"
using std::cout;
int main(int argc, char** args)
{
Scene scene;
BRDF* b = new Diffuse{1.0};
BRDF* light = new EmissiveBRDF{spectrum{4.0}};
// scene.add_shape( new Shape( new Sphere{ Vec3{-1.0, -1.0, 0.5}, 0.5},
// light,
// new SolidColor(spectrum{1.0})) );
scene.add_shape( new Shape( new Sphere{ Vec3{2.0, -1.0, 0.0}, 1.0},
b,
new SolidColor(spectrum{1.0, 0.2, 0.3})) );
scene.add_shape( new Shape( new Sphere{ Vec3{1.0, 1.0, 0.5}, 0.05},
light,
new SolidColor(spectrum{1.0})) );
scene.add_shape( new Shape( new Sphere{ Vec3{-2.0, 1.0, 0.0}, 1.0},
b,
new SolidColor(spectrum{0.2, 1.0, 0.3})) );
scene.add_shape( new Shape( new Sphere{ Vec3{0.0, -1000.0, 0.0}, 998.0},
b,
new SolidColor(spectrum{0.0, 0.0, 1.0})) );
const uint WIDTH = 800;
const uint HEIGHT = 600;
Film f(WIDTH, HEIGHT);
Camera cam {Vec3{0, 0, 5}, Vec3{0, 0, 0}, Vec3{0, 1, 0}, PI / 2.0, scalar(WIDTH)/HEIGHT};
PathTracerIntegrator igr;
igr.render(&cam, &scene, &f);
//f.render_to_console(cout);
f.render_to_ppm(cout, new BoxFilter, new LinearToneMapper);
return 0;
}
<commit_msg>Default scene modification, to include mirrors<commit_after>#include <iostream>
#include "camera.h"
#include "scene.h"
#include "sphere.h"
#include "bsdf.h"
#include "integrator.h"
using std::cout;
void smallpt_scene(Scene& scene)
{
BRDF* diffuse = new Diffuse{1.0};
BRDF* light = new EmissiveBRDF{spectrum{12.0}};
scene.add_shape(new Shape(new Sphere{ Vec3{1e5+1, 40.8, 81.6}, 1e5 },
diffuse,
new SolidColor(spectrum{0.75,0.25,0.25})));
scene.add_shape(new Shape(new Sphere{ Vec3{-1e5+99, 40.8, 81.6}, 1e5 },
diffuse,
new SolidColor(spectrum{0.25, 0.25, 0.75})));
scene.add_shape(new Shape(new Sphere{Vec3{50, 40.8, 1e5}, 1e5},
diffuse,
new SolidColor(spectrum{0.75})));
scene.add_shape(new Shape(new Sphere{Vec3{50, 1e5, 81.6}, 1e5},
diffuse,
new SolidColor(spectrum{0.75})));
scene.add_shape(new Shape(new Sphere{Vec3{50, -1e5+81.6, 81.6}, 1e5},
diffuse,
new SolidColor(spectrum{0.75})));
scene.add_shape(new Shape(new Sphere{Vec3{50,681.6-.27,81.6}, 600},
light,
new SolidColor(spectrum{1.0})));
}
int main(int argc, char** args)
{
Scene scene;
BRDF* b = new Diffuse{1.0};
BRDF* light = new EmissiveBRDF{spectrum{4.0}};
BRDF* mirror = new PerfectMirrorBRDF{};
//smallpt_scene(scene);
scene.add_shape( new Shape( new Sphere{ Vec3{-2.0, -1.0, 0.0}, 1.0},
mirror,
new SolidColor(spectrum{1.0})) );
scene.add_shape( new Shape( new Sphere{ Vec3{2.0, -1.0, 0.0}, 1.0},
b,
new SolidColor(spectrum{1.0, 0.2, 0.3})) );
scene.add_shape( new Shape( new Sphere{ Vec3{-2.0, 1.0, 0.0}, 1.0},
b,
new SolidColor(spectrum{0.2, 1.0, 0.3})) );
scene.add_shape( new Shape( new Sphere{ Vec3{0.0, -1000.0, 0.0}, 998.0},
b,
new SolidColor(spectrum{0.1, 0.2, 0.9})));
scene.add_shape( new Shape( new Sphere{ Vec3{0.0, 3.0, 1.0}, 0.05},
light,
new SolidColor(spectrum{1.0})) );
const uint WIDTH = 800;
const uint HEIGHT = 600;
Film f(WIDTH, HEIGHT);
Camera cam {Vec3{0, 0, 5}, Vec3{0, 0, 0}, Vec3{0, 1, 0}, PI / 2.0,
scalar(WIDTH)/HEIGHT};
// Vec3 pos{50, 52, 295.6};
// Vec3 dir = Vec3{0, -0.042612, -1}.normal();
// Camera cam{ pos, pos+dir, Vec3{0, 1, 0}, PI/2.0, scalar(WIDTH)/HEIGHT};
PathTracerIntegrator igr;
igr.render(&cam, &scene, &f);
//f.render_to_console(cout);
f.render_to_ppm(cout, new BoxFilter, new LinearToneMapper);
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.