<commit_before>{
  TProof::Open("pod://");
  if (!gProof) return;

  TDSet *manual_dset = new TDSet("TTree", "deuterons");
  TString user[3] = {"m/mpuccio","m/masera","s/sbufalin"};
  for (int i = 0; i < 3; ++i)
  {
    TString ddset = Form("Find;BasePath=/alice/cern.ch/user/%s/NucleiPbPb2011test/output;FileName=*/root_archive.zip;Anchor=mpuccio_Flowdnt.root;Tree=/deuterons;Mode=local",user[i].Data());

    TFileCollection *fc = gProof->GetDataSet(ddset.Data());

  // Create TDSet manually (terrible hack): apparently PROOF is stupid
  // and cannot create it correctly
    TFileInfo *fi;
    TIter next( fc->GetList() );
    while (( fi = (TFileInfo *)next() )) {
      const char *fn = fi->GetCurrentUrl()->GetUrl();
      Printf("adding: %s", fn);
      manual_dset->Add( fn );
    }
  }

  const double kCent[4] = {0.,10.,30.,50.};
  const double kBins[29] = {
    0.4f,0.5f,0.6f,0.7f,0.8f,0.9f,1.0f,1.1f,1.2f,1.4f,
    1.6f,1.8f,2.0f,2.2f,2.4f,2.6f,2.8f,3.0f,3.2f,3.4f,
    3.6f,3.8f,4.0f,4.2f,4.4f,5.0f,6.0f,8.0f,10.f
  };
  TH2F *hBins = new TH2F("hBins","hBins",3,kCent,28,kBins);
  TH1D *hCuts = new TH1D("hCuts","hCuts",10,0,10);
  TNamed *taskTitle = new TNamed("taskName","deuteron3cent");
  enum cutsName {kEtaMin=1,kEtaMax,kYMin,kYMax,kTPCsig,kTPCchi2,kSPDrec,kDCAxy,kDCAz,kRecreate};
  double cutsA[10] = {-0.8,0.8,-0.5,0.5,70,4.,1,0.5,1,1};
  for (int i = 1; i < 11; ++i) {
    hCuts->SetBinContent(i,cutsA[i - 1]);
  }
  gProof->AddInput(hBins);
  gProof->AddInput(hCuts);
  gProof->AddInput(taskTitle);

  // Process the TDset
  gProof->Process(manual_dset, "AODSelector.cxx+g");

  // Other cuts
  hCuts->SetBinContent(10,0.);
  hCuts->SetBinContent(5,60);
  taskTitle.SetTitle("deuteron3cent_chi0");
  gProof->Process(manual_dset, "AODSelector.cxx+g");

}
<commit_msg>Complete cut variation in the steering macro (first attempt)<commit_after>{
  TProof::Open("pod://");
  if (!gProof) return;

  TDSet *manual_dset = new TDSet("TTree", "deuterons");
  TString user[3] = {"m/mpuccio","m/masera","s/sbufalin"};
  for (int i = 0; i < 3; ++i)
  {
    TString ddset = Form("Find;BasePath=/alice/cern.ch/user/%s/NucleiPbPb2011test/output;FileName=*/root_archive.zip;Anchor=mpuccio_Flowdnt.root;Tree=/deuterons;Mode=local",user[i].Data());

    TFileCollection *fc = gProof->GetDataSet(ddset.Data());

  // Create TDSet manually (terrible hack): apparently PROOF is stupid
  // and cannot create it correctly
    TFileInfo *fi;
    TIter next( fc->GetList() );
    while (( fi = (TFileInfo *)next() )) {
      const char *fn = fi->GetCurrentUrl()->GetUrl();
      Printf("adding: %s", fn);
      manual_dset->Add( fn );
    }
  }

  const double kCent[4] = {0.,10.,30.,50.};
  const double kBins[29] = {
    0.4f,0.5f,0.6f,0.7f,0.8f,0.9f,1.0f,1.1f,1.2f,1.4f,
    1.6f,1.8f,2.0f,2.2f,2.4f,2.6f,2.8f,3.0f,3.2f,3.4f,
    3.6f,3.8f,4.0f,4.2f,4.4f,5.0f,6.0f,8.0f,10.f
  };
  TH2F *hBins = new TH2F("hBins","hBins",3,kCent,28,kBins);
  TH1D *hCuts = new TH1D("hCuts","hCuts",10,0,10);
  TNamed *taskTitle = new TNamed("taskName","deuteron3cent");
  enum cutsName {kEtaMin=1,kEtaMax,kYMin,kYMax,kTPCsig,kTPCchi2,kSPDrec,kDCAxy,kDCAz,kRecreate};
  double cutsA[10] = {-0.8,0.8,-0.5,0.5,70,4.,1,0.5,1,1};
  for (int i = 1; i < 11; ++i) {
    hCuts->SetBinContent(i,cutsA[i - 1]);
  }
  gProof->AddInput(hBins);
  gProof->AddInput(hCuts);
  gProof->AddInput(taskTitle);

  // Process the TDset
  gProof->Process(manual_dset, "AODSelector.cxx+g");

  // Other cuts
  hCuts->SetBinContent(10,0.);
  // chi2
  hCuts->SetBinContent(5,3.5);
  taskTitle->SetTitle("deuteron3cent_chi0");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(5,4.5);
  taskTitle->SetTitle("deuteron3cent_chi1");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(5,5);
  taskTitle->SetTitle("deuteron3cent_chi2");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(5,5.5);
  taskTitle->SetTitle("deuteron3cent_chi3");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(5,6.);
  taskTitle->SetTitle("deuteron3cent_chi4");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(5,4.);
  // dca_z
  hCuts->SetBinContent(9,0.5);
  taskTitle->SetTitle("deuteron3cent_dcaz0");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(9,0.75);
  taskTitle->SetTitle("deuteron3cent_dcaz1");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(9,1.5);
  taskTitle->SetTitle("deuteron3cent_dcaz2");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(9,2.);
  taskTitle->SetTitle("deuteron3cent_dcaz3");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(9,1.);
  // tpc
  hCuts->SetBinContent(4,60);
  taskTitle->SetTitle("deuteron3cent_tpc0");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(4,65);
  taskTitle->SetTitle("deuteron3cent_tpc1");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(4,75);
  taskTitle->SetTitle("deuteron3cent_tpc2");
  gProof->Process(manual_dset, "AODSelector.cxx+g");
  hCuts->SetBinContent(4,80);
  taskTitle->SetTitle("deuteron3cent_tpc3");
  gProof->Process(manual_dset, "AODSelector.cxx+g");

}
<|endoftext|>


<commit_before>/*
1. Treat each edge id as a cluster, unordered map from edgeId to a set
2. also store size of each cluster which will 0 in the begining
//  $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp
//  $ ./calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  Nthresholds threshDensity.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <map>
#include <utility>   // for pairs
#include <algorithm> // for swap
using namespace std;

int main (int argc, char const *argv[]){
    //************* make sure args are present:
    if (argc != 6){
        cout << "ERROR: something wrong with the inputs" << endl;
        cout << "usage:\n    " << argv[0] << " networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  "
                    << " Nthresholds threshDensity.csv" << endl;
        exit(1);
    }
    // Nthresholds is the total thresholds user wants us to try
    int nThresh = atoi(argv[4]);
    cout << "nThresh = " << nThresh << endl;
    int gapBetweenthresh = 0;
    float threshold = 0;
    float D = 0.0;
    int mc, nc;
    int M = 0, Mns = 0;
    double wSum = 0.0;
    float highestD=0.0;
    float highestDThr = 0.0;
    //************* got the args
    clock_t begin = clock();

    //************* start load edgelist
    ifstream inFile;
    inFile.open( argv[1] );
    if (!inFile) {
        cout << "ERROR: unable to open input file" << endl;
        exit(1); // terminate with error
    }
    // store edge ids in a map
    // each edge id will be a cluster of it's own in the begining
    // each cluster will be og size 1
    map< int,  pair<int,int> > idEdgePairMap;
    map< int,  set<int > > index2cluster; // O(log n) access too slow?
    map< int,  map< int, set<int > >::iterator > edge2iter;
    int ni, nj, edgeId, index = 0;
    while (inFile >> ni >> nj >> edgeId){
        idEdgePairMap[ edgeId ] = make_pair(ni,nj);
        index2cluster[ index ].insert(edgeId);         // build cluster index to set of edge-pairs map
        edge2iter[edgeId] = index2cluster.find(index);
        index++;
    }
    inFile.close(); inFile.clear();
    cout << "There were " << index2cluster.size() << " edges. ";
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    /// end reading edge ids -----

    //----- ----- ----- -----
    ifstream sortedjaccFile;
    sortedjaccFile.open( argv[3] );
    if (!sortedjaccFile) {
        cout << "ERROR: unable to open sortedjaccFile file" << endl;
        exit(1); // terminate with error
    }
    int totalThresh = 0;
    int edgeId1,edgeId2;
    double jacc;
    // Count totalines in the file, we are setting
    while ( sortedjaccFile  >> jacc ) {
        if(jacc>0 && jacc<=1.0)
            totalThresh++;
    }
    sortedjaccFile.close(); sortedjaccFile.clear();
    cout << "Done counting totalines in the file, \nTotal unique Jaccs = " << totalThresh;
    cout << ".  Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    if(totalThresh==0){
        cout << "ERROR: there are 0 Jaccs!!!" << endl;
        exit(1); // terminate with error
    }
    // now we want gap between two consecutive thresholds
    // we want to consider
    gapBetweenthresh =  totalThresh/nThresh;
    if(totalThresh < nThresh)
            gapBetweenthresh = totalThresh;
    set<float> thresholdSet;
    set<float> ::reverse_iterator thIt;
    cout << "thresholds" << endl;
    // ----------------------------
    totalThresh = -1;
    sortedjaccFile.open( argv[3] );
    while ( sortedjaccFile  >> jacc ){
        totalThresh++;
        if(totalThresh%gapBetweenthresh!=0){
            continue;
        }
        cout << jacc << endl;
        thresholdSet.insert(jacc);
    }
    sortedjaccFile.close(); sortedjaccFile.clear();
    thresholdSet.insert(1.1);
    cout << "Done with thresholdSet creation.";
    cout << "  Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    // ---------------------------

    ifstream jaccFile;
    jaccFile.open(argv[2]);
    // read first line
    jaccFile >> edgeId1 >> edgeId2 >> jacc ;
    // open the outputfile
    map< int, set< int> >::iterator iter_i,iter_j;
    set<int>::iterator iterS;
    FILE * threshDensityFile = fopen( argv[5], "w" );
    fclose(threshDensityFile);
    fprintf( threshDensityFile, "thresh  D\n" );
    long long done = 0;
    float percDone = 0.01;
    clock_t lastBegin = clock();
    for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
        threshold = *thIt;
        if (threshold < 0.0 || threshold > 1.11){
            cout << "ERROR: specified threshold not in [0,1]: " << threshold << endl;
            exit(1);
        }
        cout << " Starting new clustering...... " ;
        do{
            if( jacc < threshold )
                break;
            iter_i = edge2iter[ edgeId1 ];
            iter_j = edge2iter[ edgeId2 ];
            if ( iter_i != iter_j ) {
                //cout << edgeId1 << " " << edgeId2 << " " << jacc << endl;
                // always merge smaller cluster into bigger:
                if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!!
                    swap(iter_i, iter_j);
                }
                // merge cluster j into i and update index for all elements in j:
                //cout << "merging cluster " << endl;
                for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){
                    iter_i->second.insert( *iterS );
                    edge2iter[ *iterS ] = iter_i;
                }

                // delete cluster j:
                cout << "Deleting cluster " << endl;
                index2cluster.erase(iter_j);
                cout << "Done deleteing " << endl;
            }
        }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );
        cout << " Done!" << endl;
        // all done clustering, write to file (and calculated partition density):
        M = 0, Mns = 0;
        wSum = 0.0;
        set< int >::iterator S;
        set<int> clusterNodes;
        map< int, set< int > >::iterator it;
        for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {
            clusterNodes.clear();
            for (S = it->second.begin(); S != it->second.end(); S++ ){
                //fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...!
                clusterNodes.insert(idEdgePairMap[*S].first);
                clusterNodes.insert(idEdgePairMap[*S].second);
            }
            mc = it->second.size();
            nc = clusterNodes.size();
            M += mc;
            if (nc > 2) {
                Mns  += mc;
                wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0));
            }
        }
        threshDensityFile = fopen( argv[5], "a" );
        D = 2.0 * wSum / M;
        if (isinf(D)){
            fprintf( threshDensityFile, "\nERROR: D == -inf \n\n");
            fclose(threshDensityFile);
            exit(1);
        }
        //*************
        fprintf( threshDensityFile, "%.6f %.6f \n", threshold, D);
        fclose(threshDensityFile);
        if(D > highestD){
            highestD = D;
            highestDThr = threshold;
        }
        done++;
        if((float)done/(float)thresholdSet.size() >= percDone){
            cout << percDone*100 << " pc done.\n" << endl;
            percDone += 0.01;
        }
        cout << "Time taken = " << double(clock() - lastBegin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
        lastBegin = clock();
    }
    jaccFile.close(); jaccFile.clear();
    fprintf( threshDensityFile, "\n highest D=%.6f at thresh:%.6f.\n", highestD, highestDThr);
    fclose(threshDensityFile);
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    return 0;
}
<commit_msg>Update calcDensityForDiffThresh.cpp<commit_after>/*
1. Treat each edge id as a cluster, unordered map from edgeId to a set
2. also store size of each cluster which will 0 in the begining
//  $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp
//  $ ./calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  Nthresholds threshDensity.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <map>
#include <utility>   // for pairs
#include <algorithm> // for swap
using namespace std;

int main (int argc, char const *argv[]){
    //************* make sure args are present:
    if (argc != 6){
        cout << "ERROR: something wrong with the inputs" << endl;
        cout << "usage:\n    " << argv[0] << " networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  "
                    << " Nthresholds threshDensity.csv" << endl;
        exit(1);
    }
    // Nthresholds is the total thresholds user wants us to try
    int nThresh = atoi(argv[4]);
    cout << "nThresh = " << nThresh << endl;
    int gapBetweenthresh = 0;
    float threshold = 0;
    float D = 0.0;
    int mc, nc;
    int M = 0, Mns = 0;
    double wSum = 0.0;
    float highestD=0.0;
    float highestDThr = 0.0;
    //************* got the args
    clock_t begin = clock();

    //************* start load edgelist
    ifstream inFile;
    inFile.open( argv[1] );
    if (!inFile) {
        cout << "ERROR: unable to open input file" << endl;
        exit(1); // terminate with error
    }
    // store edge ids in a map
    // each edge id will be a cluster of it's own in the begining
    // each cluster will be og size 1
    map< int,  pair<int,int> > idEdgePairMap;
    map< int,  set<int > > index2cluster; // O(log n) access too slow?
    map< int,  map< int, set<int > >::iterator > edge2iter;
    int ni, nj, edgeId, index = 0;
    while (inFile >> ni >> nj >> edgeId){
        idEdgePairMap[ edgeId ] = make_pair(ni,nj);
        index2cluster[ index ].insert(edgeId);         // build cluster index to set of edge-pairs map
        edge2iter[edgeId] = index2cluster.find(index);
        index++;
    }
    inFile.close(); inFile.clear();
    cout << "There were " << index2cluster.size() << " edges. ";
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    /// end reading edge ids -----

    //----- ----- ----- -----
    ifstream sortedjaccFile;
    sortedjaccFile.open( argv[3] );
    if (!sortedjaccFile) {
        cout << "ERROR: unable to open sortedjaccFile file" << endl;
        exit(1); // terminate with error
    }
    int totalThresh = 0;
    int edgeId1,edgeId2;
    double jacc;
    // Count totalines in the file, we are setting
    while ( sortedjaccFile  >> jacc ) {
        if(jacc>0 && jacc<=1.0)
            totalThresh++;
    }
    sortedjaccFile.close(); sortedjaccFile.clear();
    cout << "Done counting totalines in the file, \nTotal unique Jaccs = " << totalThresh;
    cout << ".  Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    if(totalThresh==0){
        cout << "ERROR: there are 0 Jaccs!!!" << endl;
        exit(1); // terminate with error
    }
    // now we want gap between two consecutive thresholds
    // we want to consider
    gapBetweenthresh =  totalThresh/nThresh;
    if(totalThresh < nThresh)
            gapBetweenthresh = totalThresh;
    set<float> thresholdSet;
    set<float> ::reverse_iterator thIt;
    cout << "thresholds" << endl;
    // ----------------------------
    totalThresh = -1;
    sortedjaccFile.open( argv[3] );
    while ( sortedjaccFile  >> jacc ){
        totalThresh++;
        if(totalThresh%gapBetweenthresh!=0){
            continue;
        }
        cout << jacc << endl;
        thresholdSet.insert(jacc);
    }
    sortedjaccFile.close(); sortedjaccFile.clear();
    thresholdSet.insert(1.1);
    cout << "Done with thresholdSet creation.";
    cout << "  Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    // ---------------------------

    ifstream jaccFile;
    jaccFile.open(argv[2]);
    // read first line
    jaccFile >> edgeId1 >> edgeId2 >> jacc ;
    // open the outputfile
    map< int, set< int> >::iterator iter_i,iter_j;
    set<int>::iterator iterS;
    FILE * threshDensityFile = fopen( argv[5], "w" );
    fclose(threshDensityFile);
    fprintf( threshDensityFile, "thresh  D\n" );
    long long done = 0;
    float percDone = 0.01;
    clock_t lastBegin = clock();
    for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
        threshold = *thIt;
        if (threshold < 0.0 || threshold > 1.11){
            cout << "ERROR: specified threshold not in [0,1]: " << threshold << endl;
            exit(1);
        }
        cout << " Starting new clustering...... " ;
        do{
            if( jacc < threshold )
                break;
            iter_i = edge2iter[ edgeId1 ];
            iter_j = edge2iter[ edgeId2 ];
            if ( iter_i != iter_j ) {
                //cout << edgeId1 << " " << edgeId2 << " " << jacc << endl;
                // always merge smaller cluster into bigger:
                if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!!
                    swap(iter_i, iter_j);
                }
                // merge cluster j into i and update index for all elements in j:
                //cout << "merging cluster " << endl;
                for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){
                    iter_i->second.insert( *iterS );
                    edge2iter[ *iterS ] = iter_i;
                }

                // delete cluster j:
                //cout << "Deleting cluster " << endl;
                index2cluster.erase(iter_j);
                //cout << "Done deleteing " << endl;
            }
        }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );
        cout << " Done!" << endl;
        // all done clustering, write to file (and calculated partition density):
        M = 0, Mns = 0;
        wSum = 0.0;
        set< int >::iterator S;
        set<int> clusterNodes;
        map< int, set< int > >::iterator it;
        for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {
            clusterNodes.clear();
            for (S = it->second.begin(); S != it->second.end(); S++ ){
                //fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...!
                clusterNodes.insert(idEdgePairMap[*S].first);
                clusterNodes.insert(idEdgePairMap[*S].second);
            }
            mc = it->second.size();
            nc = clusterNodes.size();
            M += mc;
            if (nc > 2) {
                Mns  += mc;
                wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0));
            }
        }
        threshDensityFile = fopen( argv[5], "a" );
        D = 2.0 * wSum / M;
        if (isinf(D)){
            fprintf( threshDensityFile, "\nERROR: D == -inf \n\n");
            fclose(threshDensityFile);
            exit(1);
        }
        //*************
        fprintf( threshDensityFile, "%.6f %.6f \n", threshold, D);
        fclose(threshDensityFile);
        if(D > highestD){
            highestD = D;
            highestDThr = threshold;
        }
        done++;
        if((float)done/(float)thresholdSet.size() >= percDone){
            cout << percDone*100 << " pc done.\n" << endl;
            percDone += 0.01;
        }
        cout << "Time taken = " << double(clock() - lastBegin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
        lastBegin = clock();
    }
    jaccFile.close(); jaccFile.clear();
    fprintf( threshDensityFile, "\n highest D=%.6f at thresh:%.6f.\n", highestD, highestDThr);
    fclose(threshDensityFile);
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    return 0;
}
<|endoftext|>


<commit_before>/*
1. Treat each edge id as a cluster, unordered map from edgeId to a set
2. also store size of each cluster which will 0 in the begining
//  $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp
//  $ ./calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  Nthresholds threshDensity.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <set>
#include <map>
#include <utility>   // for pairs
#include <algorithm> // for swap
using namespace std;

int main (int argc, char const *argv[]){
    //************* make sure args are present:
    if (argc != 4){
        cout << "ERROR: something wrong with the inputs" << endl;
        cout << "usage:\n    " << argv[0] << " networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  "
                    << " Nthresholds threshDensity.csv" << endl;
        exit(1);
    }
    // Nthresholds is the total thresholds user wants us to try
    int nThresh = atoi(argv[4]);
    int gapBetweenthresh = 0;
    float threshold = 0;
    float D = 0.0;
    int mc, nc;
    int M = 0, Mns = 0;
    double wSum = 0.0;
    float highestD=0.0;
    float highestDThr = 0.0;
    //************* got the args
    clock_t begin = clock();

    //************* start load edgelist
    ifstream inFile;
    inFile.open( argv[1] );
    if (!inFile) {
        cout << "ERROR: unable to open input file" << endl;
        exit(1); // terminate with error
    }
    // store edge ids in a map
    // each edge id will be a cluster of it's own in the begining
    // each cluster will be og size 1
    unordered_map< int,  pair<int,int> > idEdgePairMap;
    unordered_map< int,  set<int > > index2cluster; // O(log n) access too slow?
    unordered_map< int,  unordered_map< int, set<int > >::iterator > edge2iter;
    int ni, nj, edgeId, index = 0;
    while (inFile >> ni >> nj >> edgeId){
        idEdgePairMap[ edgeId ] = make_pair(ni,nj);
        index2cluster[ index ].insert(edgeId);         // build cluster index to set of edge-pairs map
        edge2iter[edgeId] = index2cluster.find(index);
        index++;
    }
    inFile.close(); inFile.clear();
    cout << "There were " << index2cluster.size() << " edges." << endl;
    /// end reading edge ids -----

    //----- ----- ----- -----
    ifstream sortedjaccFile;
    sortedjaccFile.open( argv[3] );
    if (!sortedjaccFile) {
        cout << "ERROR: unable to open sortedjaccFile file" << endl;
        exit(1); // terminate with error
    }
    int totalThresh = 0;
    int edgeId1,edgeId2;
    float jacc;
    // Count totalines in the file, we are setting
    while ( sortedjaccFile  >> jacc ) {
        if(jacc>0 && jacc<=1.0)
            totalThresh++;
    }
    sortedjaccFile.close(); sortedjaccFile.clear();
    cout << "Done counting totalines in the file, \nTotal unique Jaccs = " << totalThresh << endl;
    if(totalThresh==0){
        cout << "ERROR: there are 0 Jaccs!!!" << endl;
        exit(1); // terminate with error
    }
    // now we want gap between two consecutive thresholds
    // we want to consider
    gapBetweenthresh =  totalThresh/nThresh;
    if(totalThresh < nThresh)
            gapBetweenthresh = totalThresh;
    set<float> thresholdSet;
    set<float> ::reverse_iterator thIt;
    // ----------------------------
    totalThresh = -1;
    sortedjaccFile.open( argv[3] );
    while ( sortedjaccFile  >> jacc ){
        totalThresh++;
        if(totalThresh%gapBetweenthresh!=0){
            continue;
        }
        thresholdSet.insert(jacc);
    }
    thresholdSet.insert(1.1);
    cout << "Done with thresholdSet creation." << endl;
    // ---------------------------

    ifstream jaccFile;
    jaccFile.open(argv[2]);
    // read first line
    jaccFile >> edgeId1 >> edgeId2 >> jacc ;
    // open the outputfile
    unordered_map< int, set< int> >::iterator iter_i,iter_j;
    set<int>::iterator iterS;
    FILE * threshDensityFile = fopen( argv[3], "w" );
    fclose(threshDensityFile);
    fprintf( threshDensityFile, "thresh  D\n" );
    for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
        threshold = *thIt;
        if (threshold < 0.0 || threshold > 1.0){
            cout << "ERROR: specified threshold not in [0,1]" << endl;
            exit(1);
        }
        do{
            if( jacc < threshold )
                break;
            iter_i = edge2iter[ edgeId1 ];
            iter_j = edge2iter[ edgeId2 ];
            if ( iter_i != iter_j ) {
                // always merge smaller cluster into bigger:
                if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!!
                    swap(iter_i, iter_j);
                }
                // merge cluster j into i and update index for all elements in j:
                for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){
                    iter_i->second.insert( *iterS );
                    edge2iter[ *iterS ] = iter_i;
                }
                // delete cluster j:
                index2cluster.erase(iter_j);
            }
        }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );

        // all done clustering, write to file (and calculated partition density):
        M = 0, Mns = 0;
        wSum = 0.0;
        set< int >::iterator S;
        set<int> clusterNodes;
        unordered_map< int, set< int > >::iterator it;
        for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {
            clusterNodes.clear();
            for (S = it->second.begin(); S != it->second.end(); S++ ){
                //fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...!
                clusterNodes.insert(idEdgePairMap[*S].first);
                clusterNodes.insert(idEdgePairMap[*S].second);
            }
            mc = it->second.size();
            nc = clusterNodes.size();
            M += mc;
            if (nc > 2) {
                Mns  += mc;
                wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0));
            }
        }
        threshDensityFile = fopen( argv[3], "a" );
        D = 2.0 * wSum / M;
        if (isinf(D)){
            fprintf( threshDensityFile, "\nERROR: D == -inf \n\n");
            fclose(threshDensityFile);
            exit(1);
        }
        //*************
        fprintf( threshDensityFile, "%.6f %.6f ", threshold, D);
        fclose(threshDensityFile);
        if(D > highestD){
            highestD = D;
            highestDThr = threshold;
        }
    }
    jaccFile.close(); jaccFile.clear();
    fprintf( threshDensityFile, "\n highest D=%.6f at thresh:%.6f.\n", highestD, highestDThr);
    fclose(threshDensityFile);
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    return 0;
}
<commit_msg>Update calcDensityForDiffThresh.cpp<commit_after>/*
1. Treat each edge id as a cluster, unordered map from edgeId to a set
2. also store size of each cluster which will 0 in the begining
//  $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp
//  $ ./calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  Nthresholds threshDensity.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <set>
#include <map>
#include <utility>   // for pairs
#include <algorithm> // for swap
using namespace std;

int main (int argc, char const *argv[]){
    //************* make sure args are present:
    if (argc != 4){
        cout << "ERROR: something wrong with the inputs" << endl;
        cout << "usage:\n    " << argv[0] << " networkEdgeIdMap.csv network.jaccs sortedjaccs.csv  "
                    << " Nthresholds threshDensity.csv" << endl;
        exit(1);
    }
    // Nthresholds is the total thresholds user wants us to try
    int nThresh = atoi(argv[4]);
    int gapBetweenthresh = 0;
    float threshold = 0;
    float D = 0.0;
    int mc, nc;
    int M = 0, Mns = 0;
    double wSum = 0.0;
    float highestD=0.0;
    float highestDThr = 0.0;
    //************* got the args
    clock_t begin = clock();

    //************* start load edgelist
    ifstream inFile;
    inFile.open( argv[1] );
    if (!inFile) {
        cout << "ERROR: unable to open input file" << endl;
        exit(1); // terminate with error
    }
    // store edge ids in a map
    // each edge id will be a cluster of it's own in the begining
    // each cluster will be og size 1
    unordered_map< int,  pair<int,int> > idEdgePairMap;
    unordered_map< int,  set<int > > index2cluster; // O(log n) access too slow?
    unordered_map< int,  unordered_map< int, set<int > >::iterator > edge2iter;
    int ni, nj, edgeId, index = 0;
    while (inFile >> ni >> nj >> edgeId){
        idEdgePairMap[ edgeId ] = make_pair(ni,nj);
        index2cluster[ index ].insert(edgeId);         // build cluster index to set of edge-pairs map
        edge2iter[edgeId] = index2cluster.find(index);
        index++;
    }
    inFile.close(); inFile.clear();
    cout << "There were " << index2cluster.size() << " edges." << endl;
    /// end reading edge ids -----

    //----- ----- ----- -----
    ifstream sortedjaccFile;
    sortedjaccFile.open( argv[3] );
    if (!sortedjaccFile) {
        cout << "ERROR: unable to open sortedjaccFile file" << endl;
        exit(1); // terminate with error
    }
    int totalThresh = 0;
    int edgeId1,edgeId2;
    float jacc;
    // Count totalines in the file, we are setting
    while ( sortedjaccFile  >> jacc ) {
        if(jacc>0 && jacc<=1.0)
            totalThresh++;
    }
    sortedjaccFile.close(); sortedjaccFile.clear();
    cout << "Done counting totalines in the file, \nTotal unique Jaccs = " << totalThresh << endl;
    if(totalThresh==0){
        cout << "ERROR: there are 0 Jaccs!!!" << endl;
        exit(1); // terminate with error
    }
    // now we want gap between two consecutive thresholds
    // we want to consider
    gapBetweenthresh =  totalThresh/nThresh;
    if(totalThresh < nThresh)
            gapBetweenthresh = totalThresh;
    set<float> thresholdSet;
    set<float> ::reverse_iterator thIt;
    // ----------------------------
    totalThresh = -1;
    sortedjaccFile.open( argv[3] );
    while ( sortedjaccFile  >> jacc ){
        totalThresh++;
        if(totalThresh%gapBetweenthresh!=0){
            continue;
        }
        thresholdSet.insert(jacc);
    }
    thresholdSet.insert(1.1);
    cout << "Done with thresholdSet creation." << endl;
    // ---------------------------

    ifstream jaccFile;
    jaccFile.open(argv[2]);
    // read first line
    jaccFile >> edgeId1 >> edgeId2 >> jacc ;
    // open the outputfile
    unordered_map< int, set< int> >::iterator iter_i,iter_j;
    set<int>::iterator iterS;
    FILE * threshDensityFile = fopen( argv[3], "w" );
    fclose(threshDensityFile);
    fprintf( threshDensityFile, "thresh  D\n" );
    long long done = 0;
    float percDone = 0.01;
    clock_t lastBegin = clock();
    for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
        threshold = *thIt;
        if (threshold < 0.0 || threshold > 1.0){
            cout << "ERROR: specified threshold not in [0,1]" << endl;
            exit(1);
        }
        do{
            if( jacc < threshold )
                break;
            iter_i = edge2iter[ edgeId1 ];
            iter_j = edge2iter[ edgeId2 ];
            if ( iter_i != iter_j ) {
                // always merge smaller cluster into bigger:
                if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!!
                    swap(iter_i, iter_j);
                }
                // merge cluster j into i and update index for all elements in j:
                for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){
                    iter_i->second.insert( *iterS );
                    edge2iter[ *iterS ] = iter_i;
                }
                // delete cluster j:
                index2cluster.erase(iter_j);
            }
        }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );
        // all done clustering, write to file (and calculated partition density):
        M = 0, Mns = 0;
        wSum = 0.0;
        set< int >::iterator S;
        set<int> clusterNodes;
        unordered_map< int, set< int > >::iterator it;
        for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {
            clusterNodes.clear();
            for (S = it->second.begin(); S != it->second.end(); S++ ){
                //fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...!
                clusterNodes.insert(idEdgePairMap[*S].first);
                clusterNodes.insert(idEdgePairMap[*S].second);
            }
            mc = it->second.size();
            nc = clusterNodes.size();
            M += mc;
            if (nc > 2) {
                Mns  += mc;
                wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0));
            }
        }
        threshDensityFile = fopen( argv[3], "a" );
        D = 2.0 * wSum / M;
        if (isinf(D)){
            fprintf( threshDensityFile, "\nERROR: D == -inf \n\n");
            fclose(threshDensityFile);
            exit(1);
        }
        //*************
        fprintf( threshDensityFile, "%.6f %.6f \n", threshold, D);
        fclose(threshDensityFile);
        if(D > highestD){
            highestD = D;
            highestDThr = threshold;
        }
        done++;
        if((float)done/(float)thresholdSet.size() >= percDone){
            cout << percDone*100 << " pc done.\n" << endl;
            percDone += 0.01;
        }
        cout << "Time taken = " << double(clock() - lastBegin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
        lastBegin = clock();
    }
    jaccFile.close(); jaccFile.clear();
    fprintf( threshDensityFile, "\n highest D=%.6f at thresh:%.6f.\n", highestD, highestDThr);
    fclose(threshDensityFile);
    cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
    return 0;
}
<|endoftext|>


<commit_before>//
// TreeView.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "App.h"
#include "TreeView.h"
#include "MenuEnum.h"	// for LayerTree_Ctrl
#include "Frame.h"
#include "BuilderView.h"

DECLARE_APP(MyApp)

// Under Windows, the icons are in the .rc file; on Unix, they are included
// from .xpm files.
#ifndef __WXMSW__
#include "building.xpm"
#include "file1.xpm"
#include "file2.xpm"
#include "folder1.xpm"
#include "folder2.xpm"
#include "folder3.xpm"

#include "grid.xpm"
#include "image.xpm"
#include "raw.xpm"
#include "road.xpm"
#include "veg1.xpm"
#include "water.xpm"
#include "util.xpm"
#include "transit.xpm"
#endif

/////////////////////////////////////////////////

// MyTreeCtrl implementation
IMPLEMENT_DYNAMIC_CLASS(MyTreeCtrl, wxTreeCtrl)

MyTreeCtrl::MyTreeCtrl(wxWindow *parent, const wxWindowID id,
	const wxPoint& pos, const wxSize& size,
	long style)
: wxTreeCtrl(parent, id, pos, size, style)
{
	m_reverseSort = false;
	m_imageListNormal = NULL;
	m_bShowPaths = true;

	CreateImageList(16);

	// Add some items to the tree
	RefreshTreeItems(NULL);
}

void MyTreeCtrl::CreateImageList(int size)
{
	delete m_imageListNormal;

	if ( size == -1 )
	{
		m_imageListNormal = NULL;
		return;
	}

	// Make an image list containing small icons
	m_imageListNormal = new wxImageList(size, size, TRUE);

	// should correspond to TreeCtrlIcon_xxx enum
	wxIcon icons[14];
	icons[0] = wxICON(file1);
	icons[1] = wxICON(file2);
	icons[2] = wxICON(folder1);
	icons[3] = wxICON(folder2);
	icons[4] = wxICON(folder3);
	icons[5] = wxICON(building);
	icons[6] = wxICON(road);
	icons[7] = wxICON(grid);
	icons[8] = wxICON(image);
	icons[9] = wxICON(veg1);
	icons[10] = wxICON(water);
	icons[11] = wxICON(transit);
	icons[12] = wxICON(util);
	icons[13] = wxICON(raw);

	int sizeOrig = icons[0].GetWidth();
	for ( size_t i = 0; i < WXSIZEOF(icons); i++ )
	{
		if ( size == sizeOrig )
			m_imageListNormal->Add(icons[i]);
		else
			m_imageListNormal->Add(wxImage(icons[i]).Rescale(size, size).
				ConvertToBitmap());
	}

	SetImageList(m_imageListNormal);
}

MyTreeCtrl::~MyTreeCtrl()
{
	delete m_imageListNormal;
}

int MyTreeCtrl::OnCompareItems(const wxTreeItemId& item1,
	const wxTreeItemId& item2)
{
	if ( m_reverseSort )
	{
		// just exchange 1st and 2nd items
		return wxTreeCtrl::OnCompareItems(item2, item1);
	}
	else
	{
		return wxTreeCtrl::OnCompareItems(item1, item2);
	}
}

wxTreeItemId rootId;

wxTreeItemId MyTreeCtrl::AddRootItem(int image, const char *text)
{
	wxTreeItemId id = AppendItem(rootId, text, image);
	SetItemBold(id);
	return id;
}

wxString MyTreeCtrl::MakeItemName(vtLayerPtr lp)
{
	wxString str;
	if (lp->GetModified())
		str += "(*) ";
	wxString fullpath = lp->GetFilename();
	if (!m_bShowPaths)
	{
		if (fullpath.Find('/') != -1)
			fullpath = fullpath.AfterLast('/');
		if (fullpath.Find('\\') != -1)
			fullpath = fullpath.AfterLast('\\');
		if (fullpath.Find(':') != -1)
			fullpath = fullpath.AfterLast(':');
	}
	str += fullpath;
	return str;
}

void MyTreeCtrl::RefreshTreeItems(MainFrame *pFrame)
{
	DeleteAllItems();

	rootId = AddRoot("Layers");
	SetItemBold(rootId);

	int	image, imageSel;

	wxTreeItemId elevId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Grid, "Elevation");
#ifndef ELEVATION_ONLY
	wxTreeItemId imageId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Image, "Images");
	wxTreeItemId buildId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Building, "Structures");
	wxTreeItemId roadId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Road, "Roads");
	wxTreeItemId vegId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Veg1, "Vegetation");
	wxTreeItemId waterId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Water, "Water");
#if SUPPORT_TRANSIT
	wxTreeItemId transId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Transit, "Transit");
#endif
	wxTreeItemId utilityId = AddRootItem(MyTreeCtrl::TreeCtrlIcon_Utility, "Utilities");
#endif
	wxTreeItemId rawId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Raw, "Raw");

	image = TreeCtrlIcon_File;
	imageSel = TreeCtrlIcon_FileSelected;
	vtLayerPtr lp;
	int iLayers = 0;
	if (pFrame) iLayers = pFrame->m_Layers.GetSize();
	for (int i = 0; i < iLayers; i++)
	{
		lp = pFrame->m_Layers.GetAt(i);

		wxString str = MakeItemName(lp);

		wxTreeItemId hItem = -1;
		switch (lp->GetType())
		{
			case LT_ELEVATION:
				hItem = AppendItem(elevId, str, image, imageSel);
				break;
#ifndef ELEVATION_ONLY
			case LT_IMAGE:
				hItem = AppendItem(imageId, str, image, imageSel);
				break;
			case LT_ROAD:
				hItem = AppendItem(roadId, str, image, imageSel);
				break;
			case LT_STRUCTURE:
				hItem = AppendItem(buildId, str, image, imageSel);
				break;
			case LT_VEG:
				hItem = AppendItem(vegId, str, image, imageSel);
				break;
			case LT_WATER:
				hItem = AppendItem(waterId, str, image, imageSel);
				break;
#if SUPPORT_TRANSIT
			case LT_TRANSIT:
				hItem = AppendItem(transId, str, image, imageSel);
				break;
#endif
			case LT_UTILITY:
				hItem = AppendItem(utilityId, str, image, imageSel);
				break;
#endif
			case LT_RAW:
				hItem = AppendItem(rawId, str, image, imageSel);
				break;
		}
		if (hItem != -1)
		{
			SetItemData(hItem, new MyTreeItemData(lp));

			if (lp == pFrame->GetActiveLayer())
				SelectItem(hItem);
		}
	}

	Expand(rootId);
	Expand(elevId);
#ifndef ELEVATION_ONLY
	Expand(imageId);
	Expand(roadId);
	Expand(buildId);
	Expand(vegId);
	Expand(waterId);
#if SUPPORT_TRANSIT
	Expand(transId);
#endif
	Expand(utilityId);
#endif
	Expand(rawId);
}

void MyTreeCtrl::RefreshTreeStatus(MainFrame *pFrame)
{
	wxTreeItemId root = GetRootItem();
	wxTreeItemId parent, item;
	long cookie = 0, cookie2 = 1;

	for (parent = GetFirstChild(root, cookie); parent; parent = GetNextChild(root, cookie))
	{
//		wxString str = GetItemText(parent);
		for (item = GetFirstChild(parent, cookie2); item; item = GetNextChild(parent, cookie2))
		{
			MyTreeItemData *data = (MyTreeItemData *)GetItemData(item);
//			wxString str2 = GetItemText(item);
			if (data)
			{
				SetItemText(item, MakeItemName(data->m_pLayer));
				if (data->m_pLayer == pFrame->GetActiveLayer())
					SelectItem(item);
			}
		}
	}
}

// avoid repetition
#define TREE_EVENT_HANDLER(name)			\
void MyTreeCtrl::name(wxTreeEvent& event)	\
{											\
	event.Skip();							\
}

TREE_EVENT_HANDLER(OnBeginRDrag)
	TREE_EVENT_HANDLER(OnDeleteItem)
	TREE_EVENT_HANDLER(OnGetInfo)
	TREE_EVENT_HANDLER(OnSetInfo)
	TREE_EVENT_HANDLER(OnItemExpanded)
	TREE_EVENT_HANDLER(OnItemExpanding)
	TREE_EVENT_HANDLER(OnItemCollapsed)
	TREE_EVENT_HANDLER(OnSelChanging)
	TREE_EVENT_HANDLER(OnTreeKeyDown)

#undef TREE_EVENT_HANDLER

	void MyTreeCtrl::OnSelChanged(wxTreeEvent& event)
{
	wxTreeItemId item = event.GetItem();
	MyTreeItemData *data = (MyTreeItemData *)GetItemData(item);
	vtLayerPtr lp = NULL;
	if (data)
		lp = data->m_pLayer;

	vtLayerPtr last = GetMainFrame()->GetActiveLayer();
	if (lp != last)
		GetMainFrame()->GetView()->SetActiveLayer(lp);

	LayerType last_ltype = last ? last->GetType() : LT_UNKNOWN;
	if (lp && lp->GetType() != last_ltype)
		GetMainFrame()->RefreshToolbar();
}

void MyTreeCtrl::OnBeginDrag(wxTreeEvent& event)
{
}

void MyTreeCtrl::OnEndDrag(wxTreeEvent& event)
{
}

void MyTreeCtrl::OnBeginLabelEdit(wxTreeEvent& event)
{
#if 0
	wxLogMessage("OnBeginLabelEdit");

	// for testing, prevent this items label editing
	wxTreeItemId itemId = event.GetItem();
	if ( IsTestItem(itemId) )
	{
		wxMessageBox("You can't edit this item.");

		event.Veto();
	}
#endif
}

void MyTreeCtrl::OnEndLabelEdit(wxTreeEvent& event)
{
#if 0
	wxLogMessage("OnEndLabelEdit");

	// don't allow anything except letters in the labels
	if ( !event.GetLabel().IsWord() )
	{
		wxMessageBox("The label should contain only letters.");

		event.Veto();
	}
#endif
}

void MyTreeCtrl::OnItemCollapsing(wxTreeEvent& event)
{
#if 0
	wxLogMessage("OnItemCollapsing");

	// for testing, prevent the user from collapsing the first child folder
	wxTreeItemId itemId = event.GetItem();
	if ( IsTestItem(itemId) )
	{
		wxMessageBox("You can't collapse this item.");

		event.Veto();
	}
#endif
}

void MyTreeCtrl::OnItemActivated(wxTreeEvent& event)
{
#if 0
	// show some info about this item
	wxTreeItemId itemId = event.GetItem();
	MyTreeItemData *item = (MyTreeItemData *)GetItemData(itemId);

	if ( item != NULL )
	{
		item->ShowInfo(this);
	}
	wxLogMessage("OnItemActivated");
#endif
}

void MyTreeCtrl::OnRMouseDClick(wxMouseEvent& event)
{
#if 0
	wxTreeItemId id = HitTest(event.GetPosition());
	if ( !id )
		wxLogMessage("No item under mouse");
	else
	{
		MyTreeItemData *item = (MyTreeItemData *)GetItemData(id);
		if ( item )
			wxLogMessage("Item '%s' under mouse", item->GetDesc());
	}
#endif
}

/////////////////////////////////////////////////

BEGIN_EVENT_TABLE(MyTreeCtrl, wxTreeCtrl)
EVT_TREE_BEGIN_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginDrag)
EVT_TREE_BEGIN_RDRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginRDrag)
EVT_TREE_END_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnEndDrag)
EVT_TREE_BEGIN_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnBeginLabelEdit)
EVT_TREE_END_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnEndLabelEdit)
EVT_TREE_DELETE_ITEM(LayerTree_Ctrl, MyTreeCtrl::OnDeleteItem)
EVT_TREE_SET_INFO(LayerTree_Ctrl, MyTreeCtrl::OnSetInfo)
EVT_TREE_ITEM_EXPANDED(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanded)
EVT_TREE_ITEM_EXPANDING(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanding)
EVT_TREE_ITEM_COLLAPSED(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsed)
EVT_TREE_ITEM_COLLAPSING(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsing)
EVT_TREE_SEL_CHANGED(LayerTree_Ctrl, MyTreeCtrl::OnSelChanged)
EVT_TREE_SEL_CHANGING(LayerTree_Ctrl, MyTreeCtrl::OnSelChanging)
EVT_TREE_KEY_DOWN(LayerTree_Ctrl, MyTreeCtrl::OnTreeKeyDown)
EVT_TREE_ITEM_ACTIVATED(LayerTree_Ctrl, MyTreeCtrl::OnItemActivated)
EVT_RIGHT_DCLICK(MyTreeCtrl::OnRMouseDClick)
END_EVENT_TABLE()
<commit_msg>tweak<commit_after>//
// TreeView.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "App.h"
#include "TreeView.h"
#include "MenuEnum.h"	// for LayerTree_Ctrl
#include "Frame.h"
#include "BuilderView.h"

DECLARE_APP(MyApp)

// Under Windows, the icons are in the .rc file; on Unix, they are included
// from .xpm files.
#ifndef __WXMSW__
#include "building.xpm"
#include "file1.xpm"
#include "file2.xpm"
#include "folder1.xpm"
#include "folder2.xpm"
#include "folder3.xpm"

#include "grid.xpm"
#include "image.xpm"
#include "raw.xpm"
#include "road.xpm"
#include "veg1.xpm"
#include "water.xpm"
#include "util.xpm"
#include "transit.xpm"
#endif

/////////////////////////////////////////////////

// MyTreeCtrl implementation
IMPLEMENT_DYNAMIC_CLASS(MyTreeCtrl, wxTreeCtrl)

MyTreeCtrl::MyTreeCtrl(wxWindow *parent, const wxWindowID id,
	const wxPoint& pos, const wxSize& size,
	long style)
: wxTreeCtrl(parent, id, pos, size, style)
{
	m_reverseSort = false;
	m_imageListNormal = NULL;
	m_bShowPaths = true;

	CreateImageList(16);

	// Add some items to the tree
	RefreshTreeItems(NULL);
}

void MyTreeCtrl::CreateImageList(int size)
{
	delete m_imageListNormal;

	if ( size == -1 )
	{
		m_imageListNormal = NULL;
		return;
	}

	// Make an image list containing small icons
	m_imageListNormal = new wxImageList(size, size, TRUE);

	// should correspond to TreeCtrlIcon_xxx enum
	wxIcon icons[14];
	icons[0] = wxICON(file1);
	icons[1] = wxICON(file2);
	icons[2] = wxICON(folder1);
	icons[3] = wxICON(folder2);
	icons[4] = wxICON(folder3);
	icons[5] = wxICON(building);
	icons[6] = wxICON(road);
	icons[7] = wxICON(grid);
	icons[8] = wxICON(image);
	icons[9] = wxICON(veg1);
	icons[10] = wxICON(water);
	icons[11] = wxICON(transit);
	icons[12] = wxICON(util);
	icons[13] = wxICON(raw);

	int sizeOrig = icons[0].GetWidth();
	for ( size_t i = 0; i < WXSIZEOF(icons); i++ )
	{
		if ( size == sizeOrig )
			m_imageListNormal->Add(icons[i]);
		else
			m_imageListNormal->Add(wxImage(icons[i]).Rescale(size, size).
				ConvertToBitmap());
	}

	SetImageList(m_imageListNormal);
}

MyTreeCtrl::~MyTreeCtrl()
{
	delete m_imageListNormal;
}

int MyTreeCtrl::OnCompareItems(const wxTreeItemId& item1,
	const wxTreeItemId& item2)
{
	if ( m_reverseSort )
	{
		// just exchange 1st and 2nd items
		return wxTreeCtrl::OnCompareItems(item2, item1);
	}
	else
	{
		return wxTreeCtrl::OnCompareItems(item1, item2);
	}
}

wxTreeItemId rootId;

wxTreeItemId MyTreeCtrl::AddRootItem(int image, const char *text)
{
	wxTreeItemId id = AppendItem(rootId, text, image);
	SetItemBold(id);
	return id;
}

wxString MyTreeCtrl::MakeItemName(vtLayerPtr lp)
{
	wxString str;
	if (lp->GetModified())
		str += "(*) ";
	wxString fullpath = lp->GetFilename();
	if (!m_bShowPaths)
	{
		if (fullpath.Find('/') != -1)
			fullpath = fullpath.AfterLast('/');
		if (fullpath.Find('\\') != -1)
			fullpath = fullpath.AfterLast('\\');
		if (fullpath.Find(':') != -1)
			fullpath = fullpath.AfterLast(':');
	}
	str += fullpath;
	return str;
}

void MyTreeCtrl::RefreshTreeItems(MainFrame *pFrame)
{
	DeleteAllItems();

	rootId = AddRoot("Layers");
	SetItemBold(rootId);

	int	image, imageSel;

	wxTreeItemId elevId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Grid, "Elevation");
#ifndef ELEVATION_ONLY
	wxTreeItemId imageId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Image, "Images");
	wxTreeItemId buildId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Building, "Structures");
	wxTreeItemId roadId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Road, "Roads");
	wxTreeItemId vegId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Veg1, "Vegetation");
	wxTreeItemId waterId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Water, "Water");
#if SUPPORT_TRANSIT
	wxTreeItemId transId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Transit, "Transit");
#endif
	wxTreeItemId utilityId = AddRootItem(MyTreeCtrl::TreeCtrlIcon_Utility, "Utilities");
#endif
	wxTreeItemId rawId =	AddRootItem(MyTreeCtrl::TreeCtrlIcon_Raw, "Raw");

	image = TreeCtrlIcon_File;
	imageSel = TreeCtrlIcon_FileSelected;
	vtLayerPtr lp;
	int iLayers = 0;
	if (pFrame) iLayers = pFrame->m_Layers.GetSize();
	for (int i = 0; i < iLayers; i++)
	{
		lp = pFrame->m_Layers.GetAt(i);

		wxString str = MakeItemName(lp);

		wxTreeItemId hItem = -1;
		switch (lp->GetType())
		{
			case LT_ELEVATION:
				hItem = AppendItem(elevId, str, image, imageSel);
				break;
#ifndef ELEVATION_ONLY
			case LT_IMAGE:
				hItem = AppendItem(imageId, str, image, imageSel);
				break;
			case LT_ROAD:
				hItem = AppendItem(roadId, str, image, imageSel);
				break;
			case LT_STRUCTURE:
				hItem = AppendItem(buildId, str, image, imageSel);
				break;
			case LT_VEG:
				hItem = AppendItem(vegId, str, image, imageSel);
				break;
			case LT_WATER:
				hItem = AppendItem(waterId, str, image, imageSel);
				break;
#if SUPPORT_TRANSIT
			case LT_TRANSIT:
				hItem = AppendItem(transId, str, image, imageSel);
				break;
#endif
			case LT_UTILITY:
				hItem = AppendItem(utilityId, str, image, imageSel);
				break;
#endif
			case LT_RAW:
				hItem = AppendItem(rawId, str, image, imageSel);
				break;
		}
		if (hItem != -1)
		{
			SetItemData(hItem, new MyTreeItemData(lp));

			if (lp == pFrame->GetActiveLayer())
				SelectItem(hItem);
		}
	}

	Expand(rootId);
	Expand(elevId);
#ifndef ELEVATION_ONLY
	Expand(imageId);
	Expand(roadId);
	Expand(buildId);
	Expand(vegId);
	Expand(waterId);
#if SUPPORT_TRANSIT
	Expand(transId);
#endif
	Expand(utilityId);
#endif
	Expand(rawId);
}

void MyTreeCtrl::RefreshTreeStatus(MainFrame *pFrame)
{
	wxTreeItemId root = GetRootItem();
	wxTreeItemId parent, item;
	long cookie = 0, cookie2 = 1;

	for (parent = GetFirstChild(root, cookie); parent; parent = GetNextChild(root, cookie))
	{
		for (item = GetFirstChild(parent, cookie2); item; item = GetNextChild(parent, cookie2))
		{
			MyTreeItemData *data = (MyTreeItemData *)GetItemData(item);
			if (data)
			{
				SetItemText(item, MakeItemName(data->m_pLayer));
				if (data->m_pLayer == pFrame->GetActiveLayer())
					SelectItem(item);
			}
		}
	}
}

// avoid repetition
#define TREE_EVENT_HANDLER(name)			\
void MyTreeCtrl::name(wxTreeEvent& event)	\
{											\
	event.Skip();							\
}

TREE_EVENT_HANDLER(OnBeginRDrag)
	TREE_EVENT_HANDLER(OnDeleteItem)
	TREE_EVENT_HANDLER(OnGetInfo)
	TREE_EVENT_HANDLER(OnSetInfo)
	TREE_EVENT_HANDLER(OnItemExpanded)
	TREE_EVENT_HANDLER(OnItemExpanding)
	TREE_EVENT_HANDLER(OnItemCollapsed)
	TREE_EVENT_HANDLER(OnSelChanging)
	TREE_EVENT_HANDLER(OnTreeKeyDown)

#undef TREE_EVENT_HANDLER

void MyTreeCtrl::OnSelChanged(wxTreeEvent& event)
{
	wxTreeItemId item = event.GetItem();
	MyTreeItemData *data = (MyTreeItemData *)GetItemData(item);
	vtLayerPtr lp = NULL;
	if (data)
		lp = data->m_pLayer;

	vtLayerPtr last = GetMainFrame()->GetActiveLayer();
	if (lp != last)
		GetMainFrame()->GetView()->SetActiveLayer(lp);

	LayerType last_ltype = last ? last->GetType() : LT_UNKNOWN;
	if (lp && lp->GetType() != last_ltype)
		GetMainFrame()->RefreshToolbar();
}

void MyTreeCtrl::OnBeginDrag(wxTreeEvent& event)
{
}

void MyTreeCtrl::OnEndDrag(wxTreeEvent& event)
{
}

void MyTreeCtrl::OnBeginLabelEdit(wxTreeEvent& event)
{
#if 0
	wxLogMessage("OnBeginLabelEdit");

	// for testing, prevent this items label editing
	wxTreeItemId itemId = event.GetItem();
	if ( IsTestItem(itemId) )
	{
		wxMessageBox("You can't edit this item.");

		event.Veto();
	}
#endif
}

void MyTreeCtrl::OnEndLabelEdit(wxTreeEvent& event)
{
#if 0
	wxLogMessage("OnEndLabelEdit");

	// don't allow anything except letters in the labels
	if ( !event.GetLabel().IsWord() )
	{
		wxMessageBox("The label should contain only letters.");

		event.Veto();
	}
#endif
}

void MyTreeCtrl::OnItemCollapsing(wxTreeEvent& event)
{
#if 0
	wxLogMessage("OnItemCollapsing");

	// for testing, prevent the user from collapsing the first child folder
	wxTreeItemId itemId = event.GetItem();
	if ( IsTestItem(itemId) )
	{
		wxMessageBox("You can't collapse this item.");

		event.Veto();
	}
#endif
}

void MyTreeCtrl::OnItemActivated(wxTreeEvent& event)
{
#if 0
	// show some info about this item
	wxTreeItemId itemId = event.GetItem();
	MyTreeItemData *item = (MyTreeItemData *)GetItemData(itemId);

	if ( item != NULL )
	{
		item->ShowInfo(this);
	}
	wxLogMessage("OnItemActivated");
#endif
}

void MyTreeCtrl::OnRMouseDClick(wxMouseEvent& event)
{
#if 0
	wxTreeItemId id = HitTest(event.GetPosition());
	if ( !id )
		wxLogMessage("No item under mouse");
	else
	{
		MyTreeItemData *item = (MyTreeItemData *)GetItemData(id);
		if ( item )
			wxLogMessage("Item '%s' under mouse", item->GetDesc());
	}
#endif
}

/////////////////////////////////////////////////

BEGIN_EVENT_TABLE(MyTreeCtrl, wxTreeCtrl)
EVT_TREE_BEGIN_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginDrag)
EVT_TREE_BEGIN_RDRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginRDrag)
EVT_TREE_END_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnEndDrag)
EVT_TREE_BEGIN_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnBeginLabelEdit)
EVT_TREE_END_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnEndLabelEdit)
EVT_TREE_DELETE_ITEM(LayerTree_Ctrl, MyTreeCtrl::OnDeleteItem)
EVT_TREE_SET_INFO(LayerTree_Ctrl, MyTreeCtrl::OnSetInfo)
EVT_TREE_ITEM_EXPANDED(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanded)
EVT_TREE_ITEM_EXPANDING(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanding)
EVT_TREE_ITEM_COLLAPSED(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsed)
EVT_TREE_ITEM_COLLAPSING(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsing)
EVT_TREE_SEL_CHANGED(LayerTree_Ctrl, MyTreeCtrl::OnSelChanged)
EVT_TREE_SEL_CHANGING(LayerTree_Ctrl, MyTreeCtrl::OnSelChanging)
EVT_TREE_KEY_DOWN(LayerTree_Ctrl, MyTreeCtrl::OnTreeKeyDown)
EVT_TREE_ITEM_ACTIVATED(LayerTree_Ctrl, MyTreeCtrl::OnItemActivated)
EVT_RIGHT_DCLICK(MyTreeCtrl::OnRMouseDClick)
END_EVENT_TABLE()
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 University of Szeged.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "TestController.h"

#include <QApplication>
#include <QObject>
#include <QTimer>

class Launcher : public QObject {
    Q_OBJECT

public:
    Launcher(int argc, char** argv)
        : m_argc(argc)
        , m_argv(argv)
    {
    }

    ~Launcher()
    {
        delete m_controller;
    }

public slots:
    void launch()
    {
        m_controller = new WTR::TestController(m_argc, const_cast<const char**>(m_argv));
        QApplication::exit();
    }

private:
    WTR::TestController* m_controller;
    int m_argc;
    char** m_argv;
};

void messageHandler(QtMsgType type, const char* message)
{
    if (type == QtCriticalMsg) {
        fprintf(stderr, "%s\n", message);
        return;
    }

    // Do nothing
}

int main(int argc, char** argv)
{
    // Suppress debug output from Qt if not started with --verbose
    bool suppressQtDebugOutput = true;
    for (int i = 1; i < argc; ++i) {
        if (!qstrcmp(argv[i], "--verbose")) {
            suppressQtDebugOutput = false;
            break;
        }
    }

    // Has to be done before QApplication is constructed in case
    // QApplication itself produces debug output.
    if (suppressQtDebugOutput) {
        qInstallMsgHandler(messageHandler);
        if (qgetenv("QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT").isEmpty())
            qputenv("QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT", "1");
    }

    QApplication app(argc, argv);
    Launcher launcher(argc, argv);
    QTimer::singleShot(0, &launcher, SLOT(launch()));
    return app.exec();;
}

#include "main.moc"
<commit_msg>[Qt] Prospective build fix for WebKit2 on Linux<commit_after>/*
 * Copyright (C) 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 University of Szeged.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "TestController.h"

#include <stdio.h>

#include <QApplication>
#include <QObject>
#include <QTimer>

class Launcher : public QObject {
    Q_OBJECT

public:
    Launcher(int argc, char** argv)
        : m_argc(argc)
        , m_argv(argv)
    {
    }

    ~Launcher()
    {
        delete m_controller;
    }

public slots:
    void launch()
    {
        m_controller = new WTR::TestController(m_argc, const_cast<const char**>(m_argv));
        QApplication::exit();
    }

private:
    WTR::TestController* m_controller;
    int m_argc;
    char** m_argv;
};

void messageHandler(QtMsgType type, const char* message)
{
    if (type == QtCriticalMsg) {
        fprintf(stderr, "%s\n", message);
        return;
    }

    // Do nothing
}

int main(int argc, char** argv)
{
    // Suppress debug output from Qt if not started with --verbose
    bool suppressQtDebugOutput = true;
    for (int i = 1; i < argc; ++i) {
        if (!qstrcmp(argv[i], "--verbose")) {
            suppressQtDebugOutput = false;
            break;
        }
    }

    // Has to be done before QApplication is constructed in case
    // QApplication itself produces debug output.
    if (suppressQtDebugOutput) {
        qInstallMsgHandler(messageHandler);
        if (qgetenv("QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT").isEmpty())
            qputenv("QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT", "1");
    }

    QApplication app(argc, argv);
    Launcher launcher(argc, argv);
    QTimer::singleShot(0, &launcher, SLOT(launch()));
    return app.exec();;
}

#include "main.moc"
<|endoftext|>


<commit_before>/*
	This file is part of the Util library.
	Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)

#include "WindowEGL.h"
#include "WindowX11Data.h"
#include "../StringUtils.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <EGL/egl.h>
#include <memory>
#include <stdexcept>

namespace Util {
namespace UI {

extern Key keySymToKey(KeySym sym);

struct WindowEGL::WindowEGLData {
		EGLDisplay display;
		EGLContext context;
		EGLSurface surface;

		WindowEGLData() :
			display(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {
		}

		~WindowEGLData() {
			if (display != EGL_NO_DISPLAY) {
				eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
				if (surface != EGL_NO_SURFACE) {
					eglDestroySurface(display, surface);
				}
				if (context != EGL_NO_CONTEXT) {
					eglDestroyContext(display, context);
				}
				eglTerminate(display);
			}
		}
};

static std::string eglErrorToString(const EGLint errorCode) {
	const std::string strErrorCode = StringUtils::toString(errorCode);
	switch(errorCode) {
		case EGL_SUCCESS:
			return "EGL_SUCCESS/" + strErrorCode + ": The last function succeeded without error.";
		case EGL_NOT_INITIALIZED:
			return "EGL_NOT_INITIALIZED/" + strErrorCode + ": EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
		case EGL_BAD_ACCESS:
			return "EGL_BAD_ACCESS/" + strErrorCode + ": EGL cannot access a requested resource (for example a context is bound in another thread).";
		case EGL_BAD_ALLOC:
			return "EGL_BAD_ALLOC/" + strErrorCode + ": EGL failed to allocate resources for the requested operation.";
		case EGL_BAD_ATTRIBUTE:
			return "EGL_BAD_ATTRIBUTE/" + strErrorCode + ": An unrecognized attribute or attribute value was passed in the attribute list.";
		case EGL_BAD_CONTEXT:
			return "EGL_BAD_CONTEXT/" + strErrorCode + ": An EGLContext argument does not name a valid EGL rendering context.";
		case EGL_BAD_CONFIG:
			return "EGL_BAD_CONFIG/" + strErrorCode + ": An EGLConfig argument does not name a valid EGL frame buffer configuration.";
		case EGL_BAD_CURRENT_SURFACE:
			return "EGL_BAD_CURRENT_SURFACE/" + strErrorCode + ": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
		case EGL_BAD_DISPLAY:
			return "EGL_BAD_DISPLAY/" + strErrorCode + ": An EGLDisplay argument does not name a valid EGL display connection.";
		case EGL_BAD_SURFACE:
			return "EGL_BAD_SURFACE/" + strErrorCode + ": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
		case EGL_BAD_MATCH:
			return "EGL_BAD_MATCH/" + strErrorCode + ": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).";
		case EGL_BAD_PARAMETER:
			return "EGL_BAD_PARAMETER/" + strErrorCode + ": One or more argument values are invalid.";
		case EGL_BAD_NATIVE_PIXMAP:
			return "EGL_BAD_NATIVE_PIXMAP/" + strErrorCode + ": A NativePixmapType argument does not refer to a valid native pixmap.";
		case EGL_BAD_NATIVE_WINDOW:
			return "EGL_BAD_NATIVE_WINDOW/" + strErrorCode + ": A NativeWindowType argument does not refer to a valid native window.";
		case EGL_CONTEXT_LOST:
			return "EGL_CONTEXT_LOST/" + strErrorCode + ": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.";
		default:
			return "";
	}
}

WindowEGL::WindowEGL(const Window::Properties & properties) :
		WindowX11(properties), eglData(new WindowEGLData) {

	eglData->display = eglGetDisplay(x11Data->display);
	if (eglData->display == EGL_NO_DISPLAY) {
		throw std::runtime_error("Failed to open display.");
	}

	EGLint versionMajor;
	EGLint versionMinor;
	if (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {
		throw std::runtime_error("Failed to initialize display.");
	}

	// EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION
	if ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {
		throw std::runtime_error("EGL version less than 1.3 detected.");
	}

	if (EGL_TRUE != eglBindAPI(EGL_OPENGL_ES_API)) {
		throw std::runtime_error("Cannot bind API.");
	}

	// Define attributes of desired framebuffer configurations
	EGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,
							EGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
	// Request a single framebuffer configuration
	EGLConfig fbConfig;
	EGLint fbCount;
	if (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {
		throw std::runtime_error("Failed to retrieve a matching framebuffer configuration.");
	}

	if (fbCount == 0) {
		// FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.
		EGLConfig fbConfigs[200];
		eglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);
		for (EGLint i = 0; i < fbCount; ++i) {
			EGLint value;
			// We want to render into a window
			eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);
			if (!(value & EGL_WINDOW_BIT)) {
				continue;
			}
			// We want a configuration with a depth buffer
			eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);
			if (value == 0) {
				continue;
			}
			fbConfig = fbConfigs[i];
		}
	}

	if (fbCount == 0) {
		throw std::runtime_error("No matching framebuffer configurations found.");
	}

	EGLint visualID;
	eglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);

	const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
	eglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);
	if (eglData->context == EGL_NO_CONTEXT) {
		throw std::runtime_error("Failed to create OpenGL ES 2.x context. " +
								 eglErrorToString(eglGetError()));
	}

	// Create X11 window
	XVisualInfo templateInfo;
	templateInfo.visualid = visualID;
	int visualCount;
	XVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);
	if (visualsInfo == nullptr) {
		throw std::runtime_error("Failed to find a matching visual.");
	} else if (visualCount != 1) {
		XFree(visualsInfo);
		throw std::runtime_error("More than one visual found.");
	}

	x11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);
	x11Data->freeColorMap = true;

	XSetWindowAttributes windowAttribs;
	windowAttribs.colormap = x11Data->colorMap;
	windowAttribs.background_pixmap = None;
	windowAttribs.border_pixel = 0;
	windowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;

	x11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen),
								 0, 0, properties.clientAreaWidth, properties.clientAreaHeight,
								 0, visualsInfo[0].depth,
								 InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);

	XFree(visualsInfo);

	if (!x11Data->window) {
		throw std::runtime_error("Failed to create window.");
	} else {
		x11Data->freeWindow = true;
	}

	if (properties.borderless) {
		x11Data->removeWindowBorder();
	}
	if (!properties.resizable) {
		x11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth),
							   static_cast<int>(properties.clientAreaHeight));
	}

	x11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);
	if (x11Data->inputMethod == nullptr) {
		throw std::runtime_error("Failed to create input method.");
	}

	x11Data->inputContext = XCreateIC(x11Data->inputMethod,
								   XNInputStyle, XIMPreeditNone | XIMStatusNone,
								   XNClientWindow, x11Data->window,
								   XNFocusWindow, x11Data->window,
								   nullptr);
	if (x11Data->inputContext == nullptr) {
		throw std::runtime_error("Failed to create input context.");
	}

	XStoreName(x11Data->display, x11Data->window, properties.title.c_str());

	XMapWindow(x11Data->display, x11Data->window);
	if (properties.positioned) {
		XMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);
	}

	eglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);
	if (eglData->surface == EGL_NO_SURFACE) {
		throw std::runtime_error("Failed to create window surface.");
	}

	eglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);
}

WindowEGL::~WindowEGL() = default;

void WindowEGL::swapBuffers() {
	eglSwapBuffers(eglData->display, eglData->surface);
}

}
}

#endif /* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) */
<commit_msg>Select rendering API based on parameter<commit_after>/*
	This file is part of the Util library.
	Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)

#include "WindowEGL.h"
#include "WindowX11Data.h"
#include "../StringUtils.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <EGL/egl.h>
#include <memory>
#include <stdexcept>

namespace Util {
namespace UI {

extern Key keySymToKey(KeySym sym);

struct WindowEGL::WindowEGLData {
		EGLDisplay display;
		EGLContext context;
		EGLSurface surface;

		WindowEGLData() :
			display(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {
		}

		~WindowEGLData() {
			if (display != EGL_NO_DISPLAY) {
				eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
				if (surface != EGL_NO_SURFACE) {
					eglDestroySurface(display, surface);
				}
				if (context != EGL_NO_CONTEXT) {
					eglDestroyContext(display, context);
				}
				eglTerminate(display);
			}
		}
};

static std::string eglErrorToString(const EGLint errorCode) {
	const std::string strErrorCode = StringUtils::toString(errorCode);
	switch(errorCode) {
		case EGL_SUCCESS:
			return "EGL_SUCCESS/" + strErrorCode + ": The last function succeeded without error.";
		case EGL_NOT_INITIALIZED:
			return "EGL_NOT_INITIALIZED/" + strErrorCode + ": EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
		case EGL_BAD_ACCESS:
			return "EGL_BAD_ACCESS/" + strErrorCode + ": EGL cannot access a requested resource (for example a context is bound in another thread).";
		case EGL_BAD_ALLOC:
			return "EGL_BAD_ALLOC/" + strErrorCode + ": EGL failed to allocate resources for the requested operation.";
		case EGL_BAD_ATTRIBUTE:
			return "EGL_BAD_ATTRIBUTE/" + strErrorCode + ": An unrecognized attribute or attribute value was passed in the attribute list.";
		case EGL_BAD_CONTEXT:
			return "EGL_BAD_CONTEXT/" + strErrorCode + ": An EGLContext argument does not name a valid EGL rendering context.";
		case EGL_BAD_CONFIG:
			return "EGL_BAD_CONFIG/" + strErrorCode + ": An EGLConfig argument does not name a valid EGL frame buffer configuration.";
		case EGL_BAD_CURRENT_SURFACE:
			return "EGL_BAD_CURRENT_SURFACE/" + strErrorCode + ": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
		case EGL_BAD_DISPLAY:
			return "EGL_BAD_DISPLAY/" + strErrorCode + ": An EGLDisplay argument does not name a valid EGL display connection.";
		case EGL_BAD_SURFACE:
			return "EGL_BAD_SURFACE/" + strErrorCode + ": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
		case EGL_BAD_MATCH:
			return "EGL_BAD_MATCH/" + strErrorCode + ": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).";
		case EGL_BAD_PARAMETER:
			return "EGL_BAD_PARAMETER/" + strErrorCode + ": One or more argument values are invalid.";
		case EGL_BAD_NATIVE_PIXMAP:
			return "EGL_BAD_NATIVE_PIXMAP/" + strErrorCode + ": A NativePixmapType argument does not refer to a valid native pixmap.";
		case EGL_BAD_NATIVE_WINDOW:
			return "EGL_BAD_NATIVE_WINDOW/" + strErrorCode + ": A NativeWindowType argument does not refer to a valid native window.";
		case EGL_CONTEXT_LOST:
			return "EGL_CONTEXT_LOST/" + strErrorCode + ": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.";
		default:
			return "";
	}
}

WindowEGL::WindowEGL(const Window::Properties & properties) :
		WindowX11(properties), eglData(new WindowEGLData) {

	eglData->display = eglGetDisplay(x11Data->display);
	if (eglData->display == EGL_NO_DISPLAY) {
		throw std::runtime_error("Failed to open display.");
	}

	EGLint versionMajor;
	EGLint versionMinor;
	if (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {
		throw std::runtime_error("Failed to initialize display.");
	}

	// EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION
	if ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {
		throw std::runtime_error("EGL version less than 1.3 detected.");
	}

	EGLenum api;
	EGLint glesVersion = 0;
	switch(properties.renderingAPI) {
		case Properties::RenderingAPI::GL_ES_1:
			api = EGL_OPENGL_ES_API;
			glesVersion = 1;
			break;
		case Properties::RenderingAPI::GL_ES_2:
			api = EGL_OPENGL_ES_API;
			glesVersion = 2;
			break;
		case Properties::RenderingAPI::GL_ES_3:
			api = EGL_OPENGL_ES_API;
			glesVersion = 3;
			break;
		case Properties::RenderingAPI::GL:
			api = EGL_OPENGL_API;
			break;
		default:
			throw std::runtime_error("Unsupported rendering API.");
	}
	if (EGL_TRUE != eglBindAPI(api)) {
		throw std::runtime_error("Cannot bind API.");
	}

	// Define attributes of desired framebuffer configurations
	EGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,
							EGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
	// Request a single framebuffer configuration
	EGLConfig fbConfig;
	EGLint fbCount;
	if (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {
		throw std::runtime_error("Failed to retrieve a matching framebuffer configuration.");
	}

	if (fbCount == 0) {
		// FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.
		EGLConfig fbConfigs[200];
		eglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);
		for (EGLint i = 0; i < fbCount; ++i) {
			EGLint value;
			// We want to render into a window
			eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);
			if (!(value & EGL_WINDOW_BIT)) {
				continue;
			}
			// We want a configuration with a depth buffer
			eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);
			if (value == 0) {
				continue;
			}
			fbConfig = fbConfigs[i];
		}
	}

	if (fbCount == 0) {
		throw std::runtime_error("No matching framebuffer configurations found.");
	}

	EGLint visualID;
	eglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);

	EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, glesVersion, EGL_NONE };
	if (0 == glesVersion) {
		contextAttribs[0] = EGL_NONE;
		contextAttribs[1] = EGL_NONE;
	}
	eglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);
	if (eglData->context == EGL_NO_CONTEXT) {
		throw std::runtime_error("Failed to create context: " +
								 eglErrorToString(eglGetError()));
	}

	// Create X11 window
	XVisualInfo templateInfo;
	templateInfo.visualid = visualID;
	int visualCount;
	XVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);
	if (visualsInfo == nullptr) {
		throw std::runtime_error("Failed to find a matching visual.");
	} else if (visualCount != 1) {
		XFree(visualsInfo);
		throw std::runtime_error("More than one visual found.");
	}

	x11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);
	x11Data->freeColorMap = true;

	XSetWindowAttributes windowAttribs;
	windowAttribs.colormap = x11Data->colorMap;
	windowAttribs.background_pixmap = None;
	windowAttribs.border_pixel = 0;
	windowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;

	x11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen),
								 0, 0, properties.clientAreaWidth, properties.clientAreaHeight,
								 0, visualsInfo[0].depth,
								 InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);

	XFree(visualsInfo);

	if (!x11Data->window) {
		throw std::runtime_error("Failed to create window.");
	} else {
		x11Data->freeWindow = true;
	}

	if (properties.borderless) {
		x11Data->removeWindowBorder();
	}
	if (!properties.resizable) {
		x11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth),
							   static_cast<int>(properties.clientAreaHeight));
	}

	x11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);
	if (x11Data->inputMethod == nullptr) {
		throw std::runtime_error("Failed to create input method.");
	}

	x11Data->inputContext = XCreateIC(x11Data->inputMethod,
								   XNInputStyle, XIMPreeditNone | XIMStatusNone,
								   XNClientWindow, x11Data->window,
								   XNFocusWindow, x11Data->window,
								   nullptr);
	if (x11Data->inputContext == nullptr) {
		throw std::runtime_error("Failed to create input context.");
	}

	XStoreName(x11Data->display, x11Data->window, properties.title.c_str());

	XMapWindow(x11Data->display, x11Data->window);
	if (properties.positioned) {
		XMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);
	}

	eglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);
	if (eglData->surface == EGL_NO_SURFACE) {
		throw std::runtime_error("Failed to create window surface.");
	}

	eglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);
}

WindowEGL::~WindowEGL() = default;

void WindowEGL::swapBuffers() {
	eglSwapBuffers(eglData->display, eglData->surface);
}

}
}

#endif /* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) */
<|endoftext|>


<commit_before>#include "VBase.h"

#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <cstdio>
#include <cstring>

#if defined(_WIN32)
#include <windows.h>
#endif

#if defined(__linux__)
#include <unistd.h>
#include <term.h>
#endif

#ifdef _DEBUG
int VBase::DebugObjectCount = 0;
#endif

void VBase::VLog(const char* format, ...)
{
	char    buf[4096], *p = buf;
	va_list args;
	int     n;

	va_start(args, format);
	n = vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL

	int len = strlen(buf);
	char* con = new char[len + 2];

	strcpy(con, buf);
	con[len] = '\n';
	con[len + 1] = '\0';

	printf(con, args);
	va_end(args);

	p += (n < 0) ? sizeof buf - 3 : n;

	while (p > buf  &&  isspace(p[-1]))
		*--p = '\0';

	*p++ = '\r';
	*p++ = '\n';
	*p = '\0';

	wchar_t output[4096];
	std::mbstowcs(output, buf, strlen(buf) + 1);

#ifdef _MSC_VER
	OutputDebugString(output);
#endif

	delete[] con;
}

void VBase::VClearLog()
{
#if defined(_WIN32)
	HANDLE                     hStdOut;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	DWORD                      count;
	DWORD                      cellCount;
	COORD                      homeCoords = { 0, 0 };

	hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if (hStdOut == INVALID_HANDLE_VALUE) return;

	/* Get the number of cells in the current buffer */
	if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;
	cellCount = csbi.dwSize.X *csbi.dwSize.Y;

	/* Fill the entire buffer with spaces */
	if (!FillConsoleOutputCharacter(
		hStdOut,
		(TCHAR) ' ',
		cellCount,
		homeCoords,
		&count
	)) return;

	/* Fill the entire buffer with the current colors and attributes */
	if (!FillConsoleOutputAttribute(
		hStdOut,
		csbi.wAttributes,
		cellCount,
		homeCoords,
		&count
	)) return;

	/* Move the cursor home */
	SetConsoleCursorPosition(hStdOut, homeCoords);
#endif

#ifdef __linux__
	if (!cur_term)
	{
		int result;
		setupterm(NULL, STDOUT_FILENO, &result);
		if (result <= 0) return;
	}

	putp(tigetstr("clear"));
#endif
}<commit_msg>Add source for clearing logs.<commit_after>#include "VBase.h"

#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <cstdio>
#include <cstring>

#if defined(_WIN32)
#include <windows.h>
#endif

#if defined(__linux__)
#include <unistd.h>
#include <term.h>
#endif

#ifdef _DEBUG
int VBase::DebugObjectCount = 0;
#endif

void VBase::VLog(const char* format, ...)
{
	char    buf[4096], *p = buf;
	va_list args;
	int     n;

	va_start(args, format);
	n = vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL

	int len = strlen(buf);
	char* con = new char[len + 2];

	strcpy(con, buf);
	con[len] = '\n';
	con[len + 1] = '\0';

	printf(con, args);
	va_end(args);

	p += (n < 0) ? sizeof buf - 3 : n;

	while (p > buf  &&  isspace(p[-1]))
		*--p = '\0';

	*p++ = '\r';
	*p++ = '\n';
	*p = '\0';

	wchar_t output[4096];
	std::mbstowcs(output, buf, strlen(buf) + 1);

#ifdef _MSC_VER
	OutputDebugString(output);
#endif

	delete[] con;
}

//Source http://www.cplusplus.com/articles/4z18T05o/
void VBase::VClearLog()
{
#if defined(_WIN32)
	HANDLE                     hStdOut;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	DWORD                      count;
	DWORD                      cellCount;
	COORD                      homeCoords = { 0, 0 };

	hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if (hStdOut == INVALID_HANDLE_VALUE) return;

	/* Get the number of cells in the current buffer */
	if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;
	cellCount = csbi.dwSize.X *csbi.dwSize.Y;

	/* Fill the entire buffer with spaces */
	if (!FillConsoleOutputCharacter(
		hStdOut,
		(TCHAR) ' ',
		cellCount,
		homeCoords,
		&count
	)) return;

	/* Fill the entire buffer with the current colors and attributes */
	if (!FillConsoleOutputAttribute(
		hStdOut,
		csbi.wAttributes,
		cellCount,
		homeCoords,
		&count
	)) return;

	/* Move the cursor home */
	SetConsoleCursorPosition(hStdOut, homeCoords);
#endif

#ifdef __linux__
	if (!cur_term)
	{
		int result;
		setupterm(NULL, STDOUT_FILENO, &result);
		if (result <= 0) return;
	}

	putp(tigetstr("clear"));
#endif
}<|endoftext|>


<commit_before>/* we will try to recreate the mem layout from the execution traces */
#include <fstream>
#include <iostream>
#include <vector>

#include "utility/fileparser.h"
#include "utility/defines.h"
#include "meminfo.h"
#include "utilities.h"
#include "memory/meminstrace.h"

using namespace std;

void create_mem_layout(std::ifstream &in, vector<mem_info_t *> &mem_info, uint32_t version){

	uint32_t count = 0;

	in.clear();
	in.seekg(0, in.beg);

	DEBUG_PRINT(("create_mem_layout(mem_info)...\n"), 2);

	while (!in.eof()){
		cinstr_t * instr = get_next_from_ascii_file(in, version);
		mem_input_t * input = new mem_input_t;

		if (instr != NULL){

			for (int i = 0; i < instr->num_srcs; i++){
				if (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){
					input->mem_addr = instr->srcs[i].value;
					input->stride = instr->srcs[i].width;
					input->write = false;
					input->type = instr->srcs[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}
			for (int i = 0; i < instr->num_dsts; i++){
				if (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){
					input->mem_addr = instr->dsts[i].value;
					input->stride = instr->dsts[i].width;
					input->write = true;
					input->type = instr->dsts[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}

		}

		print_progress(&count, 10000);

		delete instr;
		delete input;
	}

	postprocess_mem_regions(mem_info);

	DEBUG_PRINT(("create_mem_layout(mem_info) - done\n"), 2);

}

/* only app_pc based pc_mem_region recording is done here - if needed implement the module based recording */
void create_mem_layout(std::ifstream &in, vector<pc_mem_region_t *> &mem_info, uint32_t version){

	uint32_t count = 0;

	in.clear();
	in.seekg(0, in.beg);

	DEBUG_PRINT(("create_mem_layout(pc_mem_regions)...\n"), 2);

	while (!in.eof()){
		cinstr_t * instr = get_next_from_ascii_file(in, version);
		mem_input_t * input = new mem_input_t;

		if (instr != NULL){

			for (int i = 0; i < instr->num_srcs; i++){
				if (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){
					input->pc = instr->pc;
					input->mem_addr = instr->srcs[i].value;
					input->stride = instr->srcs[i].width;
					input->write = false;
					input->type = instr->srcs[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}
			for (int i = 0; i < instr->num_dsts; i++){
				if (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){
					input->pc = instr->pc;
					input->mem_addr = instr->dsts[i].value;
					input->stride = instr->dsts[i].width;
					input->write = true;
					input->type = instr->dsts[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}

		}

		print_progress(&count, 10000);

		delete instr;
		delete input;
	}

	postprocess_mem_regions(mem_info);

	DEBUG_PRINT(("create_mem_layout(pc_mem_regions) - done\n"), 2);

}

void create_mem_layout(vector<cinstr_t * > &instrs, vector<mem_info_t *> &mem_info){

}

void create_mem_layout(vector<cinstr_t * > &instrs, vector<pc_mem_region_t *> &pc_mems){

}

<commit_msg>stack locations excluded<commit_after>/* we will try to recreate the mem layout from the execution traces */
#include <fstream>
#include <iostream>
#include <vector>

#include "utility/fileparser.h"
#include "utility/defines.h"
#include "meminfo.h"
#include "utilities.h"
#include "memory/meminstrace.h"

using namespace std;

void create_mem_layout(std::ifstream &in, vector<mem_info_t *> &mem_info, uint32_t version){

	uint32_t count = 0;

	in.clear();
	in.seekg(0, in.beg);

	DEBUG_PRINT(("create_mem_layout(mem_info)...\n"), 2);

	while (!in.eof()){
		cinstr_t * instr = get_next_from_ascii_file(in, version);
		mem_input_t * input = new mem_input_t;

		if (instr != NULL){

			for (int i = 0; i < instr->num_srcs; i++){
				if (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){

					bool skip = true;
					if (instr->srcs[i].type == MEM_STACK_TYPE){
						operand_t opnd = instr->srcs[i];
						for (int addr = 0; addr < 2; addr++){
							uint32_t reg = opnd.addr[addr].value;
							if (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;

						}
					}
					else{
						skip = false;
					}

					if (skip) continue;

					input->mem_addr = instr->srcs[i].value;
					input->stride = instr->srcs[i].width;
					input->write = false;
					input->type = instr->srcs[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}
			for (int i = 0; i < instr->num_dsts; i++){
				if (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){

					bool skip = true;
					if (instr->dsts[i].type == MEM_STACK_TYPE){
						operand_t opnd = instr->dsts[i];
						for (int addr = 0; addr < 2; addr++){
							uint32_t reg = opnd.addr[addr].value;
							if (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;
						}
					}
					else{
						skip = false;
					}

					if (skip) continue;

					input->mem_addr = instr->dsts[i].value;
					input->stride = instr->dsts[i].width;
					input->write = true;
					input->type = instr->dsts[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}

		}

		print_progress(&count, 10000);

		delete instr;
		delete input;
	}

	postprocess_mem_regions(mem_info);

	DEBUG_PRINT(("create_mem_layout(mem_info) - done\n"), 2);

}

/* only app_pc based pc_mem_region recording is done here - if needed implement the module based recording */
void create_mem_layout(std::ifstream &in, vector<pc_mem_region_t *> &mem_info, uint32_t version){

	uint32_t count = 0;

	in.clear();
	in.seekg(0, in.beg);

	DEBUG_PRINT(("create_mem_layout(pc_mem_regions)...\n"), 2);

	while (!in.eof()){
		cinstr_t * instr = get_next_from_ascii_file(in, version);
		mem_input_t * input = new mem_input_t;

		if (instr != NULL){

			for (int i = 0; i < instr->num_srcs; i++){
				if (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){

					bool skip = true;
					if (instr->srcs[i].type == MEM_STACK_TYPE){
						operand_t opnd = instr->srcs[i];
						for (int addr = 0; addr < 2; addr++){
							uint32_t reg = opnd.addr[addr].value;
							if (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;

						}
					}
					else{
						skip = false;
					}

					if (skip) continue;

					input->pc = instr->pc;
					input->mem_addr = instr->srcs[i].value;
					input->stride = instr->srcs[i].width;
					input->write = false;
					input->type = instr->srcs[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}
			for (int i = 0; i < instr->num_dsts; i++){
				if (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){

					bool skip = true;
					if (instr->dsts[i].type == MEM_STACK_TYPE){
						operand_t opnd = instr->dsts[i];
						for (int addr = 0; addr < 2; addr++){
							uint32_t reg = opnd.addr[addr].value;
							if (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;
						}
					}
					else{
						skip = false;
					}

					if (skip) continue;

					input->pc = instr->pc;
					input->mem_addr = instr->dsts[i].value;
					input->stride = instr->dsts[i].width;
					input->write = true;
					input->type = instr->dsts[i].type;
					if (input->stride != 0){
						update_mem_regions(mem_info, input);
					}
				}
			}

		}

		print_progress(&count, 10000);

		delete instr;
		delete input;
	}

	postprocess_mem_regions(mem_info);

	DEBUG_PRINT(("create_mem_layout(pc_mem_regions) - done\n"), 2);

}

void create_mem_layout(vector<cinstr_t * > &instrs, vector<mem_info_t *> &mem_info){

}

void create_mem_layout(vector<cinstr_t * > &instrs, vector<pc_mem_region_t *> &pc_mems){

}

<|endoftext|>


<commit_before>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>

extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
	std::string address;
	std::string amount;
};
void VerifySnapShot()
{
}
void GenerateSnapShot()
{
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
    UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
    for (unsigned int idx = 0; idx < tests.size(); idx++) {
        UniValue test = tests[idx];
        std::string strTest = test.write();
        if (test.size() < 2) // Allow for extra stuff (useful for comments)
        {
            BOOST_ERROR("Bad test: " << strTest);
            continue;
        }
		PaymentAmount payment;
        payment.address  = test[0].get_str();
        payment.amount = ValueFromAmount(test[1].get_int64()).write());
		paymentAmounts.push_back(payment);
    }
}
bool IsMainNetAlreadyCreated()
{
	int height;
	UniValue r;
	BOOST_CHECK_NO_THROW(r = CallRPC(node, "getinfo"));
	height = find_value(r.get_obj(), "blocks").get_int();
	return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
	std::vector<PaymentAmount> paymentAmounts;
	GetUTXOs(paymentAmounts);
	if(IsMainNetAlreadyCreated())
	{
		VerifySnapShot();
	}
	else
	{
		GenerateSnapShot();
		VerifySnapShot();
	}
}
BOOST_AUTO_TEST_SUITE_END ()<commit_msg>typos<commit_after>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>

extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
	std::string address;
	std::string amount;
};
void VerifySnapShot()
{
}
void GenerateSnapShot()
{
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
    UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
    for (unsigned int idx = 0; idx < tests.size(); idx++) {
        UniValue test = tests[idx];
        std::string strTest = test.write();
        if (test.size() < 2) // Allow for extra stuff (useful for comments)
        {
            BOOST_ERROR("Bad test: " << strTest);
            continue;
        }
		PaymentAmount payment;
        payment.address  = test[0].get_str();
        payment.amount = ValueFromAmount(test[1].get_int64()).write();
		paymentAmounts.push_back(payment);
    }
}
bool IsMainNetAlreadyCreated()
{
	int height;
	UniValue r;
	BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo"));
	height = find_value(r.get_obj(), "blocks").get_int();
	return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
	std::vector<PaymentAmount> paymentAmounts;
	GetUTXOs(paymentAmounts);
	if(IsMainNetAlreadyCreated())
	{
		VerifySnapShot();
	}
	else
	{
		GenerateSnapShot();
		VerifySnapShot();
	}
}
BOOST_AUTO_TEST_SUITE_END ()<|endoftext|>