<commit_before>#define AODSelector_cxx
// The class definition in AODSelector.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.

// The following methods are defined in this file:
//    Begin():        called every time a loop on the tree starts,
//                    a convenient place to create your histograms.
//    SlaveBegin():   called after Begin(), when on PROOF called only on the
//                    slave servers.
//    Process():      called for each event, in this function you decide what
//                    to read and fill your histograms.
//    SlaveTerminate: called at the end of the loop on the tree, when on PROOF
//                    called only on the slave servers.
//    Terminate():    called at the end of the loop on the tree,
//                    a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// Root > T->Process("AODSelector.cxx")
// Root > T->Process("AODSelector.cxx","some options")
// Root > T->Process("AODSelector.cxx+")
//

#include "AODSelector.h"
#include <TH2.h>
#include <TStyle.h>
#include <TMath.h>
#include <TAxis.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TH1F.h>
#include <TF1.h>
#include <TCanvas.h>
#include <TRandom3.h>

static void BinLogAxis(const TH1 *h)
{
  //
  // Method for the correct logarithmic binning of histograms
  //
  TAxis *axis = const_cast<TAxis*>(h->GetXaxis());
  const Int_t bins = axis->GetNbins();

  const Double_t from = axis->GetXmin();
  const Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins + 1];

  newBins[0] = from;
  Double_t factor = pow(to / from, 1. / bins);

  for (Int_t i = 1; i <= bins; i++) {
    newBins[i] = factor * newBins[i - 1];
  }
  axis->Set(bins, newBins);
  delete [] newBins;
}

Double_t BetheBlochAleph(Double_t bg,
                         Double_t kp1,
                         Double_t kp2,
                         Double_t kp3,
                         Double_t kp4,
                         Double_t kp5) {
  Double_t beta = bg / TMath::Sqrt(1. + bg * bg);
  Double_t aa = TMath::Power(beta,kp4);
  Double_t bb = TMath::Power(1. / bg,kp5);
  bb = TMath::Log(kp3 + bb);
  return (kp2 - aa - bb) * kp1 / aa;
}

Double_t DeuteronTPC(Double_t *x, Double_t *) {
  // Deuteron expected signal in TPC, taken from AntiHe4 task
  return BetheBlochAleph(x[0] / MD ,4.69637,7.51827,0.0183746,2.60,2.7);
}

unsigned int Log2Int(const unsigned int v) {
  // Taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
  static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 0xFF00FF00, 0xFFFF0000};
  unsigned int r = (v & b[0]) != 0;
  r |= ((v & b[4]) != 0) << 4;
  r |= ((v & b[3]) != 0) << 3;
  r |= ((v & b[2]) != 0) << 2;
  r |= ((v & b[1]) != 0) << 1;
  return r;
}

void AODSelector::Begin(TTree * /*tree*/)
{
  // The Begin() function is called at the start of the query.
  // When running with PROOF Begin() is only called on the client.
  // The tree argument is deprecated (on PROOF 0 is passed).

  TString option = GetOption();

}

Int_t AODSelector::GetCentBin(float cent) {
  if (cent < fCentralityBins[0]) return -1;

  for (int i = 0; i < kNCent; ++i)
    if (cent <= fCentralityBins[i + 1])
      return i;

  return -1;
}

Int_t AODSelector::GetPtBin(float pt) {
  for (int i = 0; i < kNBins; ++i) {
    if (pt < fBins[i+1] && pt >= fBins[i]) {
      return i;
    }
  }
  return -1;
}

Bool_t AODSelector::Flatten(float cent) {
  float prob[13] = {
    0.855566,0.846964,0.829618,0.829259,0.830984,
    0.85094,0.844346,0.851818,0.874758,1,
    0.374767,0.650491,0.946963
  };
  return gRandom->Rndm() > prob[int(cent)];
}

void AODSelector::SlaveBegin(TTree * /*tree*/)
{
  // The SlaveBegin() function is called after the Begin() function.
  // When running with PROOF SlaveBegin() is called on each slave server.
  // The tree argument is deprecated (on PROOF 0 is passed).

  TString option = GetOption();

  const Int_t nPtBins = kNBins;
  const Int_t nCentBins = kNCent;
  const Double_t *pTbins = fBins;
  const Double_t *centBins = fCentralityBins;

  const Int_t nDCAbins = 80;
  const Float_t range = 0.5;
  Double_t dcaBins[nDCAbins+1];
  for (int i = 0; i <= nDCAbins; ++i)
    dcaBins[i] = i * range * 2 / nDCAbins - range;

  fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.);
  fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins);
  fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.);
  GetOutputList()->Add(fCentrality);
  GetOutputList()->Add(fCentralityClasses);
  GetOutputList()->Add(fFlattenedCentrality);

  const int tofNbins = 75;
  const float tofLowBoundary = -2.4,tofHighBoundary = 3.6;
  Double_t tofBins[tofNbins + 1];
  const float deltaTOF = (tofHighBoundary - tofLowBoundary) / tofNbins;
  for (int i = 0; i <= tofNbins; ++i)
    tofBins[i] = i * deltaTOF + tofLowBoundary;
  const int dcaZnBins = 400;
  const float dcaZlimit = 10.;
  Double_t dcazBins[dcaZnBins + 1];
  const float deltaDCAz = 2.f * dcaZlimit / dcaZnBins;
  for (int i = 0; i <= dcaZnBins; ++i)
    dcazBins[i] = i * deltaDCAz - dcaZlimit;
  const int nTpcBins = 500;
  Double_t tpcBins[nTpcBins + 1];
  for (int i = 0; i <= nTpcBins; ++i) {
    tpcBins[i] = i * 5;
  }

  fTPCSignal = new TH2F("fTPCSignal","p_{T} (GeV/c);dE/dx (a.u.)",nPtBins,pTbins,500,0,2500);

  fATOFsignal = new TH3F("fATOFsignal",
                         ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}",
                         nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins);
  fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)",
                         nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins);
  fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)",
                     nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins);
  fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)",
                    nCentBins,centBins,nPtBins,pTbins,dcaZnBins,dcazBins);
  fMTOFsignal = new TH3F("fMTOFsignal",
                         ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}",
                         nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins);
  fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)",
                         nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins);
  GetOutputList()->Add(fATOFsignal);
  GetOutputList()->Add(fATPCcounts);
  GetOutputList()->Add(fMDCAxy);
  GetOutputList()->Add(fMDCAz);
  GetOutputList()->Add(fMTOFsignal);
  GetOutputList()->Add(fMTPCcounts);
  GetOutputList()->Add(fTPCSignal);

  fDeutBB = new TF1("fDeutBB",DeuteronTPC,0.3,6,0);
}

Bool_t AODSelector::Process(Long64_t entry)
{
  // The Process() function is called for each entry in the tree (or possibly
  // keyed object in the case of PROOF) to be processed. The entry argument
  // specifies which entry in the currently loaded tree is to be processed.
  // It can be passed to either AODSelector::GetEntry() or TBranch::GetEntry()
  // to read either all or the required parts of the data. When processing
  // keyed objects with PROOF, the object is already loaded and is available
  // via the fObject pointer.
  //
  // This function should contain the "body" of the analysis. It can contain
  // simple or elaborate selection criteria, run algorithms on the data
  // of the event and typically fill histograms.
  //
  // The processing can be stopped by calling Abort().
  //
  // Use fStatus to set the return value of TTree::Process().
  //
  // The return value is currently not used.

  GetEntry(entry);

  if (centrality < 0) {
    fSkipEvent = kFALSE;
    if (-centrality < 13.f)
      fSkipEvent = Flatten(-centrality);

    if (!fSkipEvent) {
      fFlattenedCentrality->Fill(-centrality);
      fCentralityClasses->Fill(-centrality);
    }
    fCentrality->Fill(-centrality);
  }
  if (fSkipEvent) return kTRUE;

  const int cent = GetCentBin(TMath::Abs(centrality));
  if (cent < 0)
    return kTRUE;

  if (TMath::Abs(eta) > 0.8)
    return kTRUE;

  if (TMath::Abs(chi2NDF) > kChi2Cut)
    return kTRUE;

  Double_t pz = TMath::Sqrt(p * p - pT * pT);
  Double_t e = TMath::Sqrt(p * p + M2D);
  Double_t y = 0.5 * TMath::Log((e + pz) / (e - pz));
  if (TMath::Abs(y) > 0.5) {
    return kTRUE;
  }

  if (TPCnSignal < kTPCsig)
    return kTRUE;

  if (ITSnClust - ITSnSignal <= 0) return kTRUE;
  if (TMath::Abs(DCAz) > kDCAz) return kTRUE;

  if (TMath::Abs(DCAxy) > 0.5f) return kTRUE;

  Float_t c_pT = pT;
  if (c_pT > 0) {
    c_pT -= fCorrectionD(c_pT);
  } else {
    c_pT += fCorrectionAD(-c_pT);
  }

  fTPCSignal->Fill(pTPC, TPCsignal);

  if (TPCsignal > 0.76f * fDeutBB->Eval(pTPC) && TPCsignal < 1.24f * fDeutBB->Eval(pTPC)) {
    if(c_pT > 0.) {
      fMTPCcounts->Fill(centrality,c_pT,TPCsignal);
      fMDCAxy->Fill(centrality,c_pT,DCAxy);
      fMDCAz->Fill(centrality,c_pT,DCAz);
    } else {
      fATPCcounts->Fill(centrality,-c_pT,TPCsignal);
    }
    if (TOFtime > 0.f && length > 350.f) {
      Float_t beta = length / (2.99792457999999984e-02f * TOFtime);
      if (beta < (1.f - EPSILON)) {
        Float_t gamma = 1. / TMath::Sqrt(1.f - (beta * beta));
        const float dm = p * p / (beta * beta * gamma * gamma) - M2D;
        if(c_pT > 0.) {
          fMTOFsignal->Fill(centrality,c_pT,dm);
        } else {
          fATOFsignal->Fill(centrality,-c_pT,dm);
        }
      }
    }
  }

  return kTRUE;
}

void AODSelector::SlaveTerminate()
{
  // The SlaveTerminate() function is called after all entries or objects
  // have been processed. When running with PROOF SlaveTerminate() is called
  // on each slave server.

}

void AODSelector::Terminate()
{
  // The Terminate() function is the last function to be called during
  // a query. It always runs on the client, it can be used to present
  // the results graphically or save the results to file.

  TFile f("nuclei.root","update");
  f.mkdir(kName.Data());
  f.cd(kName.Data());
  ((TH1F*)GetOutputList()->FindObject("fCentrality"))->Write();
  ((TH1F*)GetOutputList()->FindObject("fFlattenCentrality"))->Write();
  ((TH1F*)GetOutputList()->FindObject("fCentralityClasses"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fATOFsignal"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fATPCcounts"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMDCAxy"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMDCAz"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMTOFsignal"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMTPCcounts"))->Write();
  f.Close();

  fTPCSignal = (TH2F*)GetOutputList()->FindObject("fTPCSignal");
  fTPCSignal->Draw("colz");
  fDeutBB = new TF1("deutTPC",DeuteronTPC,0.4,6,0);
  fDeutBB->Draw("same");
}
<commit_msg>Added ITS selection<commit_after>#define AODSelector_cxx
// The class definition in AODSelector.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.

// The following methods are defined in this file:
//    Begin():        called every time a loop on the tree starts,
//                    a convenient place to create your histograms.
//    SlaveBegin():   called after Begin(), when on PROOF called only on the
//                    slave servers.
//    Process():      called for each event, in this function you decide what
//                    to read and fill your histograms.
//    SlaveTerminate: called at the end of the loop on the tree, when on PROOF
//                    called only on the slave servers.
//    Terminate():    called at the end of the loop on the tree,
//                    a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// Root > T->Process("AODSelector.cxx")
// Root > T->Process("AODSelector.cxx","some options")
// Root > T->Process("AODSelector.cxx+")
//

#include "AODSelector.h"
#include <TH2.h>
#include <TStyle.h>
#include <TMath.h>
#include <TAxis.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TH1F.h>
#include <TF1.h>
#include <TCanvas.h>
#include <TRandom3.h>

static void BinLogAxis(const TH1 *h)
{
  //
  // Method for the correct logarithmic binning of histograms
  //
  TAxis *axis = const_cast<TAxis*>(h->GetXaxis());
  const Int_t bins = axis->GetNbins();

  const Double_t from = axis->GetXmin();
  const Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins + 1];

  newBins[0] = from;
  Double_t factor = pow(to / from, 1. / bins);

  for (Int_t i = 1; i <= bins; i++) {
    newBins[i] = factor * newBins[i - 1];
  }
  axis->Set(bins, newBins);
  delete [] newBins;
}

Double_t BetheBlochAleph(Double_t bg,
                         Double_t kp1,
                         Double_t kp2,
                         Double_t kp3,
                         Double_t kp4,
                         Double_t kp5) {
  Double_t beta = bg / TMath::Sqrt(1. + bg * bg);
  Double_t aa = TMath::Power(beta,kp4);
  Double_t bb = TMath::Power(1. / bg,kp5);
  bb = TMath::Log(kp3 + bb);
  return (kp2 - aa - bb) * kp1 / aa;
}

Double_t DeuteronTPC(Double_t *x, Double_t *) {
  // Deuteron expected signal in TPC, taken from AntiHe4 task
  return BetheBlochAleph(x[0] / MD ,4.69637,7.51827,0.0183746,2.60,2.7);
}

unsigned int Log2Int(const unsigned int v) {
  // Taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
  static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 0xFF00FF00, 0xFFFF0000};
  unsigned int r = (v & b[0]) != 0;
  r |= ((v & b[4]) != 0) << 4;
  r |= ((v & b[3]) != 0) << 3;
  r |= ((v & b[2]) != 0) << 2;
  r |= ((v & b[1]) != 0) << 1;
  return r;
}

void AODSelector::Begin(TTree * /*tree*/)
{
  // The Begin() function is called at the start of the query.
  // When running with PROOF Begin() is only called on the client.
  // The tree argument is deprecated (on PROOF 0 is passed).

  TString option = GetOption();

}

Int_t AODSelector::GetCentBin(float cent) {
  if (cent < fCentralityBins[0]) return -1;

  for (int i = 0; i < kNCent; ++i)
    if (cent <= fCentralityBins[i + 1])
      return i;

  return -1;
}

Int_t AODSelector::GetPtBin(float pt) {
  for (int i = 0; i < kNBins; ++i) {
    if (pt < fBins[i+1] && pt >= fBins[i]) {
      return i;
    }
  }
  return -1;
}

Bool_t AODSelector::Flatten(float cent) {
  float prob[13] = {
    0.855566,0.846964,0.829618,0.829259,0.830984,
    0.85094,0.844346,0.851818,0.874758,1,
    0.374767,0.650491,0.946963
  };
  return gRandom->Rndm() > prob[int(cent)];
}

void AODSelector::SlaveBegin(TTree * /*tree*/)
{
  // The SlaveBegin() function is called after the Begin() function.
  // When running with PROOF SlaveBegin() is called on each slave server.
  // The tree argument is deprecated (on PROOF 0 is passed).

  TString option = GetOption();

  const Int_t nPtBins = kNBins;
  const Int_t nCentBins = kNCent;
  const Double_t *pTbins = fBins;
  const Double_t *centBins = fCentralityBins;

  const Int_t nDCAbins = 80;
  const Float_t range = 0.5;
  Double_t dcaBins[nDCAbins+1];
  for (int i = 0; i <= nDCAbins; ++i)
    dcaBins[i] = i * range * 2 / nDCAbins - range;

  fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.);
  fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins);
  fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.);
  GetOutputList()->Add(fCentrality);
  GetOutputList()->Add(fCentralityClasses);
  GetOutputList()->Add(fFlattenedCentrality);

  const int tofNbins = 75;
  const float tofLowBoundary = -2.4,tofHighBoundary = 3.6;
  Double_t tofBins[tofNbins + 1];
  const float deltaTOF = (tofHighBoundary - tofLowBoundary) / tofNbins;
  for (int i = 0; i <= tofNbins; ++i)
    tofBins[i] = i * deltaTOF + tofLowBoundary;
  const int dcaZnBins = 400;
  const float dcaZlimit = 10.;
  Double_t dcazBins[dcaZnBins + 1];
  const float deltaDCAz = 2.f * dcaZlimit / dcaZnBins;
  for (int i = 0; i <= dcaZnBins; ++i)
    dcazBins[i] = i * deltaDCAz - dcaZlimit;
  const int nTpcBins = 500;
  Double_t tpcBins[nTpcBins + 1];
  for (int i = 0; i <= nTpcBins; ++i) {
    tpcBins[i] = i * 5;
  }

  fTPCSignal = new TH2F("fTPCSignal","p_{T} (GeV/c);dE/dx (a.u.)",nPtBins,pTbins,500,0,2500);

  fATOFsignal = new TH3F("fATOFsignal",
                         ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}",
                         nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins);
  fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)",
                         nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins);
  fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)",
                     nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins);
  fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)",
                    nCentBins,centBins,nPtBins,pTbins,dcaZnBins,dcazBins);
  fMTOFsignal = new TH3F("fMTOFsignal",
                         ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}",
                         nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins);
  fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)",
                         nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins);
  GetOutputList()->Add(fATOFsignal);
  GetOutputList()->Add(fATPCcounts);
  GetOutputList()->Add(fMDCAxy);
  GetOutputList()->Add(fMDCAz);
  GetOutputList()->Add(fMTOFsignal);
  GetOutputList()->Add(fMTPCcounts);
  GetOutputList()->Add(fTPCSignal);

  fDeutBB = new TF1("fDeutBB",DeuteronTPC,0.3,6,0);
}

Bool_t AODSelector::Process(Long64_t entry)
{
  // The Process() function is called for each entry in the tree (or possibly
  // keyed object in the case of PROOF) to be processed. The entry argument
  // specifies which entry in the currently loaded tree is to be processed.
  // It can be passed to either AODSelector::GetEntry() or TBranch::GetEntry()
  // to read either all or the required parts of the data. When processing
  // keyed objects with PROOF, the object is already loaded and is available
  // via the fObject pointer.
  //
  // This function should contain the "body" of the analysis. It can contain
  // simple or elaborate selection criteria, run algorithms on the data
  // of the event and typically fill histograms.
  //
  // The processing can be stopped by calling Abort().
  //
  // Use fStatus to set the return value of TTree::Process().
  //
  // The return value is currently not used.

  GetEntry(entry);

  if (centrality < 0) {
    fSkipEvent = kFALSE;
    if (-centrality < 13.f)
      fSkipEvent = Flatten(-centrality);

    if (!fSkipEvent) {
      fFlattenedCentrality->Fill(-centrality);
      fCentralityClasses->Fill(-centrality);
    }
    fCentrality->Fill(-centrality);
  }
  if (fSkipEvent) return kTRUE;

  const int cent = GetCentBin(TMath::Abs(centrality));
  if (cent < 0)
    return kTRUE;

  if (TMath::Abs(eta) > 0.8)
    return kTRUE;

  if (TMath::Abs(chi2NDF) > kChi2Cut)
    return kTRUE;

  Double_t pz = TMath::Sqrt(p * p - pT * pT);
  Double_t e = TMath::Sqrt(p * p + M2D);
  Double_t y = 0.5 * TMath::Log((e + pz) / (e - pz));
  if (TMath::Abs(y) > 0.5) {
    return kTRUE;
  }

  if (TPCnSignal < kTPCsig)
    return kTRUE;

  if (ITSnClust - ITSnSignal <= 0) return kTRUE;
  if (TMath::Abs(DCAz) > kDCAz) return kTRUE;

  if (TMath::Abs(DCAxy) > 0.5f) return kTRUE;

  Float_t c_pT = pT;
  if (c_pT > 0) {
    c_pT -= fCorrectionD(c_pT);
  } else {
    c_pT += fCorrectionAD(-c_pT);
  }

  fTPCSignal->Fill(pTPC, TPCsignal);

  if (TPCsignal > 0.76f * fDeutBB->Eval(pTPC) && TPCsignal < 1.24f * fDeutBB->Eval(pTPC)) {
    if (pTPC < 1.4 && TMath::Abs(ITSsigmad) > 3.) {
      return kTRUE;
    }
    if(c_pT > 0.) {
      fMTPCcounts->Fill(centrality,c_pT,TPCsignal);
      fMDCAxy->Fill(centrality,c_pT,DCAxy);
      fMDCAz->Fill(centrality,c_pT,DCAz);
    } else {
      fATPCcounts->Fill(centrality,-c_pT,TPCsignal);
    }
    if (TOFtime > 0.f && length > 350.f) {
      Float_t beta = length / (2.99792457999999984e-02f * TOFtime);
      if (beta < (1.f - EPSILON)) {
        Float_t gamma = 1. / TMath::Sqrt(1.f - (beta * beta));
        const float dm = p * p / (beta * beta * gamma * gamma) - M2D;
        if(c_pT > 0.) {
          fMTOFsignal->Fill(centrality,c_pT,dm);
        } else {
          fATOFsignal->Fill(centrality,-c_pT,dm);
        }
      }
    }
  }

  return kTRUE;
}

void AODSelector::SlaveTerminate()
{
  // The SlaveTerminate() function is called after all entries or objects
  // have been processed. When running with PROOF SlaveTerminate() is called
  // on each slave server.

}

void AODSelector::Terminate()
{
  // The Terminate() function is the last function to be called during
  // a query. It always runs on the client, it can be used to present
  // the results graphically or save the results to file.

  TFile f("nuclei.root","update");
  f.mkdir(kName.Data());
  f.cd(kName.Data());
  ((TH1F*)GetOutputList()->FindObject("fCentrality"))->Write();
  ((TH1F*)GetOutputList()->FindObject("fFlattenCentrality"))->Write();
  ((TH1F*)GetOutputList()->FindObject("fCentralityClasses"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fATOFsignal"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fATPCcounts"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMDCAxy"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMDCAz"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMTOFsignal"))->Write();
  ((TH3F*)GetOutputList()->FindObject("fMTPCcounts"))->Write();
  f.Close();

  fTPCSignal = (TH2F*)GetOutputList()->FindObject("fTPCSignal");
  fTPCSignal->Draw("colz");
  fDeutBB = new TF1("deutTPC",DeuteronTPC,0.4,6,0);
  fDeutBB->Draw("same");
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// string_functions.cpp
//
// Identification: src/function/string_functions.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cctype>
#include <string>
#include <algorithm>

#include "function/string_functions.h"
#include "type/value_factory.h"

#define NextByte(p, plen) ((p)++, (plen)--)

namespace peloton {
namespace function {

uint32_t StringFunctions::Ascii(const char *str, uint32_t length) {
  PL_ASSERT(str != nullptr);
  return length <= 1 ? 0 : static_cast<uint32_t>(str[0]);
}

// ASCII code of the first character of the argument.
type::Value StringFunctions::_Ascii(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }

  uint32_t ret = Ascii(args[0].GetAs<const char *>(), args[0].GetLength());
  return type::ValueFactory::GetIntegerValue(ret);
}

bool StringFunctions::Like(const char *t, uint32_t tlen, const char *p,
                           uint32_t plen) {
  PL_ASSERT(t != nullptr);
  PL_ASSERT(p != nullptr);
  if (plen == 1 && *p == '%') return true;

  while (tlen > 0 && plen > 0) {
    if (*p == '\\') {
      NextByte(p, plen);
      if (plen <= 0) return false;
      if (tolower(*p) != tolower(*t)) return false;
    } else if (*p == '%') {
      char firstpat;
      NextByte(p, plen);

      while (plen > 0) {
        if (*p == '%')
          NextByte(p, plen);
        else if (*p == '_') {
          if (tlen <= 0) return false;
          NextByte(t, tlen);
          NextByte(p, plen);
        } else
          break;
      }

      if (plen <= 0) return true;

      if (*p == '\\') {
        if (plen < 2) return false;
        firstpat = tolower(p[1]);
      } else
        firstpat = tolower(*p);

      while (tlen > 0) {
        if (tolower(*t) == firstpat) {
          int matched = Like(t, tlen, p, plen);

          if (matched != false) return matched;
        }

        NextByte(t, tlen);
      }
      return false;
    } else if (*p == '_') {
      NextByte(t, tlen);
      NextByte(p, plen);
      continue;
    } else if (tolower(*p) != tolower(*t)) {
      return false;
    }
    NextByte(t, tlen);
    NextByte(p, plen);
  }

  if (tlen > 0) return false;

  while (plen > 0 && *p == '%') NextByte(p, plen);
  if (plen <= 0) return true;

  return false;
}

type::Value StringFunctions::_Like(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }

  bool ret = Like(args[0].GetAs<const char *>(), args[0].GetLength(),
                  args[1].GetAs<const char *>(), args[1].GetLength());
  return type::ValueFactory::GetBooleanValue(ret);
}

// Get Character from integer
type::Value StringFunctions::Chr(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  int32_t val = args[0].GetAs<int32_t>();
  std::string str(1, static_cast<char>(val));
  return type::ValueFactory::GetVarcharValue(str);
}

// substring
type::Value StringFunctions::Substr(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 3);
  if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  int32_t from = args[1].GetAs<int32_t>() - 1;
  int32_t len = args[2].GetAs<int32_t>();
  return type::ValueFactory::GetVarcharValue(str.substr(from, len));
}

// Number of characters in string
type::Value StringFunctions::CharLength(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }
  std::string str = args[0].ToString();
  int32_t len = str.length();
  return (type::ValueFactory::GetIntegerValue(len));
}

// Concatenate two strings
type::Value StringFunctions::Concat(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString() + args[1].ToString();
  return (type::ValueFactory::GetVarcharValue(str));
}

// Number of bytes in string
type::Value StringFunctions::OctetLength(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  std::string str = args[0].ToString();
  int32_t len = str.length();
  return (type::ValueFactory::GetIntegerValue(len));
}

// Repeat string the specified number of times
type::Value StringFunctions::Repeat(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  int32_t num = args[1].GetAs<int32_t>();
  std::string ret = "";
  while (num--) {
    ret = ret + str;
  }
  return (type::ValueFactory::GetVarcharValue(ret));
}

// Replace all occurrences in string of substring from with substring to
type::Value StringFunctions::Replace(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 3);
  if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  std::string from = args[1].ToString();
  std::string to = args[2].ToString();
  size_t pos = 0;
  while ((pos = str.find(from, pos)) != std::string::npos) {
    str.replace(pos, from.length(), to);
    pos += to.length();
  }
  return (type::ValueFactory::GetVarcharValue(str));
}

// Remove the longest string containing only characters from characters
// from the start of string
type::Value StringFunctions::LTrim(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  std::string from = args[1].ToString();
  size_t pos = 0;
  bool erase = 0;
  while (from.find(str[pos]) != std::string::npos) {
    erase = 1;
    pos++;
  }
  if (erase) str.erase(0, pos);
  return (type::ValueFactory::GetVarcharValue(str));
}

// Remove the longest string containing only characters from characters
// from the end of string
type::Value StringFunctions::RTrim(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args.at(0).ToString();
  std::string from = args.at(1).ToString();
  if (str.length() == 0) return (type::ValueFactory::GetVarcharValue(""));
  size_t pos = str.length() - 1;
  bool erase = 0;
  while (from.find(str[pos]) != std::string::npos) {
    erase = 1;
    pos--;
  }
  if (erase) str.erase(pos + 1, str.length() - pos - 1);
  return (type::ValueFactory::GetVarcharValue(str));
}

// Remove the longest string consisting only of characters in characters
// from the start and end of string
StringFunctions::StrWithLen StringFunctions::BTrim(
    const char *str, uint32_t str_len, const char *from,
    UNUSED_ATTRIBUTE uint32_t from_len) {
  PL_ASSERT(str != nullptr && from != nullptr);
  if (str_len == 0) {
    return StringFunctions::StrWithLen(nullptr, 0);
  }

  int tail = str_len - 1, head = 0;
  while (tail >= 0 && strchr(from, str[tail]) != NULL) tail--;
  tail++;

  while (head < (int)str_len && strchr(from, str[head]) != NULL) head++;

  return StringFunctions::StrWithLen(str + head, std::max(tail - head + 1, 0));
}

type::Value StringFunctions::_BTrim(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args.at(0).ToString();
  std::string from = args.at(1).ToString();
  if (str.length() == 0) return (type::ValueFactory::GetVarcharValue(""));

  size_t pos = str.length() - 1;
  bool erase = 0;
  while (from.find(str[pos]) != std::string::npos) {
    erase = 1;
    pos--;
  }
  if (erase) str.erase(pos + 1, str.length() - pos - 1);

  pos = 0;
  erase = 0;
  while (from.find(str[pos]) != std::string::npos) {
    erase = 1;
    pos++;
  }
  if (erase) str.erase(0, pos);
  return (type::ValueFactory::GetVarcharValue(str));
}

uint32_t StringFunctions::Length(UNUSED_ATTRIBUTE const char *str,
                                 uint32_t length) {
  PL_ASSERT(str != nullptr);
  return length;
}

// The length of the string
type::Value StringFunctions::_Length(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }

  uint32_t ret = Length(args[0].GetAs<const char *>(), args[0].GetLength());
  return type::ValueFactory::GetIntegerValue(ret);
}

}  // namespace function
}  // namespace peloton
<commit_msg>fix length and use BTrim within _BTrim<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// string_functions.cpp
//
// Identification: src/function/string_functions.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cctype>
#include <string>
#include <algorithm>

#include "function/string_functions.h"
#include "type/value_factory.h"

#define NextByte(p, plen) ((p)++, (plen)--)

namespace peloton {
namespace function {

uint32_t StringFunctions::Ascii(const char *str, uint32_t length) {
  PL_ASSERT(str != nullptr);
  return length <= 1 ? 0 : static_cast<uint32_t>(str[0]);
}

// ASCII code of the first character of the argument.
type::Value StringFunctions::_Ascii(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }

  uint32_t ret = Ascii(args[0].GetAs<const char *>(), args[0].GetLength());
  return type::ValueFactory::GetIntegerValue(ret);
}

bool StringFunctions::Like(const char *t, uint32_t tlen, const char *p,
                           uint32_t plen) {
  PL_ASSERT(t != nullptr);
  PL_ASSERT(p != nullptr);
  if (plen == 1 && *p == '%') return true;

  while (tlen > 0 && plen > 0) {
    if (*p == '\\') {
      NextByte(p, plen);
      if (plen <= 0) return false;
      if (tolower(*p) != tolower(*t)) return false;
    } else if (*p == '%') {
      char firstpat;
      NextByte(p, plen);

      while (plen > 0) {
        if (*p == '%')
          NextByte(p, plen);
        else if (*p == '_') {
          if (tlen <= 0) return false;
          NextByte(t, tlen);
          NextByte(p, plen);
        } else
          break;
      }

      if (plen <= 0) return true;

      if (*p == '\\') {
        if (plen < 2) return false;
        firstpat = tolower(p[1]);
      } else
        firstpat = tolower(*p);

      while (tlen > 0) {
        if (tolower(*t) == firstpat) {
          int matched = Like(t, tlen, p, plen);

          if (matched != false) return matched;
        }

        NextByte(t, tlen);
      }
      return false;
    } else if (*p == '_') {
      NextByte(t, tlen);
      NextByte(p, plen);
      continue;
    } else if (tolower(*p) != tolower(*t)) {
      return false;
    }
    NextByte(t, tlen);
    NextByte(p, plen);
  }

  if (tlen > 0) return false;

  while (plen > 0 && *p == '%') NextByte(p, plen);
  if (plen <= 0) return true;

  return false;
}

type::Value StringFunctions::_Like(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }

  bool ret = Like(args[0].GetAs<const char *>(), args[0].GetLength(),
                  args[1].GetAs<const char *>(), args[1].GetLength());
  return type::ValueFactory::GetBooleanValue(ret);
}

// Get Character from integer
type::Value StringFunctions::Chr(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  int32_t val = args[0].GetAs<int32_t>();
  std::string str(1, static_cast<char>(val));
  return type::ValueFactory::GetVarcharValue(str);
}

// substring
type::Value StringFunctions::Substr(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 3);
  if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  int32_t from = args[1].GetAs<int32_t>() - 1;
  int32_t len = args[2].GetAs<int32_t>();
  return type::ValueFactory::GetVarcharValue(str.substr(from, len));
}

// Number of characters in string
type::Value StringFunctions::CharLength(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }
  std::string str = args[0].ToString();
  int32_t len = str.length();
  return (type::ValueFactory::GetIntegerValue(len));
}

// Concatenate two strings
type::Value StringFunctions::Concat(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString() + args[1].ToString();
  return (type::ValueFactory::GetVarcharValue(str));
}

// Number of bytes in string
type::Value StringFunctions::OctetLength(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  std::string str = args[0].ToString();
  int32_t len = str.length();
  return (type::ValueFactory::GetIntegerValue(len));
}

// Repeat string the specified number of times
type::Value StringFunctions::Repeat(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  int32_t num = args[1].GetAs<int32_t>();
  std::string ret = "";
  while (num--) {
    ret = ret + str;
  }
  return (type::ValueFactory::GetVarcharValue(ret));
}

// Replace all occurrences in string of substring from with substring to
type::Value StringFunctions::Replace(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 3);
  if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  std::string from = args[1].ToString();
  std::string to = args[2].ToString();
  size_t pos = 0;
  while ((pos = str.find(from, pos)) != std::string::npos) {
    str.replace(pos, from.length(), to);
    pos += to.length();
  }
  return (type::ValueFactory::GetVarcharValue(str));
}

// Remove the longest string containing only characters from characters
// from the start of string
type::Value StringFunctions::LTrim(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args[0].ToString();
  std::string from = args[1].ToString();
  size_t pos = 0;
  bool erase = 0;
  while (from.find(str[pos]) != std::string::npos) {
    erase = 1;
    pos++;
  }
  if (erase) str.erase(0, pos);
  return (type::ValueFactory::GetVarcharValue(str));
}

// Remove the longest string containing only characters from characters
// from the end of string
type::Value StringFunctions::RTrim(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }
  std::string str = args.at(0).ToString();
  std::string from = args.at(1).ToString();
  if (str.length() == 0) return (type::ValueFactory::GetVarcharValue(""));
  size_t pos = str.length() - 1;
  bool erase = 0;
  while (from.find(str[pos]) != std::string::npos) {
    erase = 1;
    pos--;
  }
  if (erase) str.erase(pos + 1, str.length() - pos - 1);
  return (type::ValueFactory::GetVarcharValue(str));
}

// Remove the longest string consisting only of characters in characters
// from the start and end of string
StringFunctions::StrWithLen StringFunctions::BTrim(
    const char *str, uint32_t str_len, const char *from,
    UNUSED_ATTRIBUTE uint32_t from_len) {
  PL_ASSERT(str != nullptr && from != nullptr);

  str_len--;  // skip the tailing 0

  if (str_len == 0) {
    return StringFunctions::StrWithLen(str, 1);
  }

  int tail = str_len - 1, head = 0;
  while (tail >= 0 && strchr(from, str[tail]) != NULL) tail--;

  while (head < (int)str_len && strchr(from, str[head]) != NULL) head++;

  return StringFunctions::StrWithLen(str + head, std::max(tail - head + 1, 0) + 1);
}

type::Value StringFunctions::_BTrim(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 2);
  if (args[0].IsNull() || args[1].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR);
  }

  StrWithLen ret = BTrim(args.at(0).GetData(), strlen(args.at(0).GetData() + 1),
                         args.at(1).GetData(), strlen(args.at(1).GetData()) + 1);

  std::string str(ret.str, ret.length - 1);
  return type::ValueFactory::GetVarcharValue(str);
}

uint32_t StringFunctions::Length(UNUSED_ATTRIBUTE const char *str,
                                 uint32_t length) {
  PL_ASSERT(str != nullptr);
  return length;
}

// The length of the string
type::Value StringFunctions::_Length(const std::vector<type::Value> &args) {
  PL_ASSERT(args.size() == 1);
  if (args[0].IsNull()) {
    return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER);
  }

  uint32_t ret = Length(args[0].GetAs<const char *>(), args[0].GetLength());
  return type::ValueFactory::GetIntegerValue(ret);
}

}  // namespace function
}  // namespace peloton
<|endoftext|>


<commit_before>/*
 * simple_tree.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: programmer
 */

#include "../system/discursive_system.h"
#include "./initial_agents.h"

#include "repository_access.h"
#include <Magick++.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../model/surrogate_tree_node.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"

using namespace Magick;
int debugLevel;

// display our command usage
void display_usage( void )
{
	std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n";
	usage_string += "where option can be any of the following";
	usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n";
	usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n";
	usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n";
	usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
	usage_string += "\n-i option - interactive mode (asks you questions) \n";
	usage_string += "\n-d option - debug level, defaults to 1\n";
	usage_string += "\n-o or -O option - output file name, defaults to tree.jpg\n";
	usage_string += "\n-m option - output the creation of the current tree one step at a time via many .jpgs in sequence\n";
	usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .jpgs in sequence\n";
	usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-l option - spatial displacement scaling levels, expects W1:H1:W2:H2 defaults to 5000:5000:4500:4200\n";
	usage_string += "\n----------------where W1 is the start width\n";
	usage_string += "\n----------------where H1 is the start height\n";
	usage_string += "\n----------------where W2 is the end width\n";
	usage_string += "\n----------------where H2 is the end height\n";
	usage_string += "\n-z option - image size , expects WxH, defaults to 500x500 \n";

	DiscursivePrint("%s",usage_string.c_str());
    DiscursiveError("Copyright Discursive Labs LLC, 2010");
}

int main(int argc, char **argv)
{
	// set the debug level
	SetDiscursiveDebugLevel(0);

	// agentName equates to the passed command line parameter argument string
	char *agentName = NULL;

	// type of agent to use, ie command line options or interactive
	int agentType = 0;

	// scaling factors to use for spatial displacement
	int startWidth = 5000;
	int startHeight = 5000;
	int endWidth = 4500;
	int endHeight = 4250;

	// image size options for jpg output
	int imageWidth = 500;
	int imageHeight = 500;

	// our filename for output file
	std::string fileName = "tree.jpg";

	// should we make many jpgs?
	int manyJpgs = 0;

	// options for many jpgs
	int jpgStep = 1;
	int jpgStart = 3;
	int jpgStop = 10000;

	// should we output a jpg per revision?
	int revJpgs = 0;

	// options for jpg per revison
	int revStep = 1;
	int revStart = 2;
	int revStop = 10000;

	// our option string
	static const char *optString = "g:G:S:C:O:o:m:R:l:z:ridh?";

	// loop over our command options in the normal unix way

	int opt;
	opt = getopt( argc, argv, optString );
	while( opt != -1 ) {
		switch( opt ) {
			case 'g':
				agentName = optarg;
				agentType = 1;
				break;
			case 'G':
				agentName = optarg;
				agentType = 2;
				break;
			case 'S':
				agentName = optarg;
				agentType = 3;
				break;
			case 'C':
				agentName = optarg;
				agentType = 4;
				break;
			case 'l':
				sscanf(optarg,"%d:%d:%d:%d",&startWidth,&startHeight,&endWidth,&endHeight);
				break;
			case 'z':
				sscanf(optarg,"%dx%d",&imageWidth,&imageHeight);
				break;
			case 'm':
				manyJpgs = 1;
				sscanf(optarg,"%d:%d:%d",&jpgStart,&jpgStop,&jpgStep);
				if(jpgStart < 3)
				{
					jpgStart = 3;
				}
				break;
			case 'R':
				revJpgs = 1;
				sscanf(optarg,"%d:%d:%d",&revStart,&revStop,&revStep);
				if(revStart < 3)
				{
					revStart = 3;
				}
				break;
			case 'r':
				revJpgs = 1;
				revStart = 3;
				revStop = 100000;
				revStep = 1;
				break;
			case 'o':
			case 'O':
				fileName = optarg;
				break;
			case 'd':
				// set the debug level
				SetDiscursiveDebugLevel(1);
				break;
			case 'i':
				// set the interactivity level
				agentType = 5;
				break;
			case 'h':   /* fall-through is intentional */
			case '?':
				display_usage();
				break;
			default:
				DiscursiveError("bad cli, bad!");
				break;
		}
		// get the next Command Line option
		opt = getopt( argc, argv, optString );
	}

	// Tree Generation pipeline
	// create an abstract method for repository access
	RepositoryAccess* git;

	// let an interactive or command line agent create the repository access type
	switch(agentType)
	{
		case 5:
			git = interactive_agent();
			break;
		case 1:
		case 2:
		case 3:
		case 4:
			DiscursiveDebugPrint("%s\n",agentName);
			git = noninteractive_agent(agentType, agentName);
			break;
		case 0:
			display_usage();
			break;
        default:
            /* You won't actually get here. */
        	DiscursiveError("an impossibility occured in error processing");
            break;
	}

	// set our scaling factor from our received or default options
	double widthRescaling = endWidth/(double)startWidth;
	double heightRescaling = endHeight/(double)startHeight;

    // set our repository single or manyjpg options
	git->snapshotJpgs = manyJpgs;
	git->jpgIndex = 1000;
	git->scaleHeight = heightRescaling;
	git->scaleWidth = widthRescaling;
	git->fileName = (char*)fileName.c_str();
	git->globalInserts = 0;
	git->localInserts = 0;
	git->insertTarget = 0;
	git->revJpgs = revJpgs;
	git->globalRevs = 0;
	git->localRevs = 0;
	git->revTarget = 0;
	git->currentTreeSize = 0;
	git->logGenerated = 0;

	// retrieve our source tree
	DiscursivePrint("Retrieving From Server, Please Wait...\n");
	git->source = git->retrieve();

	// output tree info
	DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str());
	DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts);

	// create loop step variables generically for any jpg looping type
	int loopStart = 0;
	int loopStop = 1;
	int loopStep = 1;
	int executeLoopType = 1;

	// check for our custom loop types
	if(manyJpgs)
	{
		loopStart = jpgStart;
		loopStop = jpgStop;
		loopStep = jpgStep;
		executeLoopType = 2;
	}
	else if(revJpgs)
	{
		loopStart = revStart;
		loopStop = revStop;
		loopStep = revStep;
		executeLoopType = 3;
	}

	// check for too many global inserts or revisions
	if((executeLoopType == 2) && (loopStop >= git->globalInserts))
	{
		loopStop = git->globalInserts-1;
	}
	DiscursiveDebugPrint("Total revs in repo = %d and loopstop = %d\n",git->globalRevs,loopStop);
	if((executeLoopType == 3) && (loopStop >= git->globalRevs))
	{
		loopStop = git->globalRevs-1;
	}

	// loop over a bunch of increasingly large trees for debug or revision tree generation
	// use our user-set parameters to define our step
	for(int i = loopStart; i<loopStop;i+= loopStep)
	{

		// reset our insert variables
		if(executeLoopType == 2)
		{
			git->localInserts = 0;
			git->insertTarget = i;
		}
		else if(executeLoopType == 3)
		{
			git->localRevs = 0;
			git->revTarget = i;
		}

		// retrieve our source tree
		git->source = git->retrieve();

		DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,loopStop,loopStep);
		// Decorate surrogate tree nodes with locations
		SpatialDisplacement* disp = new SpatialDisplacement(imageWidth,imageHeight,widthRescaling,heightRescaling);
		disp->decorate(git->source);

		// Digitize decorated surrogate tree into line segment tree
		DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,loopStop,loopStep);
	    SpaceColonizer *digitizer = new SpaceColonizer(1);
		DrawableData* lines = digitizer->digitize(git->source);

		// Transform

		// Draw tree
		DiscursivePrint("Drawing Tree %d out of %d step value %d",i,loopStop,loopStep);
		Image canvas(Geometry(imageWidth,imageHeight),"white");
		ScanlineArtist artist;
		artist.draw(canvas, lines);

		// actually generate a tree
		DiscursivePrint("Writing Tree %d out of %d step value %d\n",i,loopStop,loopStep);
		git->WriteJPGFromCanvas(&canvas);

	}
	return 0;
}
<commit_msg>updated simple tree to be jpg again<commit_after>/*
 * simple_tree.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: programmer
 */

#include "../system/discursive_system.h"
#include "./initial_agents.h"

#include "repository_access.h"
#include <Magick++.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../model/surrogate_tree_node.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"

using namespace Magick;
int debugLevel;

// display our command usage
void display_usage( void )
{
	std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n";
	usage_string += "where option can be any of the following";
	usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n";
	usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n";
	usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n";
	usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
	usage_string += "\n-i option - interactive mode (asks you questions) \n";
	usage_string += "\n-d option - debug level, defaults to 1\n";
	usage_string += "\n-o or -O option - output file name, defaults to tree.jpg\n";
	usage_string += "\n-m option - output the creation of the current tree one step at a time via many .images in sequence\n";
	usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .images in sequence\n";
	usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-l option - spatial displacement scaling levels, expects W1:H1:W2:H2 defaults to 5000:5000:4500:4200\n";
	usage_string += "\n----------------where W1 is the start width\n";
	usage_string += "\n----------------where H1 is the start height\n";
	usage_string += "\n----------------where W2 is the end width\n";
	usage_string += "\n----------------where H2 is the end height\n";
	usage_string += "\n-z option - image size , expects WxH, defaults to 500x500 \n";

	DiscursivePrint("%s",usage_string.c_str());
    DiscursiveError("Copyright Discursive Labs LLC, 2010");
}

int main(int argc, char **argv)
{
	// set the debug level
	SetDiscursiveDebugLevel(0);

	// agentName equates to the passed command line parameter argument string
	char *agentName = NULL;

	// type of agent to use, ie command line options or interactive
	int agentType = 0;

	// scaling factors to use for spatial displacement
	int startWidth = 5000;
	int startHeight = 5000;
	int endWidth = 4500;
	int endHeight = 4250;

	// image size options for jpg output
	int imageWidth = 500;
	int imageHeight = 500;

	// our filename for output file
	std::string fileName = "tree.jpg";

	// should we make many jpgs?
	int manyJpgs = 0;

	// options for many jpgs
	int jpgStep = 1;
	int jpgStart = 3;
	int jpgStop = 10000;

	// should we output a jpg per revision?
	int revJpgs = 0;

	// options for jpg per revison
	int revStep = 1;
	int revStart = 2;
	int revStop = 10000;

	// our option string
	static const char *optString = "g:G:S:C:O:o:m:R:l:z:ridh?";

	// loop over our command options in the normal unix way

	int opt;
	opt = getopt( argc, argv, optString );
	while( opt != -1 ) {
		switch( opt ) {
			case 'g':
				agentName = optarg;
				agentType = 1;
				break;
			case 'G':
				agentName = optarg;
				agentType = 2;
				break;
			case 'S':
				agentName = optarg;
				agentType = 3;
				break;
			case 'C':
				agentName = optarg;
				agentType = 4;
				break;
			case 'l':
				sscanf(optarg,"%d:%d:%d:%d",&startWidth,&startHeight,&endWidth,&endHeight);
				break;
			case 'z':
				sscanf(optarg,"%dx%d",&imageWidth,&imageHeight);
				break;
			case 'm':
				manyJpgs = 1;
				sscanf(optarg,"%d:%d:%d",&jpgStart,&jpgStop,&jpgStep);
				if(jpgStart < 3)
				{
					jpgStart = 3;
				}
				break;
			case 'R':
				revJpgs = 1;
				sscanf(optarg,"%d:%d:%d",&revStart,&revStop,&revStep);
				if(revStart < 3)
				{
					revStart = 3;
				}
				break;
			case 'r':
				revJpgs = 1;
				revStart = 3;
				revStop = 100000;
				revStep = 1;
				break;
			case 'o':
			case 'O':
				fileName = optarg;
				break;
			case 'd':
				// set the debug level
				SetDiscursiveDebugLevel(1);
				break;
			case 'i':
				// set the interactivity level
				agentType = 5;
				break;
			case 'h':   /* fall-through is intentional */
			case '?':
				display_usage();
				break;
			default:
				DiscursiveError("bad cli, bad!");
				break;
		}
		// get the next Command Line option
		opt = getopt( argc, argv, optString );
	}

	// Tree Generation pipeline
	// create an abstract method for repository access
	RepositoryAccess* git;

	// let an interactive or command line agent create the repository access type
	switch(agentType)
	{
		case 5:
			git = interactive_agent();
			break;
		case 1:
		case 2:
		case 3:
		case 4:
			DiscursiveDebugPrint("%s\n",agentName);
			git = noninteractive_agent(agentType, agentName);
			break;
		case 0:
			display_usage();
			break;
        default:
            /* You won't actually get here. */
        	DiscursiveError("an impossibility occured in error processing");
            break;
	}

	// set our scaling factor from our received or default options
	double widthRescaling = endWidth/(double)startWidth;
	double heightRescaling = endHeight/(double)startHeight;

    // set our repository single or manyjpg options
	git->snapshotJpgs = manyJpgs;
	git->jpgIndex = 1000;
	git->scaleHeight = heightRescaling;
	git->scaleWidth = widthRescaling;
	git->fileName = (char*)fileName.c_str();
	git->globalInserts = 0;
	git->localInserts = 0;
	git->insertTarget = 0;
	git->revJpgs = revJpgs;
	git->globalRevs = 0;
	git->localRevs = 0;
	git->revTarget = 0;
	git->currentTreeSize = 0;
	git->logGenerated = 0;

	// retrieve our source tree
	DiscursivePrint("Retrieving From Server, Please Wait...\n");
	git->source = git->retrieve();

	// output tree info
	DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str());
	DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts);

	// create loop step variables generically for any jpg looping type
	int loopStart = 0;
	int loopStop = 1;
	int loopStep = 1;
	int executeLoopType = 1;

	// check for our custom loop types
	if(manyJpgs)
	{
		loopStart = jpgStart;
		loopStop = jpgStop;
		loopStep = jpgStep;
		executeLoopType = 2;
	}
	else if(revJpgs)
	{
		loopStart = revStart;
		loopStop = revStop;
		loopStep = revStep;
		executeLoopType = 3;
	}

	// check for too many global inserts or revisions
	if((executeLoopType == 2) && (loopStop >= git->globalInserts))
	{
		loopStop = git->globalInserts-1;
	}
	DiscursiveDebugPrint("Total revs in repo = %d and loopstop = %d\n",git->globalRevs,loopStop);
	if((executeLoopType == 3) && (loopStop >= git->globalRevs))
	{
		loopStop = git->globalRevs-1;
	}

	// loop over a bunch of increasingly large trees for debug or revision tree generation
	// use our user-set parameters to define our step
	for(int i = loopStart; i<loopStop;i+= loopStep)
	{

		// reset our insert variables
		if(executeLoopType == 2)
		{
			git->localInserts = 0;
			git->insertTarget = i;
		}
		else if(executeLoopType == 3)
		{
			git->localRevs = 0;
			git->revTarget = i;
		}

		// retrieve our source tree
		git->source = git->retrieve();

		DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,loopStop,loopStep);
		// Decorate surrogate tree nodes with locations
		SpatialDisplacement* disp = new SpatialDisplacement(imageWidth,imageHeight,widthRescaling,heightRescaling);
		disp->decorate(git->source);

		// Digitize decorated surrogate tree into line segment tree
		DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,loopStop,loopStep);
	    SpaceColonizer *digitizer = new SpaceColonizer(1);
		DrawableData* lines = digitizer->digitize(git->source);

		// Transform

		// Draw tree
		DiscursivePrint("Drawing Tree %d out of %d step value %d",i,loopStop,loopStep);
		Image canvas(Geometry(imageWidth,imageHeight),"white");
		ScanlineArtist artist;
		artist.draw(canvas, lines);

		// actually generate a tree
		DiscursivePrint("Writing Tree %d out of %d step value %d\n",i,loopStop,loopStep);
		git->WriteJPGFromCanvas(&canvas);

	}
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Theme ID used for testing.
const char* const theme_crx = "iamefpfkojoapidjnbafmgkgncegbkad";

}  // namespace

class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest {
 public:
  // Checks that a theme info bar is currently visible and issues an undo to
  // revert to the previous theme.
  void VerifyThemeInfoBarAndUndoInstall() {
    TabContents* tab_contents = browser()->GetSelectedTabContents();
    ASSERT_TRUE(tab_contents);
    ASSERT_EQ(1, tab_contents->infobar_delegate_count());
    ThemeInstalledInfoBarDelegate* delegate = tab_contents->
        GetInfoBarDelegateAt(0)->AsThemePreviewInfobarDelegate();
    ASSERT_TRUE(delegate);
    delegate->Cancel();
    ASSERT_EQ(0, tab_contents->infobar_delegate_count());
  }
};

// Flaky, http://crbug.com/43441.
IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       FLAKY_TestThemeInstallUndoResetsToDefault) {
  // Install theme once and undo to verify we go back to default theme.
  FilePath theme_path = test_data_dir_.AppendASCII("theme.crx");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1));
  Extension* theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());

  // Set the same theme twice and undo to verify we go back to default theme.
  // We set the |expected_change| to zero in these 'InstallExtensionWithUI'
  // calls since the theme has already been installed above and this is an
  // overinstall to set the active theme.
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());
}
<commit_msg>Disable ExtensionInstallUIBrowserTest.TestThemeInstallUndoResetsToDefault because of crashiness.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Theme ID used for testing.
const char* const theme_crx = "iamefpfkojoapidjnbafmgkgncegbkad";

}  // namespace

class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest {
 public:
  // Checks that a theme info bar is currently visible and issues an undo to
  // revert to the previous theme.
  void VerifyThemeInfoBarAndUndoInstall() {
    TabContents* tab_contents = browser()->GetSelectedTabContents();
    ASSERT_TRUE(tab_contents);
    ASSERT_EQ(1, tab_contents->infobar_delegate_count());
    ThemeInstalledInfoBarDelegate* delegate = tab_contents->
        GetInfoBarDelegateAt(0)->AsThemePreviewInfobarDelegate();
    ASSERT_TRUE(delegate);
    delegate->Cancel();
    ASSERT_EQ(0, tab_contents->infobar_delegate_count());
  }
};

// Flaky, http://crbug.com/43441.
// Crashy, http://crbug.com/44548.
IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest,
                       DISABLED_TestThemeInstallUndoResetsToDefault) {
  // Install theme once and undo to verify we go back to default theme.
  FilePath theme_path = test_data_dir_.AppendASCII("theme.crx");
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1));
  Extension* theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());

  // Set the same theme twice and undo to verify we go back to default theme.
  // We set the |expected_change| to zero in these 'InstallExtensionWithUI'
  // calls since the theme has already been installed above and this is an
  // overinstall to set the active theme.
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0));
  theme = browser()->profile()->GetTheme();
  ASSERT_TRUE(theme);
  ASSERT_EQ(theme_crx, theme->id());
  VerifyThemeInfoBarAndUndoInstall();
  ASSERT_EQ(NULL, browser()->profile()->GetTheme());
}
<|endoftext|>


<commit_before>/*
 * simple_tree.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: programmer
 */
#include <Magick++.h>
#include "../model/surrogate_tree_node.h"
#include "../io/git_repository_access.h"
#include "../io/github_repository_access.h"
#include "../io/svn_remote_repository_access.h"
#include "../io/cvs_remote_repository_access.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"
#include "../system/discursive_system.h"

using namespace Magick;

int main(int argc, char **argv)
{
	// Tree image size parameters
	int WIDTH = 500;
	int HEIGHT = 500;

	// Tree Generation pipeline

	// Retrieve tree from GIT and create surrogate tree
	// for now, ask the user if local files or github project
	cout << "\n1==local git\n2==grit git remote Project\n3==any github project";
	cout << "\n4==http://hkit.googlecode.com/svn/trunk/\n5==any SVN url";
	cout << "\n6==pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd";
	cout << "\n7==any CVS url\n";
	int answer = 0 * argc;
	cin >> answer;

	RepositoryAccess* git;
	if(answer == 1)
	{
		git = new GitRepositoryAccess("~/Projects/source_tree_vis");
	}
	else if(answer == 2)
	{
		git = new GitHubRepositoryAccess("mojombo","grit");
	}
	else if(answer == 3)
	{
		// allow user to pick github user name/project
		char userNameBuffer[255];
		char projectNameBuffer[255];
		cout << "\nEnter the github user name\n";
		cin >> userNameBuffer;
		cout << "\nEnter the github project name\n";
		cin >> projectNameBuffer;

		git = new GitHubRepositoryAccess(userNameBuffer,projectNameBuffer);
	}
	else if(answer == 4)
	{
		git = new SvnRemoteRepositoryAccess(" http://hkit.googlecode.com/svn/trunk/");
	}
	else if(answer == 5)
	{
		char svnRepoBuffer[255];
		cout << "\nEnter a SVN url like http://hkit.googlecode.com/svn/trunk/\n";
		cin >> svnRepoBuffer;
		git = new SvnRemoteRepositoryAccess(svnRepoBuffer);
	}
	else if(answer == 6)
	{
		git = new CvsRemoteRepositoryAccess("pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd");
	}
	else if(answer == 7)
	{
		char cvsRepoBuffer[255];
		cout << "\nEnter a qualified CVS url like pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
		cin >> cvsRepoBuffer;
		git = new CvsRemoteRepositoryAccess(cvsRepoBuffer);
	}

	SurrogateTreeNode* source = git->retrieve();
	printf("Source tree name is %s\n", source->data["name"].c_str());

	// Decorate surrogate tree nodes with locations
	SpatialDisplacement* disp = new SpatialDisplacement(WIDTH,HEIGHT);
	disp->decorate(source);

	// Digitize decorated surrogate tree into line segment tree
	SpaceColonizer* digitizer = new SpaceColonizer(2);
	DrawableData* lines = digitizer->digitize(source);

	// Transform

	// Draw tree
	InitializeMagick(*argv);
	Image canvas(Geometry(WIDTH,HEIGHT),"white");
	ScanlineArtist* artist = new ScanlineArtist();
	artist->draw(canvas, lines);

	try
	{
		// Write the image to a file
		canvas.write( "out/tree.jpg" );
	}
	catch( Exception &error_ )
	{
		DiscursiveError(error_.what());
	}

	return 0;
}
<commit_msg>updated call to set debug level<commit_after>/*
 * simple_tree.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: programmer
 */
#include <Magick++.h>
#include "../model/surrogate_tree_node.h"
#include "../io/git_repository_access.h"
#include "../io/github_repository_access.h"
#include "../io/svn_remote_repository_access.h"
#include "../io/cvs_remote_repository_access.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"
#include "../system/discursive_system.h"

using namespace Magick;

int main(int argc, char **argv)
{
	// set the debug level
	SetDiscursiveDebugLevel(1);
	// Tree image size parameters
	int WIDTH = 500;
	int HEIGHT = 500;

	// Tree Generation pipeline

	// Retrieve tree from GIT and create surrogate tree
	// for now, ask the user if local files or github project
	cout << "\n1==local git\n2==grit git remote Project\n3==any github project";
	cout << "\n4==http://hkit.googlecode.com/svn/trunk/\n5==any SVN url";
	cout << "\n6==pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd";
	cout << "\n7==any CVS url\n";
	int answer = 0 * argc;
	cin >> answer;

	RepositoryAccess* git;
	if(answer == 1)
	{
		git = new GitRepositoryAccess("~/Projects/source_tree_vis");
	}
	else if(answer == 2)
	{
		git = new GitHubRepositoryAccess("mojombo","grit");
	}
	else if(answer == 3)
	{
		// allow user to pick github user name/project
		char userNameBuffer[255];
		char projectNameBuffer[255];
		cout << "\nEnter the github user name\n";
		cin >> userNameBuffer;
		cout << "\nEnter the github project name\n";
		cin >> projectNameBuffer;

		git = new GitHubRepositoryAccess(userNameBuffer,projectNameBuffer);
	}
	else if(answer == 4)
	{
		git = new SvnRemoteRepositoryAccess(" http://hkit.googlecode.com/svn/trunk/");
	}
	else if(answer == 5)
	{
		char svnRepoBuffer[255];
		cout << "\nEnter a SVN url like http://hkit.googlecode.com/svn/trunk/\n";
		cin >> svnRepoBuffer;
		git = new SvnRemoteRepositoryAccess(svnRepoBuffer);
	}
	else if(answer == 6)
	{
		git = new CvsRemoteRepositoryAccess("pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd");
	}
	else if(answer == 7)
	{
		char cvsRepoBuffer[255];
		cout << "\nEnter a qualified CVS url like pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
		cin >> cvsRepoBuffer;
		git = new CvsRemoteRepositoryAccess(cvsRepoBuffer);
	}

	SurrogateTreeNode* source = git->retrieve();
	printf("Source tree name is %s\n", source->data["name"].c_str());

	// Decorate surrogate tree nodes with locations
	SpatialDisplacement* disp = new SpatialDisplacement(WIDTH,HEIGHT);
	disp->decorate(source);

	// Digitize decorated surrogate tree into line segment tree
	SpaceColonizer* digitizer = new SpaceColonizer(2);
	DrawableData* lines = digitizer->digitize(source);

	// Transform

	// Draw tree
	InitializeMagick(*argv);
	Image canvas(Geometry(WIDTH,HEIGHT),"white");
	ScanlineArtist* artist = new ScanlineArtist();
	artist->draw(canvas, lines);

	try
	{
		// Write the image to a file
		canvas.write( "out/tree.jpg" );
	}
	catch( Exception &error_ )
	{
		DiscursiveError(error_.what());
	}

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}
<commit_msg>Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// Disabled, http://crbug.com/63589.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/extensions/extension_installed_bubble.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/location_bar_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/image_button.h"
#include "views/controls/label.h"
#include "views/standard_layout.h"
#include "views/view.h"

namespace {

const int kIconSize = 43;

const int kRightColumnWidth = 285;

// The InfoBubble uses a BubbleBorder which adds about 6 pixels of whitespace
// around the content view. We compensate by reducing our outer borders by this
// amount.
const int kBubbleBorderInsert = 6;
const int kHorizOuterMargin = kPanelHorizMargin - kBubbleBorderInsert;
const int kVertOuterMargin = kPanelVertMargin - kBubbleBorderInsert;

// The image we use for the close button has three pixels of whitespace padding.
const int kCloseButtonPadding = 3;

// InstalledBubbleContent is the content view which is placed in the
// ExtensionInstalledBubble. It displays the install icon and explanatory
// text about the installed extension.
class InstalledBubbleContent : public views::View,
                               public views::ButtonListener {
 public:
  InstalledBubbleContent(Extension* extension,
                         ExtensionInstalledBubble::BubbleType type,
                         SkBitmap* icon)
      : type_(type),
        info_(NULL) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont);

    // Scale down to 43x43, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > kIconSize || size.height() > kIconSize)
      size = gfx::Size(kIconSize, kIconSize);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
                              UTF8ToWide(extension->name())));
    heading_->SetFont(font.DeriveFont(3, gfx::Font::NORMAL));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);

    if (type_ == ExtensionInstalledBubble::PAGE_ACTION) {
      info_ = new views::Label(l10n_util::GetString(
          IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO));
      info_->SetFont(font);
      info_->SetMultiLine(true);
      info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
      AddChildView(info_);
    }

    manage_ = new views::Label(l10n_util::GetString(
      IDS_EXTENSION_INSTALLED_MANAGE_INFO));
    manage_->SetFont(font);
    manage_->SetMultiLine(true);
    manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(manage_);

    close_button_ = new views::ImageButton(this);
    close_button_->SetImage(views::CustomButton::BS_NORMAL,
        rb.GetBitmapNamed(IDR_CLOSE_BAR));
    close_button_->SetImage(views::CustomButton::BS_HOT,
        rb.GetBitmapNamed(IDR_CLOSE_BAR_H));
    close_button_->SetImage(views::CustomButton::BS_PUSHED,
        rb.GetBitmapNamed(IDR_CLOSE_BAR_P));
    AddChildView(close_button_);
  }

  virtual void ButtonPressed(
      views::Button* sender,
      const views::Event& event) {
    GetWidget()->Close();
  }

 private:
  virtual gfx::Size GetPreferredSize() {
    int width = kRightColumnWidth + kHorizOuterMargin + kHorizOuterMargin;
    width += kIconSize;
    width += kPanelHorizMargin;
    width += close_button_->GetPreferredSize().width();
    width -= 2 * kCloseButtonPadding;
    width += kPanelHorizMargin;

    int height = kVertOuterMargin * 2;
    height += heading_->GetHeightForWidth(kRightColumnWidth);
    height += kPanelVertMargin;
    if (type_ == ExtensionInstalledBubble::PAGE_ACTION) {
      height += info_->GetHeightForWidth(kRightColumnWidth);
      height += kPanelVertMargin;
    }
    height += manage_->GetHeightForWidth(kRightColumnWidth);

    return gfx::Size(width, std::max(height, kIconSize + kVertOuterMargin * 2));
  }

  virtual void Layout() {
    int x = kHorizOuterMargin;
    int y = kVertOuterMargin;

    icon_->SetBounds(x, y, kIconSize, kIconSize);
    x += kIconSize;
    x += kPanelHorizMargin;

    heading_->SizeToFit(kRightColumnWidth);
    heading_->SetX(x);
    heading_->SetY(y);
    y += heading_->height();
    y += kPanelVertMargin;

    if (type_ == ExtensionInstalledBubble::PAGE_ACTION) {
      info_->SizeToFit(kRightColumnWidth);
      info_->SetX(x);
      info_->SetY(y);
      y += info_->height();
      y += kPanelVertMargin;
    }

    manage_->SizeToFit(kRightColumnWidth);
    manage_->SetX(x);
    manage_->SetY(y);

    x += kRightColumnWidth + kPanelHorizMargin;
    y = kVertOuterMargin;
    gfx::Size sz = close_button_->GetPreferredSize();
    close_button_->SetBounds(x - kCloseButtonPadding,
                             y - kCloseButtonPadding,
                             sz.width(),
                             sz.height());
}

  ExtensionInstalledBubble::BubbleType type_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* info_;
  views::Label* manage_;
  views::ImageButton* close_button_;

  DISALLOW_COPY_AND_ASSIGN(InstalledBubbleContent);
};

}  // namespace

void ExtensionInstalledBubble::Show(Extension *extension, Browser *browser,
                                    SkBitmap icon) {
  new ExtensionInstalledBubble(extension, browser, icon);
}

ExtensionInstalledBubble::ExtensionInstalledBubble(Extension *extension,
                                                   Browser *browser,
                                                   SkBitmap icon)
    : extension_(extension),
      browser_(browser),
      icon_(icon) {
  AddRef();  // Balanced in InfoBubbleClosing.

  if (extension_->browser_action()) {
    type_ = BROWSER_ACTION;
  } else if (extension->page_action() &&
             !extension->page_action()->default_icon_path().empty()) {
    type_ = PAGE_ACTION;
  } else {
    type_ = GENERIC;
  }

  // |extension| has been initialized but not loaded at this point. We need
  // to wait on showing the Bubble until not only the EXTENSION_LOADED gets
  // fired, but all of the EXTENSION_LOADED Observers have run. Only then can we
  // be sure that a BrowserAction or PageAction has had views created which we
  // can inspect for the purpose of previewing of pointing to them.
  registrar_.Add(this, NotificationType::EXTENSION_LOADED,
      NotificationService::AllSources());
}

void ExtensionInstalledBubble::Observe(NotificationType type,
                                       const NotificationSource& source,
                                       const NotificationDetails& details) {
  if (type == NotificationType::EXTENSION_LOADED) {
    Extension* extension = Details<Extension>(details).ptr();
    if (extension == extension_) {
      // PostTask to ourself to allow all EXTENSION_LOADED Observers to run.
      MessageLoopForUI::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
          &ExtensionInstalledBubble::ShowInternal));
    }
  } else {
    NOTREACHED() << L"Received unexpected notification";
  }
}

void ExtensionInstalledBubble::ShowInternal() {
  BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
      browser_->window()->GetNativeHandle());

  views::View* reference_view = NULL;
  if (type_ == BROWSER_ACTION) {
    reference_view = browser_view->GetToolbarView()->browser_actions()
        ->GetBrowserActionView(extension_);
    DCHECK(reference_view);
  } else if (type_ == PAGE_ACTION) {
    LocationBarView* location_bar_view = browser_view->GetLocationBarView();
    location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(),
                                                   true);  // preview_enabled
    reference_view = location_bar_view->GetPageActionView(
        extension_->page_action());
    DCHECK(reference_view);
  }

  // Default case.
  if (reference_view == NULL)
    reference_view = browser_view->GetToolbarView()->app_menu();

  gfx::Point origin;
  views::View::ConvertPointToScreen(reference_view, &origin);
  gfx::Rect bounds = reference_view->bounds();
  bounds.set_x(origin.x());
  bounds.set_y(origin.y());

  views::View* bubble_content = new InstalledBubbleContent(extension_, type_,
      &icon_);
  InfoBubble::Show(browser_view->GetWindow(), bounds, bubble_content, this);
}

// InfoBubbleDelegate
void ExtensionInstalledBubble::InfoBubbleClosing(InfoBubble* info_bubble,
                                                 bool closed_by_escape) {
  if (extension_->page_action()) {
    BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
        browser_->window()->GetNativeHandle());
    browser_view->GetLocationBarView()->SetPreviewEnabledPageAction(
        extension_->page_action(),
        false);  // preview_enabled
  }
  Release();  // Balanced in ctor.
}
<commit_msg>ExtensionInstalledBubble border/sizing polish<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/extensions/extension_installed_bubble.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/location_bar_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/image_button.h"
#include "views/controls/label.h"
#include "views/standard_layout.h"
#include "views/view.h"

namespace {

const int kIconSize = 43;

const int kRightColumnWidth = 285;

// The InfoBubble uses a BubbleBorder which adds about 6 pixels of whitespace
// around the content view. We compensate by reducing our outer borders by this
// amount + 4px.
const int kOuterMarginInset = 10;
const int kHorizOuterMargin = kPanelHorizMargin - kOuterMarginInset;
const int kVertOuterMargin = kPanelVertMargin - kOuterMarginInset;

// Interior vertical margin is 8px smaller than standard
const int kVertInnerMargin = kPanelVertMargin - 8;

// The image we use for the close button has three pixels of whitespace padding.
const int kCloseButtonPadding = 3;

// We want to shift the right column (which contains the header and text) up
// 4px to align with icon.
const int kRightcolumnVerticalShift = -4;

// InstalledBubbleContent is the content view which is placed in the
// ExtensionInstalledBubble. It displays the install icon and explanatory
// text about the installed extension.
class InstalledBubbleContent : public views::View,
                               public views::ButtonListener {
 public:
  InstalledBubbleContent(Extension* extension,
                         ExtensionInstalledBubble::BubbleType type,
                         SkBitmap* icon)
      : type_(type),
        info_(NULL) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont);

    // Scale down to 43x43, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > kIconSize || size.height() > kIconSize)
      size = gfx::Size(kIconSize, kIconSize);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
                              UTF8ToWide(extension->name())));
    heading_->SetFont(font.DeriveFont(3, gfx::Font::NORMAL));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);

    if (type_ == ExtensionInstalledBubble::PAGE_ACTION) {
      info_ = new views::Label(l10n_util::GetString(
          IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO));
      info_->SetFont(font);
      info_->SetMultiLine(true);
      info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
      AddChildView(info_);
    }

    manage_ = new views::Label(l10n_util::GetString(
      IDS_EXTENSION_INSTALLED_MANAGE_INFO));
    manage_->SetFont(font);
    manage_->SetMultiLine(true);
    manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(manage_);

    close_button_ = new views::ImageButton(this);
    close_button_->SetImage(views::CustomButton::BS_NORMAL,
        rb.GetBitmapNamed(IDR_CLOSE_BAR));
    close_button_->SetImage(views::CustomButton::BS_HOT,
        rb.GetBitmapNamed(IDR_CLOSE_BAR_H));
    close_button_->SetImage(views::CustomButton::BS_PUSHED,
        rb.GetBitmapNamed(IDR_CLOSE_BAR_P));
    AddChildView(close_button_);
  }

  virtual void ButtonPressed(
      views::Button* sender,
      const views::Event& event) {
    GetWidget()->Close();
  }

 private:
  virtual gfx::Size GetPreferredSize() {
    int width = kHorizOuterMargin;
    width += kIconSize;
    width += kPanelHorizMargin;
    width += kRightColumnWidth;
    width += 2*kPanelHorizMargin;
    width += kHorizOuterMargin;

    int height = kVertOuterMargin;
    height += heading_->GetHeightForWidth(kRightColumnWidth);
    height += kVertInnerMargin;
    if (type_ == ExtensionInstalledBubble::PAGE_ACTION) {
      height += info_->GetHeightForWidth(kRightColumnWidth);
      height += kVertInnerMargin;
    }
    height += manage_->GetHeightForWidth(kRightColumnWidth);
    height += kVertOuterMargin;
    return gfx::Size(width, std::max(height, kIconSize + 2 * kVertOuterMargin));
  }

  virtual void Layout() {
    int x = kHorizOuterMargin;
    int y = kVertOuterMargin;

    icon_->SetBounds(x, y, kIconSize, kIconSize);
    x += kIconSize;
    x += kPanelHorizMargin;

    y += kRightcolumnVerticalShift;
    heading_->SizeToFit(kRightColumnWidth);
    heading_->SetX(x);
    heading_->SetY(y);
    y += heading_->height();
    y += kVertInnerMargin;

    if (type_ == ExtensionInstalledBubble::PAGE_ACTION) {
      info_->SizeToFit(kRightColumnWidth);
      info_->SetX(x);
      info_->SetY(y);
      y += info_->height();
      y += kVertInnerMargin;
    }

    manage_->SizeToFit(kRightColumnWidth);
    manage_->SetX(x);
    manage_->SetY(y);

    x += kRightColumnWidth + 2*kPanelHorizMargin + kHorizOuterMargin -
        close_button_->GetPreferredSize().width();
    y = kVertOuterMargin;
    gfx::Size sz = close_button_->GetPreferredSize();
    // x-1 & y-1 is just slop to get the close button visually aligned with the
    // title text and bubble arrow.
    close_button_->SetBounds(x - 1, y - 1, sz.width(), sz.height());
}

  ExtensionInstalledBubble::BubbleType type_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* info_;
  views::Label* manage_;
  views::ImageButton* close_button_;

  DISALLOW_COPY_AND_ASSIGN(InstalledBubbleContent);
};

}  // namespace

void ExtensionInstalledBubble::Show(Extension *extension, Browser *browser,
                                    SkBitmap icon) {
  new ExtensionInstalledBubble(extension, browser, icon);
}

ExtensionInstalledBubble::ExtensionInstalledBubble(Extension *extension,
                                                   Browser *browser,
                                                   SkBitmap icon)
    : extension_(extension),
      browser_(browser),
      icon_(icon) {
  AddRef();  // Balanced in InfoBubbleClosing.

  if (extension_->browser_action()) {
    type_ = BROWSER_ACTION;
  } else if (extension->page_action() &&
             !extension->page_action()->default_icon_path().empty()) {
    type_ = PAGE_ACTION;
  } else {
    type_ = GENERIC;
  }

  // |extension| has been initialized but not loaded at this point. We need
  // to wait on showing the Bubble until not only the EXTENSION_LOADED gets
  // fired, but all of the EXTENSION_LOADED Observers have run. Only then can we
  // be sure that a BrowserAction or PageAction has had views created which we
  // can inspect for the purpose of previewing of pointing to them.
  registrar_.Add(this, NotificationType::EXTENSION_LOADED,
      NotificationService::AllSources());
}

void ExtensionInstalledBubble::Observe(NotificationType type,
                                       const NotificationSource& source,
                                       const NotificationDetails& details) {
  if (type == NotificationType::EXTENSION_LOADED) {
    Extension* extension = Details<Extension>(details).ptr();
    if (extension == extension_) {
      // PostTask to ourself to allow all EXTENSION_LOADED Observers to run.
      MessageLoopForUI::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
          &ExtensionInstalledBubble::ShowInternal));
    }
  } else {
    NOTREACHED() << L"Received unexpected notification";
  }
}

void ExtensionInstalledBubble::ShowInternal() {
  BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
      browser_->window()->GetNativeHandle());

  views::View* reference_view = NULL;
  if (type_ == BROWSER_ACTION) {
    reference_view = browser_view->GetToolbarView()->browser_actions()
        ->GetBrowserActionView(extension_);
    DCHECK(reference_view);
  } else if (type_ == PAGE_ACTION) {
    LocationBarView* location_bar_view = browser_view->GetLocationBarView();
    location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(),
                                                   true);  // preview_enabled
    reference_view = location_bar_view->GetPageActionView(
        extension_->page_action());
    DCHECK(reference_view);
  }

  // Default case.
  if (reference_view == NULL)
    reference_view = browser_view->GetToolbarView()->app_menu();

  gfx::Point origin;
  views::View::ConvertPointToScreen(reference_view, &origin);
  gfx::Rect bounds = reference_view->bounds();
  bounds.set_x(origin.x());
  bounds.set_y(origin.y());

  views::View* bubble_content = new InstalledBubbleContent(extension_, type_,
      &icon_);
  InfoBubble::Show(browser_view->GetWindow(), bounds, bubble_content, this);
}

// InfoBubbleDelegate
void ExtensionInstalledBubble::InfoBubbleClosing(InfoBubble* info_bubble,
                                                 bool closed_by_escape) {
  if (extension_->page_action()) {
    BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
        browser_->window()->GetNativeHandle());
    browser_view->GetLocationBarView()->SetPreviewEnabledPageAction(
        extension_->page_action(),
        false);  // preview_enabled
  }
  Release();  // Balanced in ctor.
}
<|endoftext|>