<commit_before>#include "TDirectory.h"
#include "TMath.h"
#include "TString.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

AliAnalysisTask *AddTaskJFFlucJCMAPsMaster(TString taskName = "JFFlucJCMAP_Run2_pass2", UInt_t period = 0, double ptMin = 0.2, double ptMax = 5.0,
  std::string configArray = "0 1 2 4 5 8 11 13", bool saveQA = kFALSE, bool ESDpileup = false, double intercept = 15000, bool saveQApileup = false)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // Less essential global variables.
  bool removeBadArea = kFALSE;
  int debug = 0;
  bool useTightCuts = kFALSE;
  double slope = 3.38;

  // Prepare the configuration of the wagons.
  enum { lhc15o = 0, lhc18q = 1, lhc18r = 2 };
  TString speriod[3] = { "15o", "18q", "18r" };   // Needed to load correct map config.
  std::cout << "AddTaskJFFlucJCMAPsMaster:: period =" << period << "\t pT range = ("
    << ptMin << "," << ptMax << ")." << std::endl;

  int iConfig = -1;
  int iOldConfig = -2;
  int index = 0;
  std::vector<TString> configNames;
  std::istringstream sConfig(configArray);

  do {
    sConfig >> iConfig;
    if (iOldConfig == iConfig) {break;}

    switch(iConfig) {   // Hardcoded names to prevent typo in phi weights files.
      // For the "syst" selection: only the changed variables is indicated, all the others are left as in default.
    case 0 :    // Default selection.     // V0M + |zVtx < 8| + (pileup > 15000)
      configNames.push_back("default");   // + global tracks 96 + (NTPC < 70) + (chi2 in [0.1, 4]).
      break;
    case 1 :    // Syst: global changed to hybrid.
      configNames.push_back("hybrid");
      break;
    case 2 :    // Syst: V0M changed to SPD clusters.
      configNames.push_back("SPD");
      break;
    case 3 :    // Syst: (pileup > 15000) changed to (no pileup cut).
      configNames.push_back("noPileup");
      break;
    case 4 :    // Syst: (pileup > 15000) changed to (pileup > 10000).
      configNames.push_back("pileup10");
      break;
    case 5 :    // Syst: |zVtx < 8| changed to |zVtx < 10|.
      configNames.push_back("zvtx10");
      break;
    case 6 :    // Syst: |zVtx < 8| changed to |zVtx < 9|.
      configNames.push_back("zvtx9");
      break;
    case 7 :    // Syst: |zVtx < 8| changed to |zVtx < 7|.
      configNames.push_back("zvtx7");
      break;
    case 8 :    // Syst: (NTPC > 70) changed to (NTPC > 80).
      configNames.push_back("NTPC80");
      break;
    case 9 :    // Syst: (NTPC > 70) changed to (NTPC > 90).
      configNames.push_back("NTPC90");
      break;
    case 10 :    // Syst: (NTPC > 70) changed to (NTPC > 100).
      configNames.push_back("NTPC100");
      break;
    case 11 :    // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 4).
      configNames.push_back("chi2def");
      break;
    case 12 :    // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 2.5).
      configNames.push_back("chi2tight");
      break;
    case 13 :     // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 1cm).
      configNames.push_back("DCAz1");
      break;
    case 14 :     // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 0.5cm).
      configNames.push_back("DCAz05");
      break;
    case 15 :     // Syst: (all charges) changed to (negative charges only).
      configNames.push_back("nqq");
      break;
    case 16 :     // Syst: (all charges) changed to (positive charges only).
      configNames.push_back("pqq");
      break;
    case 17 :     // Syst: subA. TBI
      configNames.push_back("subA");
      break;
    default :
      std::cout << "ERROR: Invalid configuration index. Skipping this element."
        << std::endl;
    }
    index++;
    iOldConfig = iConfig;
  } while (sConfig);

// Load the correction maps.
// We assume the same maps for all minPt values.

  TString MAPfilenames;  // Azimuthal corrections.
  TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/";
  AliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask("JCorrectionMapTask");
  TString sCorrection[3] = { "15o", "18q", "18r" }; // 17i2a for 15o?

  if (period == lhc18q || period == lhc18r) {   // 2018 PbPb datasets.
    cmaptask->EnableCentFlattening(Form("alien:///alice/cern.ch/user/j/jparkkil/legotrain/Cent/CentWeights_LHC%s_pass13.root", speriod[period].Data()));
    cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC18l8-0-Lists.root", speriod[period].Data()));
  } else if (period == lhc15o) {    // 2015 PbPb dataset.
    cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC16g-0-Lists.root", speriod[period].Data()));
  }

  MAPfilenames = Form("%sPhiWeights_LHC%s_Error_pt02_s_%s.root", MAPdirname.Data(), sCorrection[period].Data(), configName.Data());
  cmaptask->EnablePhiCorrection(0, MAPfilenames);  // i = 0: index for 'SetPhiCorrectionIndex(i)'.
  mgr->AddTask((AliAnalysisTask *) cmaptask);

  // Set the general variables.
  int globalCut = 96;       // Global tracks - default.
  int hybridCut = 768;      // Hybrid tracks.
  UInt_t selEvt;            // Trigger.
  if (period == lhc15o) {   // Minimum bias.
    selEvt = AliVEvent::kINT7;
  } else if (period == lhc18q || period == lhc18r) {  // Minimum bias + central + semicentral.
    selEvt = AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral;
  }

  // Configure the catalyst tasks for each config.
  // taskName added in the name of the catalyst to prevent merging issues between wagons.
  const int Nsets = index;
  AliJCatalystTask *fJCatalyst[Nsets];  // One catalyst needed per configuration.
  for (int i = 0; i < Nsets; i++) {
    fJCatalyst[i] = new AliJCatalystTask(Form("JCatalystTask_%s_s_%s", taskName.Data(), configNames[i].Data()));
    std::cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << std::endl;
    fJCatalyst[i]->SetSaveAllQA(saveQA);

    /// Trigger and centrality selection.
    fJCatalyst[i]->SelectCollisionCandidates(selEvt);
    fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
    fJCatalyst[i]->SetInitializeCentralityArray();
    if (strcmp(configNames[i].Data(), "SPD") == 0) {
      fJCatalyst[i]->SetCentDetName("CL1");
    } else {  // Default: V0M.
      fJCatalyst[i]->SetCentDetName("V0M");
    }

    /// Event selection: pileup cuts and Zvtx.
    if (strcmp(configNames[i].Data(), "noPileup") != 0) {   // Set flag only if we cut on pileup.
      fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CUT_OUTLIERS);
      if (strcmp(configNames[i].Data(), "pileup10") == 0) {fJCatalyst[i]->SetESDpileupCuts(true, slope, 10000, saveQApileup);}
      else {fJCatalyst[i]->SetESDpileupCuts(ESDpileup, slope, intercept, saveQApileup);}
    }
    if (period == lhc18q || period == lhc18r) {fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CENT_FLATTENING);}

    if (strcmp(configNames[i].Data(), "zvtx10") == 0) {
      fJCatalyst[i]->SetZVertexCut(10.0);
    } else if (strcmp(configNames[i].Data(), "zvtx9") == 0) {
      fJCatalyst[i]->SetZVertexCut(9.0);
    } else if (strcmp(configNames[i].Data(), "zvtx7") == 0) {
      fJCatalyst[i]->SetZVertexCut(7.0);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetZVertexCut(8.0);
    }

    /// Filtering, kinematic and detector cuts.
    if (strcmp(configNames[i].Data(), "hybrid") == 0) {
      fJCatalyst[i]->SetTestFilterBit(hybridCut);
    } else {  // Default: global tracks.
      fJCatalyst[i]->SetTestFilterBit(globalCut);
    }

    if (strcmp(configNames[i].Data(), "NTPC80") == 0) {
      fJCatalyst[i]->SetNumTPCClusters(80);
    } else if (strcmp(configNames[i].Data(), "NTPC90") == 0) {
      fJCatalyst[i]->SetNumTPCClusters(90);
    } else if (strcmp(configNames[i].Data(), "NTPC100") == 0) {
      fJCatalyst[i]->SetNumTPCClusters(100);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetNumTPCClusters(70);
    }

    if (strcmp(configNames[i].Data(), "chi2def") == 0) {
      fJCatalyst[i]->SetChi2Cuts(0.0, 4.0);
    } else if (strcmp(configNames[i].Data(), "chi2tight") == 0) {
      fJCatalyst[i]->SetChi2Cuts(0.0, 2.5);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetChi2Cuts(0.1, 4.0);
    }

    if (strcmp(configNames[i].Data(), "DCAz1") == 0) {
      fJCatalyst[i]->SetDCAzCut(1.0);
    } else if (strcmp(configNames[i].Data(), "DCAz05") == 0) {
      fJCatalyst[i]->SetDCAzCut(0.5);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetDCAzCut(2.0);
    }

    if (strcmp(configNames[i].Data(), "nqq") == 0) {
      fJCatalyst[i]->SetParticleCharge(-1);
    } else if (strcmp(configNames[i].Data(), "pqq") == 0) {
      fJCatalyst[i]->SetParticleCharge(1);
    }   // Default: charge = 0 to accept all charges.

    // TBA: subA systematics.

    fJCatalyst[i]->SetPtRange(ptMin, ptMax);
    fJCatalyst[i]->SetEtaRange(-0.8, 0.8);
    fJCatalyst[i]->SetPhiCorrectionIndex(i);
    fJCatalyst[i]->SetRemoveBadArea(removeBadArea);
    fJCatalyst[i]->SetTightCuts(useTightCuts);
    mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);
  }

// Configure the analysis task wagons.
  AliJFFlucJCTask *myTask[Nsets];
  for (int i = 0; i < Nsets; i++) {
    myTask[i] = new AliJFFlucJCTask(Form("%s_s_%s",
      taskName.Data(), configNames[i].Data()));
    myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());

    mgr->AddTask((AliAnalysisTask *)myTask[i]);
  }

// Create the containers for input/output.
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *jHist[2*Nsets];

  for (int i = 0; i < Nsets; i++) {
    mgr->ConnectInput(fJCatalyst[i], 0, cinput);
    mgr->ConnectInput(myTask[i], 0, cinput);

    jHist[i] = new AliAnalysisDataContainer();
    jHist[i] = mgr->CreateContainer(Form("%s", myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer,
      Form("%s:%s", AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));
    mgr->ConnectOutput(myTask[i], 1, jHist[i]);

    jHist[Nsets+i] = new AliAnalysisDataContainer();
    jHist[Nsets+i] = mgr->CreateContainer(Form("%s", fJCatalyst[i]->GetName()),
      TList::Class(), AliAnalysisManager::kOutputContainer,
      Form("%s", AliAnalysisManager::GetCommonFileName()));
    mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]);
  }

  return myTask[0];
}
<commit_msg>Adding macro with corrections switched on<commit_after>#include "TDirectory.h"
#include "TMath.h"
#include "TString.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

AliAnalysisTask *AddTaskJFFlucJCMasterCorrOn(TString taskName = "JFFlucJCMAP_Run2_pass2", UInt_t period = 0, double ptMin = 0.2, double ptMax = 5.0,
  std::string configArray = "0", bool saveQA = kFALSE, bool ESDpileup = false, double intercept = 15000, bool saveQApileup = false)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // Less essential global variables.
  // Enable only one Config for now because of map memory
  bool removeBadArea = kFALSE;
  int debug = 0;
  bool useTightCuts = kFALSE;
  double slope = 3.38;

  // Prepare the configuration of the wagons.
  enum { lhc15o = 0, lhc18q = 1, lhc18r = 2 };
  TString speriod[3] = { "15o", "18q", "18r" };   // Needed to load correct map config.
  std::cout << "AddTaskJFFlucJCMAPsMaster:: period =" << period << "\t pT range = ("
    << ptMin << "," << ptMax << ")." << std::endl;

  int iConfig = -1;
  int iOldConfig = -2;
  int index = 0;
  std::vector<TString> configNames;
  std::istringstream sConfig(configArray);

  do {
    sConfig >> iConfig;
    if (iOldConfig == iConfig) {break;}

    switch(iConfig) {   // Hardcoded names to prevent typo in phi weights files.
      // For the "syst" selection: only the changed variables is indicated, all the others are left as in default.
    case 0 :    // Default selection.     // V0M + |zVtx < 8| + (pileup > 15000)
      configNames.push_back("default");   // + global tracks 96 + (NTPC < 70) + (chi2 in [0.1, 4]).
      break;
    case 1 :    // Syst: global changed to hybrid.
      configNames.push_back("hybrid");
      break;
    case 2 :    // Syst: V0M changed to SPD clusters.
      configNames.push_back("SPD");
      break;
    case 3 :    // Syst: (pileup > 15000) changed to (no pileup cut).
      configNames.push_back("noPileup");
      break;
    case 4 :    // Syst: (pileup > 15000) changed to (pileup > 10000).
      configNames.push_back("pileup10");
      break;
    case 5 :    // Syst: |zVtx < 8| changed to |zVtx < 10|.
      configNames.push_back("zvtx10");
      break;
    case 6 :    // Syst: |zVtx < 8| changed to |zVtx < 9|.
      configNames.push_back("zvtx9");
      break;
    case 7 :    // Syst: |zVtx < 8| changed to |zVtx < 7|.
      configNames.push_back("zvtx7");
      break;
    case 8 :    // Syst: (NTPC > 70) changed to (NTPC > 80).
      configNames.push_back("NTPC80");
      break;
    case 9 :    // Syst: (NTPC > 70) changed to (NTPC > 90).
      configNames.push_back("NTPC90");
      break;
    case 10 :    // Syst: (NTPC > 70) changed to (NTPC > 100).
      configNames.push_back("NTPC100");
      break;
    case 11 :    // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 4).
      configNames.push_back("chi2def");
      break;
    case 12 :    // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 2.5).
      configNames.push_back("chi2tight");
      break;
    case 13 :     // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 1cm).
      configNames.push_back("DCAz1");
      break;
    case 14 :     // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 0.5cm).
      configNames.push_back("DCAz05");
      break;
    case 15 :     // Syst: (all charges) changed to (negative charges only).
      configNames.push_back("nqq");
      break;
    case 16 :     // Syst: (all charges) changed to (positive charges only).
      configNames.push_back("pqq");
      break;
    case 17 :     // Syst: subA. TBI
      configNames.push_back("subA");
      break;
    default :
      std::cout << "ERROR: Invalid configuration index. Skipping this element."
        << std::endl;
    }
    index++;
    iOldConfig = iConfig;
  } while (sConfig);

// Load the correction maps.
// We assume the same maps for all minPt values.

  TString MAPfilenames;  // Azimuthal corrections.
  TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/";
  AliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask("JCorrectionMapTask");

  if (period == lhc18q || period == lhc18r) {   // 2018 PbPb datasets.
    cmaptask->EnableCentFlattening(Form("alien:///alice/cern.ch/user/j/jparkkil/legotrain/Cent/CentWeights_LHC%s_pass13.root", speriod[period].Data()));
    cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC18l8-0-Lists.root", speriod[period].Data()));
  } else if (period == lhc15o) {    // 2015 PbPb dataset.
    cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC16g-0-Lists.root", speriod[period].Data()));
  }

  // Set the general variables.
  int globalCut = 96;       // Global tracks - default.
  int hybridCut = 768;      // Hybrid tracks.
  UInt_t selEvt;            // Trigger.
  if (period == lhc15o) {   // Minimum bias.
    selEvt = AliVEvent::kINT7;
  } else if (period == lhc18q || period == lhc18r) {  // Minimum bias + central + semicentral.
    selEvt = AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral;
  }

  // Configure the catalyst tasks for each config.
  // taskName added in the name of the catalyst to prevent merging issues between wagons.
  const int Nsets = index;
  AliJCatalystTask *fJCatalyst[Nsets];  // One catalyst needed per configuration.
  for (int i = 0; i < Nsets; i++) {
    MAPfilenames = Form("%sPhiWeights_LHC%s_Error_finerBins_pt02_s_%s.root", MAPdirname.Data(), speriod[period].Data(), configNames[i].Data());
    cmaptask->EnablePhiCorrection(i, MAPfilenames);  // i = 0: index for 'SetPhiCorrectionIndex(i)'.
    mgr->AddTask((AliAnalysisTask *) cmaptask);
    fJCatalyst[i] = new AliJCatalystTask(Form("JCatalystTask_%s_s_%s", taskName.Data(), configNames[i].Data()));
    std::cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << std::endl;
    fJCatalyst[i]->SetSaveAllQA(saveQA);
    fJCatalyst[i]->SetPhiCorrectionIndex(i); // same as line for cmaptask

    /// Trigger and centrality selection.
    fJCatalyst[i]->SelectCollisionCandidates(selEvt);
    fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
    fJCatalyst[i]->SetInitializeCentralityArray();
    if (strcmp(configNames[i].Data(), "SPD") == 0) {
      fJCatalyst[i]->SetCentDetName("CL1");
    } else {  // Default: V0M.
      fJCatalyst[i]->SetCentDetName("V0M");
    }

    /// Event selection: pileup cuts and Zvtx.
    if (strcmp(configNames[i].Data(), "noPileup") != 0) {   // Set flag only if we cut on pileup.
      fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CUT_OUTLIERS);
      if (strcmp(configNames[i].Data(), "pileup10") == 0) {fJCatalyst[i]->SetESDpileupCuts(true, slope, 10000, saveQApileup);}
      else {fJCatalyst[i]->SetESDpileupCuts(ESDpileup, slope, intercept, saveQApileup);}
    }
    if (period == lhc18q || period == lhc18r) {fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CENT_FLATTENING);}

    if (strcmp(configNames[i].Data(), "zvtx10") == 0) {
      fJCatalyst[i]->SetZVertexCut(10.0);
    } else if (strcmp(configNames[i].Data(), "zvtx9") == 0) {
      fJCatalyst[i]->SetZVertexCut(9.0);
    } else if (strcmp(configNames[i].Data(), "zvtx7") == 0) {
      fJCatalyst[i]->SetZVertexCut(7.0);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetZVertexCut(8.0);
    }

    /// Filtering, kinematic and detector cuts.
    if (strcmp(configNames[i].Data(), "hybrid") == 0) {
      fJCatalyst[i]->SetTestFilterBit(hybridCut);
    } else {  // Default: global tracks.
      fJCatalyst[i]->SetTestFilterBit(globalCut);
    }

    if (strcmp(configNames[i].Data(), "NTPC80") == 0) {
      fJCatalyst[i]->SetNumTPCClusters(80);
    } else if (strcmp(configNames[i].Data(), "NTPC90") == 0) {
      fJCatalyst[i]->SetNumTPCClusters(90);
    } else if (strcmp(configNames[i].Data(), "NTPC100") == 0) {
      fJCatalyst[i]->SetNumTPCClusters(100);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetNumTPCClusters(70);
    }

    if (strcmp(configNames[i].Data(), "chi2def") == 0) {
      fJCatalyst[i]->SetChi2Cuts(0.0, 4.0);
    } else if (strcmp(configNames[i].Data(), "chi2tight") == 0) {
      fJCatalyst[i]->SetChi2Cuts(0.0, 2.5);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetChi2Cuts(0.1, 4.0);
    }

    if (strcmp(configNames[i].Data(), "DCAz1") == 0) {
      fJCatalyst[i]->SetDCAzCut(1.0);
    } else if (strcmp(configNames[i].Data(), "DCAz05") == 0) {
      fJCatalyst[i]->SetDCAzCut(0.5);
    } else {  // Default value for JCorran analyses in Run 2.
      fJCatalyst[i]->SetDCAzCut(2.0);
    }

    if (strcmp(configNames[i].Data(), "nqq") == 0) {
      fJCatalyst[i]->SetParticleCharge(-1);
    } else if (strcmp(configNames[i].Data(), "pqq") == 0) {
      fJCatalyst[i]->SetParticleCharge(1);
    }   // Default: charge = 0 to accept all charges.

    // TBA: subA systematics.

    fJCatalyst[i]->SetPtRange(ptMin, ptMax);
    fJCatalyst[i]->SetEtaRange(-0.8, 0.8);
    fJCatalyst[i]->SetPhiCorrectionIndex(i);
    fJCatalyst[i]->SetRemoveBadArea(removeBadArea);
    fJCatalyst[i]->SetTightCuts(useTightCuts);
    mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);
  }

// Configure the analysis task wagons.
  AliJFFlucJCTask *myTask[Nsets];
  for (int i = 0; i < Nsets; i++) {
    myTask[i] = new AliJFFlucJCTask(Form("%s_s_%s",
      taskName.Data(), configNames[i].Data()));
    myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());

    mgr->AddTask((AliAnalysisTask *)myTask[i]);
  }

// Create the containers for input/output.
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *jHist[2*Nsets];

  for (int i = 0; i < Nsets; i++) {
    mgr->ConnectInput(fJCatalyst[i], 0, cinput);
    mgr->ConnectInput(myTask[i], 0, cinput);

    jHist[i] = new AliAnalysisDataContainer();
    jHist[i] = mgr->CreateContainer(Form("%s", myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer,
      Form("%s:%s", AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));
    mgr->ConnectOutput(myTask[i], 1, jHist[i]);

    jHist[Nsets+i] = new AliAnalysisDataContainer();
    jHist[Nsets+i] = mgr->CreateContainer(Form("%s", fJCatalyst[i]->GetName()),
      TList::Class(), AliAnalysisManager::kOutputContainer,
      Form("%s", AliAnalysisManager::GetCommonFileName()));
    mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]);
  }

  return myTask[0];
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

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

#include "QmitkNodeSelectionButton.h"

// berry includes
#include <berryWorkbenchPlugin.h>
#include <berryQtStyleManager.h>

#include "QPainter"
#include "QTextDocument"
#include "QEvent"

#include <mitkDataNode.h>
#include <QmitkNodeDescriptorManager.h>

// mitk core
#include <mitkBaseRenderer.h>
#include <mitkDataNode.h>
#include <mitkExtractSliceFilter.h>
#include <vtkMitkLevelWindowFilter.h>
#include <mitkPlanarFigure.h>
#include <mitkPropertyNameHelper.h>

// vtk
#include <vtkLookupTable.h>

QPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode, int height)
{
  if (nullptr == dataNode)
  {
    return QPixmap();
  }

  const mitk::Image* image = dynamic_cast<const mitk::Image*>(dataNode->GetData());
  if ((nullptr == image || !image->IsInitialized()) || // -> must be an image
    (image->GetPixelType().GetNumberOfComponents() != 1)) // -> for now only single component are allowed
  {
    auto descManager = QmitkNodeDescriptorManager::GetInstance();
    auto desc = descManager->GetDescriptor(dataNode);
    auto icon = desc->GetIcon(dataNode);
    auto fallBackMap = icon.pixmap(height, height);
    return fallBackMap;
  }

  mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
  int sliceNumber = image->GetDimension(2) / 2;
  planeGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::PlaneGeometry::Axial, sliceNumber);

  mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();
  extractSliceFilter->SetInput(image);
  extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);
  extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());
  extractSliceFilter->SetWorldGeometry(planeGeometry);
  extractSliceFilter->SetOutputDimensionality(2);
  extractSliceFilter->SetVtkOutputRequest(true);
  extractSliceFilter->Update();

  vtkImageData* imageData = extractSliceFilter->GetVtkOutput();

  mitk::LevelWindow levelWindow;
  dataNode->GetLevelWindow(levelWindow);
  vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();
  lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());
  lookupTable->SetSaturationRange(0.0, 0.0);
  lookupTable->SetValueRange(0.0, 1.0);
  lookupTable->SetHueRange(0.0, 0.0);
  lookupTable->SetRampToLinear();

  vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();
  levelWindowFilter->SetLookupTable(lookupTable);
  levelWindowFilter->SetInputData(imageData);
  levelWindowFilter->SetMinOpacity(0.0);
  levelWindowFilter->SetMaxOpacity(1.0);
  int dims[3];
  imageData->GetDimensions(dims);
  double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };
  levelWindowFilter->SetClippingBounds(clippingBounds);
  levelWindowFilter->Update();
  imageData = levelWindowFilter->GetOutput();

  QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);

  thumbnailImage = thumbnailImage.scaledToHeight(height,Qt::SmoothTransformation).rgbSwapped();
  return QPixmap::fromImage(thumbnailImage);
}

QmitkNodeSelectionButton::QmitkNodeSelectionButton(QWidget *parent)
  : QPushButton(parent), m_OutDatedThumpNail(true), m_IsOptional(true), m_NodeModifiedObserverTag(0), m_NodeObserved(false), m_DataMTime(0), m_SelectionPropMTime(0)
{ }

QmitkNodeSelectionButton::~QmitkNodeSelectionButton()
{
  this->RemoveNodeObserver();
  this->m_SelectedNode = nullptr;
}

void QmitkNodeSelectionButton::AddNodeObserver()
{
  if (this->m_SelectedNode.IsNotNull())
  {
    if (m_NodeObserved)
    {
      MITK_DEBUG << "Invalid observer state in QmitkNodeSelectionButton. There is already a registered observer. Internal logic is not correct. May be an old observer was not removed.";
    }

    auto modifiedCommand = itk::MemberCommand<QmitkNodeSelectionButton>::New();
    modifiedCommand->SetCallbackFunction(this, &QmitkNodeSelectionButton::OnNodeModified);

    // const cast because we need non const nodes and it seems to be the lesser of two evil.
    // the changes to the node are only on the observer level. The other option would be to
    // make the public interface require non const nodes, this we don't want to introduce.
    auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
    m_NodeModifiedObserverTag = nonconst_node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
    m_NodeObserved = true;
  }
}

void QmitkNodeSelectionButton::RemoveNodeObserver()
{
  if (this->m_SelectedNode.IsNotNull())
  {
    // const cast because we need non const nodes and it seems to be the lesser of two evil.
    // the changes to the node are only on the observer level. The other option would be to
    // make the public interface require non const nodes, this we don't want to introduce.
    auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
    nonconst_node->RemoveObserver(m_NodeModifiedObserverTag);
  }
  m_NodeObserved = false;
}

itk::ModifiedTimeType GetSelectedPropMTime(const mitk::DataNode* node)
{
  itk::ModifiedTimeType propMTime = 0;
  if (node)
  {
    auto prop = node->GetProperty("selected", nullptr, false);
    if (prop)
    {
      propMTime = prop->GetMTime();
    }
  }
  return propMTime;
}

void QmitkNodeSelectionButton::OnNodeModified(const itk::Object * /*caller*/, const itk::EventObject & event)
{
  if (itk::ModifiedEvent().CheckEvent(&event))
  {
    auto propMTime = GetSelectedPropMTime(this->m_SelectedNode);
    /*this check is introduced because of T27069. If the afformentioned issue is fixed,
      this check can also be removed.*/
    if (propMTime == this->m_SelectionPropMTime)
    {
      this->repaint();
    }

    this->m_SelectionPropMTime = propMTime;
  }
}

const mitk::DataNode* QmitkNodeSelectionButton::GetSelectedNode() const
{
  return m_SelectedNode;
}

void QmitkNodeSelectionButton::SetSelectedNode(const mitk::DataNode* node)
{
  if (m_SelectedNode != node)
  {
    this->RemoveNodeObserver();
    this->m_SelectedNode = node;
    this->m_OutDatedThumpNail = true;
    this->m_SelectionPropMTime = GetSelectedPropMTime(node);
    this->AddNodeObserver();
  }

  this->update();
}

void QmitkNodeSelectionButton::SetNodeInfo(QString info)
{
  this->m_Info = info;
  this->update();
}

void QmitkNodeSelectionButton::paintEvent(QPaintEvent *p)
{
  QString stylesheet;

  ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
  ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
  if (styleManagerRef)
  {
    auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
    stylesheet = styleManager->GetStylesheet();
  }

  QPushButton::paintEvent(p);

  QPainter painter(this);
  QTextDocument td(this);
  td.setDefaultStyleSheet(stylesheet);

  auto widgetSize = this->size();
  QPoint origin = QPoint(5, 5);

  if (this->m_SelectedNode)
  {
    auto iconLength = widgetSize.height() - 10;
    auto node = this->m_SelectedNode;

    itk::ModifiedTimeType dataMTime = 0;
    if (m_SelectedNode->GetData())
    {
      dataMTime = m_SelectedNode->GetData()->GetMTime();
    }
    if (dataMTime>m_DataMTime || this->m_OutDatedThumpNail)
    {
      this->m_ThumpNail = GetPixmapFromImageNode(node, iconLength);
      this->m_OutDatedThumpNail = false;
      m_DataMTime = dataMTime;
    }

    painter.drawPixmap(origin, m_ThumpNail);
    origin.setX(origin.x() + iconLength + 5);

    if (this->isEnabled())
    {
      td.setHtml(QString::fromStdString("" + node->GetName() + ""));
    }
    else
    {
      td.setHtml(QString::fromStdString("" + node->GetName() + ""));
    }
  }
  else
  {
    if (this->isEnabled())
    {
      if (this->m_IsOptional)
      {
        td.setHtml(QString("") + m_Info + QString(""));
      }
      else
      {
        td.setHtml(QString("") + m_Info + QString(""));
      }
    }
    else
    {
      td.setHtml(QString("") + m_Info + QString(""));
    }
  }

  auto textSize = td.size();

  origin.setY( (widgetSize.height() - textSize.height()) / 2.);

  painter.translate(origin);
  td.drawContents(&painter);
}

void QmitkNodeSelectionButton::changeEvent(QEvent *event)
{
  if (event->type() == QEvent::EnabledChange)
  {
    this->repaint();
  }
}

bool QmitkNodeSelectionButton::GetSelectionIsOptional() const
{
  return m_IsOptional;
}

void QmitkNodeSelectionButton::SetSelectionIsOptional(bool isOptional)
{
  m_IsOptional = isOptional;
  this->repaint();
}
<commit_msg>Fixed gcc compiler errors<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

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

#include "QmitkNodeSelectionButton.h"

// berry includes
#include <berryWorkbenchPlugin.h>
#include <berryQtStyleManager.h>

#include "QPainter"
#include "QTextDocument"
#include "QEvent"

#include <mitkDataNode.h>
#include <QmitkNodeDescriptorManager.h>

// mitk core
#include <mitkBaseRenderer.h>
#include <mitkDataNode.h>
#include <mitkExtractSliceFilter.h>
#include <vtkMitkLevelWindowFilter.h>
#include <mitkPlanarFigure.h>
#include <mitkPropertyNameHelper.h>

// vtk
#include <vtkLookupTable.h>

QPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode, int height)
{
  if (nullptr == dataNode)
  {
    return QPixmap();
  }

  const mitk::Image* image = dynamic_cast<const mitk::Image*>(dataNode->GetData());
  if ((nullptr == image || !image->IsInitialized()) || // -> must be an image
    (image->GetPixelType().GetNumberOfComponents() != 1)) // -> for now only single component are allowed
  {
    auto descManager = QmitkNodeDescriptorManager::GetInstance();
    auto desc = descManager->GetDescriptor(dataNode);
    auto icon = desc->GetIcon(dataNode);
    auto fallBackMap = icon.pixmap(height, height);
    return fallBackMap;
  }

  mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
  int sliceNumber = image->GetDimension(2) / 2;
  planeGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::PlaneGeometry::Axial, sliceNumber);

  mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();
  extractSliceFilter->SetInput(image);
  extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);
  extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());
  extractSliceFilter->SetWorldGeometry(planeGeometry);
  extractSliceFilter->SetOutputDimensionality(2);
  extractSliceFilter->SetVtkOutputRequest(true);
  extractSliceFilter->Update();

  vtkImageData* imageData = extractSliceFilter->GetVtkOutput();

  mitk::LevelWindow levelWindow;
  dataNode->GetLevelWindow(levelWindow);
  vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();
  lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());
  lookupTable->SetSaturationRange(0.0, 0.0);
  lookupTable->SetValueRange(0.0, 1.0);
  lookupTable->SetHueRange(0.0, 0.0);
  lookupTable->SetRampToLinear();

  vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();
  levelWindowFilter->SetLookupTable(lookupTable);
  levelWindowFilter->SetInputData(imageData);
  levelWindowFilter->SetMinOpacity(0.0);
  levelWindowFilter->SetMaxOpacity(1.0);
  int dims[3];
  imageData->GetDimensions(dims);
  double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };
  levelWindowFilter->SetClippingBounds(clippingBounds);
  levelWindowFilter->Update();
  imageData = levelWindowFilter->GetOutput();

  QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);

  thumbnailImage = thumbnailImage.scaledToHeight(height,Qt::SmoothTransformation).rgbSwapped();
  return QPixmap::fromImage(thumbnailImage);
}

QmitkNodeSelectionButton::QmitkNodeSelectionButton(QWidget *parent)
  : QPushButton(parent), m_OutDatedThumpNail(true), m_DataMTime(0), m_SelectionPropMTime(0), m_IsOptional(true), m_NodeModifiedObserverTag(0), m_NodeObserved(false)
{ }

QmitkNodeSelectionButton::~QmitkNodeSelectionButton()
{
  this->RemoveNodeObserver();
  this->m_SelectedNode = nullptr;
}

void QmitkNodeSelectionButton::AddNodeObserver()
{
  if (this->m_SelectedNode.IsNotNull())
  {
    if (m_NodeObserved)
    {
      MITK_DEBUG << "Invalid observer state in QmitkNodeSelectionButton. There is already a registered observer. Internal logic is not correct. May be an old observer was not removed.";
    }

    auto modifiedCommand = itk::MemberCommand<QmitkNodeSelectionButton>::New();
    modifiedCommand->SetCallbackFunction(this, &QmitkNodeSelectionButton::OnNodeModified);

    // const cast because we need non const nodes and it seems to be the lesser of two evil.
    // the changes to the node are only on the observer level. The other option would be to
    // make the public interface require non const nodes, this we don't want to introduce.
    auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
    m_NodeModifiedObserverTag = nonconst_node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
    m_NodeObserved = true;
  }
}

void QmitkNodeSelectionButton::RemoveNodeObserver()
{
  if (this->m_SelectedNode.IsNotNull())
  {
    // const cast because we need non const nodes and it seems to be the lesser of two evil.
    // the changes to the node are only on the observer level. The other option would be to
    // make the public interface require non const nodes, this we don't want to introduce.
    auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
    nonconst_node->RemoveObserver(m_NodeModifiedObserverTag);
  }
  m_NodeObserved = false;
}

itk::ModifiedTimeType GetSelectedPropMTime(const mitk::DataNode* node)
{
  itk::ModifiedTimeType propMTime = 0;
  if (node)
  {
    auto prop = node->GetProperty("selected", nullptr, false);
    if (prop)
    {
      propMTime = prop->GetMTime();
    }
  }
  return propMTime;
}

void QmitkNodeSelectionButton::OnNodeModified(const itk::Object * /*caller*/, const itk::EventObject & event)
{
  if (itk::ModifiedEvent().CheckEvent(&event))
  {
    auto propMTime = GetSelectedPropMTime(this->m_SelectedNode);
    /*this check is introduced because of T27069. If the afformentioned issue is fixed,
      this check can also be removed.*/
    if (propMTime == this->m_SelectionPropMTime)
    {
      this->repaint();
    }

    this->m_SelectionPropMTime = propMTime;
  }
}

const mitk::DataNode* QmitkNodeSelectionButton::GetSelectedNode() const
{
  return m_SelectedNode;
}

void QmitkNodeSelectionButton::SetSelectedNode(const mitk::DataNode* node)
{
  if (m_SelectedNode != node)
  {
    this->RemoveNodeObserver();
    this->m_SelectedNode = node;
    this->m_OutDatedThumpNail = true;
    this->m_SelectionPropMTime = GetSelectedPropMTime(node);
    this->AddNodeObserver();
  }

  this->update();
}

void QmitkNodeSelectionButton::SetNodeInfo(QString info)
{
  this->m_Info = info;
  this->update();
}

void QmitkNodeSelectionButton::paintEvent(QPaintEvent *p)
{
  QString stylesheet;

  ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
  ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
  if (styleManagerRef)
  {
    auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
    stylesheet = styleManager->GetStylesheet();
  }

  QPushButton::paintEvent(p);

  QPainter painter(this);
  QTextDocument td(this);
  td.setDefaultStyleSheet(stylesheet);

  auto widgetSize = this->size();
  QPoint origin = QPoint(5, 5);

  if (this->m_SelectedNode)
  {
    auto iconLength = widgetSize.height() - 10;
    auto node = this->m_SelectedNode;

    itk::ModifiedTimeType dataMTime = 0;
    if (m_SelectedNode->GetData())
    {
      dataMTime = m_SelectedNode->GetData()->GetMTime();
    }
    if (dataMTime>m_DataMTime || this->m_OutDatedThumpNail)
    {
      this->m_ThumpNail = GetPixmapFromImageNode(node, iconLength);
      this->m_OutDatedThumpNail = false;
      m_DataMTime = dataMTime;
    }

    painter.drawPixmap(origin, m_ThumpNail);
    origin.setX(origin.x() + iconLength + 5);

    if (this->isEnabled())
    {
      td.setHtml(QString::fromStdString("" + node->GetName() + ""));
    }
    else
    {
      td.setHtml(QString::fromStdString("" + node->GetName() + ""));
    }
  }
  else
  {
    if (this->isEnabled())
    {
      if (this->m_IsOptional)
      {
        td.setHtml(QString("") + m_Info + QString(""));
      }
      else
      {
        td.setHtml(QString("") + m_Info + QString(""));
      }
    }
    else
    {
      td.setHtml(QString("") + m_Info + QString(""));
    }
  }

  auto textSize = td.size();

  origin.setY( (widgetSize.height() - textSize.height()) / 2.);

  painter.translate(origin);
  td.drawContents(&painter);
}

void QmitkNodeSelectionButton::changeEvent(QEvent *event)
{
  if (event->type() == QEvent::EnabledChange)
  {
    this->repaint();
  }
}

bool QmitkNodeSelectionButton::GetSelectionIsOptional() const
{
  return m_IsOptional;
}

void QmitkNodeSelectionButton::SetSelectionIsOptional(bool isOptional)
{
  m_IsOptional = isOptional;
  this->repaint();
}
<|endoftext|>


<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <string>
#include <memory>

#include "base/scoped_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_policy.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/tests/common/controller.h"

namespace {

// The next 2 functions are copied from base\string_util.h and have been
// slighty modified because we don't want to depend on ICU.
template <class char_type>
inline char_type* WriteInto(
    std::basic_string<char_type, std::char_traits<char_type>,
                      std::allocator<char_type> >* str,
    size_t length_including_null) {
  str->reserve(length_including_null);
  str->resize(length_including_null - 1);
  return &((*str)[0]);
}

std::string WideToMultiByte(const std::wstring& wide) {
  if (wide.length() == 0)
    return std::string();

  // compute the length of the buffer we'll need
  int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
                                      NULL, 0, NULL, NULL);
  if (charcount == 0)
    return std::string();

  std::string mb;
  WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
                      WriteInto(&mb, charcount), charcount, NULL, NULL);

  return mb;
}

// While the shell API provides better calls than this home brew function
// we use GetSystemWindowsDirectoryW which does not query the registry so
// it is safe to use after revert.
std::wstring MakeFullPathToSystem32(const wchar_t* name) {
  wchar_t windows_path[MAX_PATH] = {0};
  ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);
  std::wstring full_path(windows_path);
  if (full_path.empty()) {
    return full_path;
  }
  full_path += L"\\system32\\";
  full_path += name;
  return full_path;
}

// Creates a process with the |exe| and |command| parameter using the
// unicode and ascii version of the api.
sandbox::SboxTestResult CreateProcessHelper(const std::wstring &exe,
                                            const std::wstring &command) {
  PROCESS_INFORMATION pi;
  STARTUPINFOW si = {sizeof(si)};

  wchar_t *exe_name = NULL;
  if (!exe.empty())
    exe_name = const_cast<wchar_t*>(exe.c_str());

  wchar_t *cmd_line = NULL;
  if (!command.empty())
    cmd_line = const_cast<wchar_t*>(command.c_str());

  // Create the process with the unicode version of the API.
  sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;
  if (!::CreateProcessW(exe_name, cmd_line, NULL, NULL, FALSE, 0, NULL,
                        NULL, &si, &pi)) {
    DWORD last_error = GetLastError();
    if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
        (ERROR_ACCESS_DENIED == last_error) ||
        (ERROR_FILE_NOT_FOUND == last_error)) {
      ret1 = sandbox::SBOX_TEST_DENIED;
    } else {
      ret1 = sandbox::SBOX_TEST_FAILED;
    }
  } else {
    ret1 = sandbox::SBOX_TEST_SUCCEEDED;
  }

  // Do the same with the ansi version of the api
  STARTUPINFOA sia = {sizeof(sia)};
  sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;

  if (!::CreateProcessA(
        exe_name ? WideToMultiByte(exe_name).c_str() : NULL,
        cmd_line ? const_cast<char*>(WideToMultiByte(cmd_line).c_str()) : NULL,
        NULL, NULL, FALSE, 0, NULL, NULL, &sia, &pi)) {
    DWORD last_error = GetLastError();
    if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
        (ERROR_ACCESS_DENIED == last_error) ||
        (ERROR_FILE_NOT_FOUND == last_error)) {
      ret2 = sandbox::SBOX_TEST_DENIED;
    } else {
      ret2 = sandbox::SBOX_TEST_FAILED;
    }
  } else {
    ret2 = sandbox::SBOX_TEST_SUCCEEDED;
  }

  if (ret1 == ret2)
    return ret1;

  return sandbox::SBOX_TEST_FAILED;
}

}  // namespace

namespace sandbox {

// Tries to create the process in argv[0] using 7 different ways.
// Since we also try the Ansi and Unicode version of the CreateProcess API,
// The process referenced by argv[0] will be spawned 14 times.
SBOX_TESTS_COMMAND int Process_RunApp(int argc, wchar_t **argv) {
  if (argc != 1) {
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
  }
  if ((NULL != argv) && (NULL == argv[0])) {
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
  }
  std::wstring path = MakeFullPathToSystem32(argv[0]);

  // TEST 1: Try with the path in the app_name.
  int result1 = CreateProcessHelper(path, std::wstring());

  // TEST 2: Try with the path in the cmd_line.
  std::wstring cmd_line = L"\"";
  cmd_line += path;
  cmd_line += L"\"";
  int result2 = CreateProcessHelper(std::wstring(), cmd_line);

  // TEST 3: Try file name in the cmd_line.
  int result3 = CreateProcessHelper(std::wstring(), argv[0]);

  // TEST 4: Try file name in the app_name and current directory sets correctly.
  std::wstring system32 = MakeFullPathToSystem32(L"");
  wchar_t current_directory[MAX_PATH + 1];
  int result4;
  bool test_succeeded = false;
  DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
  if (0 != ret && ret < MAX_PATH) {
    current_directory[ret] = L'\\';
    current_directory[ret+1] = L'\0';
    if (::SetCurrentDirectory(system32.c_str())) {
      result4 = CreateProcessHelper(argv[0], std::wstring());
      if (::SetCurrentDirectory(current_directory)) {
        test_succeeded = true;
      }
    }
  }
  if (!test_succeeded)
    result4 = SBOX_TEST_FAILED;

  // TEST 5: Try with the path in the cmd_line and arguments.
  cmd_line = L"\"";
  cmd_line += path;
  cmd_line += L"\" /INSERT";
  int result5 = CreateProcessHelper(std::wstring(), cmd_line);

  // TEST 6: Try with the file_name in the cmd_line and arguments.
  cmd_line = argv[0];
  cmd_line += L" /INSERT";
  int result6 = CreateProcessHelper(std::wstring(), cmd_line);

  // TEST 7: Try with the path without the drive.
  cmd_line = path.substr(path.find(L'\\'));
  int result7 = CreateProcessHelper(std::wstring(), cmd_line);

  // Check if they all returned the same thing.
  if ((result1 == result2) && (result2 == result3) && (result3 == result4) &&
      (result4 == result5) && (result5 == result6) && (result6 == result7))
    return result1;

  return SBOX_TEST_FAILED;
}

// Creates a process and checks if it's possible to get a handle to it's token.
SBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {
  if (argc != 1)
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;

  if ((NULL != argv) && (NULL == argv[0]))
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;

  std::wstring path = MakeFullPathToSystem32(argv[0]);

  PROCESS_INFORMATION pi = {0};
  STARTUPINFOW si = {sizeof(si)};

  if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,
                        NULL, NULL, &si, &pi)) {
      return SBOX_TEST_FAILED;
  }

  ScopedHandle process(pi.hProcess);
  ScopedHandle thread(pi.hThread);

  HANDLE token = NULL;
  BOOL result = ::OpenProcessToken(process.Get(), TOKEN_IMPERSONATE, &token);
  DWORD error = ::GetLastError();

  ScopedHandle token_handle(token);

  if (!::TerminateProcess(process.Get(), 0))
    return SBOX_TEST_FAILED;

  if (result && token)
    return SBOX_TEST_SUCCEEDED;

  if (ERROR_ACCESS_DENIED == error)
    return SBOX_TEST_DENIED;

  return SBOX_TEST_FAILED;
}

SBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {
  HANDLE token;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
    if (ERROR_ACCESS_DENIED == ::GetLastError()) {
      return SBOX_TEST_DENIED;
    }
  } else {
    ::CloseHandle(token);
    return SBOX_TEST_SUCCEEDED;
  }

  return SBOX_TEST_FAILED;
}

TEST(ProcessPolicyTest, TestAllAccess) {
  // Check if the "all access" rule fails to be added when the token is too
  // powerful.
  TestRunner runner;

  // Check the failing case.
  runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
  EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,
            runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
                                        TargetPolicy::PROCESS_ALL_EXEC,
                                        L"this is not important"));

  // Check the working case.
  runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);

  EXPECT_EQ(SBOX_ALL_OK,
            runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
                                        TargetPolicy::PROCESS_ALL_EXEC,
                                        L"this is not important"));
}

TEST(ProcessPolicyTest, RunFindstrExe) {
  TestRunner runner;
  std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
  std::wstring system32 = MakeFullPathToSystem32(L"");
  ASSERT_TRUE(!exe_path.empty());
  EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
                             TargetPolicy::PROCESS_MIN_EXEC,
                             exe_path.c_str()));

  // Need to add directory rules for the directories that we use in
  // SetCurrentDirectory.
  EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
                               system32.c_str()));

  wchar_t current_directory[MAX_PATH];
  DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
  ASSERT_TRUE(0 != ret && ret < MAX_PATH);

  wcscat_s(current_directory, MAX_PATH, L"\\");
  EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
                               current_directory));

  EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_RunApp findstr.exe"));
  EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp calc.exe"));
}

TEST(ProcessPolicyTest, OpenToken) {
  TestRunner runner;
  EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_OpenToken"));
}

TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {
  TestRunner runner;
  std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
  ASSERT_TRUE(!exe_path.empty());
  EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
                             TargetPolicy::PROCESS_MIN_EXEC,
                             exe_path.c_str()));

  EXPECT_EQ(SBOX_TEST_DENIED,
            runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}

TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {
  TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);
  std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
  ASSERT_TRUE(!exe_path.empty());
  EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
                             TargetPolicy::PROCESS_ALL_EXEC,
                             exe_path.c_str()));

  EXPECT_EQ(SBOX_TEST_SUCCEEDED,
            runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}

}  // namespace sandbox
<commit_msg>Disable ProcessPolicyTest.RunFindstrExe until it can be made to work on any Windows drive. B=1305476 R=nsylvain<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <string>
#include <memory>

#include "base/scoped_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_policy.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/tests/common/controller.h"

namespace {

// The next 2 functions are copied from base\string_util.h and have been
// slighty modified because we don't want to depend on ICU.
template <class char_type>
inline char_type* WriteInto(
    std::basic_string<char_type, std::char_traits<char_type>,
                      std::allocator<char_type> >* str,
    size_t length_including_null) {
  str->reserve(length_including_null);
  str->resize(length_including_null - 1);
  return &((*str)[0]);
}

std::string WideToMultiByte(const std::wstring& wide) {
  if (wide.length() == 0)
    return std::string();

  // compute the length of the buffer we'll need
  int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
                                      NULL, 0, NULL, NULL);
  if (charcount == 0)
    return std::string();

  std::string mb;
  WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
                      WriteInto(&mb, charcount), charcount, NULL, NULL);

  return mb;
}

// While the shell API provides better calls than this home brew function
// we use GetSystemWindowsDirectoryW which does not query the registry so
// it is safe to use after revert.
std::wstring MakeFullPathToSystem32(const wchar_t* name) {
  wchar_t windows_path[MAX_PATH] = {0};
  ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);
  std::wstring full_path(windows_path);
  if (full_path.empty()) {
    return full_path;
  }
  full_path += L"\\system32\\";
  full_path += name;
  return full_path;
}

// Creates a process with the |exe| and |command| parameter using the
// unicode and ascii version of the api.
sandbox::SboxTestResult CreateProcessHelper(const std::wstring &exe,
                                            const std::wstring &command) {
  PROCESS_INFORMATION pi;
  STARTUPINFOW si = {sizeof(si)};

  wchar_t *exe_name = NULL;
  if (!exe.empty())
    exe_name = const_cast<wchar_t*>(exe.c_str());

  wchar_t *cmd_line = NULL;
  if (!command.empty())
    cmd_line = const_cast<wchar_t*>(command.c_str());

  // Create the process with the unicode version of the API.
  sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;
  if (!::CreateProcessW(exe_name, cmd_line, NULL, NULL, FALSE, 0, NULL,
                        NULL, &si, &pi)) {
    DWORD last_error = GetLastError();
    if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
        (ERROR_ACCESS_DENIED == last_error) ||
        (ERROR_FILE_NOT_FOUND == last_error)) {
      ret1 = sandbox::SBOX_TEST_DENIED;
    } else {
      ret1 = sandbox::SBOX_TEST_FAILED;
    }
  } else {
    ret1 = sandbox::SBOX_TEST_SUCCEEDED;
  }

  // Do the same with the ansi version of the api
  STARTUPINFOA sia = {sizeof(sia)};
  sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;

  if (!::CreateProcessA(
        exe_name ? WideToMultiByte(exe_name).c_str() : NULL,
        cmd_line ? const_cast<char*>(WideToMultiByte(cmd_line).c_str()) : NULL,
        NULL, NULL, FALSE, 0, NULL, NULL, &sia, &pi)) {
    DWORD last_error = GetLastError();
    if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
        (ERROR_ACCESS_DENIED == last_error) ||
        (ERROR_FILE_NOT_FOUND == last_error)) {
      ret2 = sandbox::SBOX_TEST_DENIED;
    } else {
      ret2 = sandbox::SBOX_TEST_FAILED;
    }
  } else {
    ret2 = sandbox::SBOX_TEST_SUCCEEDED;
  }

  if (ret1 == ret2)
    return ret1;

  return sandbox::SBOX_TEST_FAILED;
}

}  // namespace

namespace sandbox {

// Tries to create the process in argv[0] using 7 different ways.
// Since we also try the Ansi and Unicode version of the CreateProcess API,
// The process referenced by argv[0] will be spawned 14 times.
SBOX_TESTS_COMMAND int Process_RunApp(int argc, wchar_t **argv) {
  if (argc != 1) {
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
  }
  if ((NULL != argv) && (NULL == argv[0])) {
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
  }
  std::wstring path = MakeFullPathToSystem32(argv[0]);

  // TEST 1: Try with the path in the app_name.
  int result1 = CreateProcessHelper(path, std::wstring());

  // TEST 2: Try with the path in the cmd_line.
  std::wstring cmd_line = L"\"";
  cmd_line += path;
  cmd_line += L"\"";
  int result2 = CreateProcessHelper(std::wstring(), cmd_line);

  // TEST 3: Try file name in the cmd_line.
  int result3 = CreateProcessHelper(std::wstring(), argv[0]);

  // TEST 4: Try file name in the app_name and current directory sets correctly.
  std::wstring system32 = MakeFullPathToSystem32(L"");
  wchar_t current_directory[MAX_PATH + 1];
  int result4;
  bool test_succeeded = false;
  DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
  if (0 != ret && ret < MAX_PATH) {
    current_directory[ret] = L'\\';
    current_directory[ret+1] = L'\0';
    if (::SetCurrentDirectory(system32.c_str())) {
      result4 = CreateProcessHelper(argv[0], std::wstring());
      if (::SetCurrentDirectory(current_directory)) {
        test_succeeded = true;
      }
    }
  }
  if (!test_succeeded)
    result4 = SBOX_TEST_FAILED;

  // TEST 5: Try with the path in the cmd_line and arguments.
  cmd_line = L"\"";
  cmd_line += path;
  cmd_line += L"\" /INSERT";
  int result5 = CreateProcessHelper(std::wstring(), cmd_line);

  // TEST 6: Try with the file_name in the cmd_line and arguments.
  cmd_line = argv[0];
  cmd_line += L" /INSERT";
  int result6 = CreateProcessHelper(std::wstring(), cmd_line);

  // TEST 7: Try with the path without the drive.
  cmd_line = path.substr(path.find(L'\\'));
  int result7 = CreateProcessHelper(std::wstring(), cmd_line);

  // Check if they all returned the same thing.
  if ((result1 == result2) && (result2 == result3) && (result3 == result4) &&
      (result4 == result5) && (result5 == result6) && (result6 == result7))
    return result1;

  return SBOX_TEST_FAILED;
}

// Creates a process and checks if it's possible to get a handle to it's token.
SBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {
  if (argc != 1)
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;

  if ((NULL != argv) && (NULL == argv[0]))
    return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;

  std::wstring path = MakeFullPathToSystem32(argv[0]);

  PROCESS_INFORMATION pi = {0};
  STARTUPINFOW si = {sizeof(si)};

  if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,
                        NULL, NULL, &si, &pi)) {
      return SBOX_TEST_FAILED;
  }

  ScopedHandle process(pi.hProcess);
  ScopedHandle thread(pi.hThread);

  HANDLE token = NULL;
  BOOL result = ::OpenProcessToken(process.Get(), TOKEN_IMPERSONATE, &token);
  DWORD error = ::GetLastError();

  ScopedHandle token_handle(token);

  if (!::TerminateProcess(process.Get(), 0))
    return SBOX_TEST_FAILED;

  if (result && token)
    return SBOX_TEST_SUCCEEDED;

  if (ERROR_ACCESS_DENIED == error)
    return SBOX_TEST_DENIED;

  return SBOX_TEST_FAILED;
}

SBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {
  HANDLE token;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
    if (ERROR_ACCESS_DENIED == ::GetLastError()) {
      return SBOX_TEST_DENIED;
    }
  } else {
    ::CloseHandle(token);
    return SBOX_TEST_SUCCEEDED;
  }

  return SBOX_TEST_FAILED;
}

TEST(ProcessPolicyTest, TestAllAccess) {
  // Check if the "all access" rule fails to be added when the token is too
  // powerful.
  TestRunner runner;

  // Check the failing case.
  runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
  EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,
            runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
                                        TargetPolicy::PROCESS_ALL_EXEC,
                                        L"this is not important"));

  // Check the working case.
  runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);

  EXPECT_EQ(SBOX_ALL_OK,
            runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
                                        TargetPolicy::PROCESS_ALL_EXEC,
                                        L"this is not important"));
}

// This test is disabled.  See bug 1305476.
TEST(ProcessPolicyTest, DISABLED_RunFindstrExe) {
  TestRunner runner;
  std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
  std::wstring system32 = MakeFullPathToSystem32(L"");
  ASSERT_TRUE(!exe_path.empty());
  EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
                             TargetPolicy::PROCESS_MIN_EXEC,
                             exe_path.c_str()));

  // Need to add directory rules for the directories that we use in
  // SetCurrentDirectory.
  EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
                               system32.c_str()));

  wchar_t current_directory[MAX_PATH];
  DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
  ASSERT_TRUE(0 != ret && ret < MAX_PATH);

  wcscat_s(current_directory, MAX_PATH, L"\\");
  EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
                               current_directory));

  EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_RunApp findstr.exe"));
  EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp calc.exe"));
}

TEST(ProcessPolicyTest, OpenToken) {
  TestRunner runner;
  EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_OpenToken"));
}

TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {
  TestRunner runner;
  std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
  ASSERT_TRUE(!exe_path.empty());
  EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
                             TargetPolicy::PROCESS_MIN_EXEC,
                             exe_path.c_str()));

  EXPECT_EQ(SBOX_TEST_DENIED,
            runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}

TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {
  TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);
  std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
  ASSERT_TRUE(!exe_path.empty());
  EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
                             TargetPolicy::PROCESS_ALL_EXEC,
                             exe_path.c_str()));

  EXPECT_EQ(SBOX_TEST_SUCCEEDED,
            runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}

}  // namespace sandbox
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: SlsPageObjectViewContact.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "view/SlsPageObjectViewContact.hxx"

#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"

#include <svx/svdopage.hxx>
#include <tools/debug.hxx>

using namespace ::sdr::contact;

namespace sd { namespace slidesorter { namespace view {

PageObjectViewContact::PageObjectViewContact (
    SdrPageObj& rPageObj,
    const model::SharedPageDescriptor& rpDescriptor)
    : ViewContactOfPageObj (rPageObj),
      mbIsValid(true),
      mpDescriptor(rpDescriptor)
{
}

PageObjectViewContact::~PageObjectViewContact (void)
{
}

ViewObjectContact&
    PageObjectViewContact::CreateObjectSpecificViewObjectContact(
        ObjectContact& rObjectContact)
{
    OSL_ASSERT(mpDescriptor.get()!=NULL);

    ViewObjectContact* pResult
        = mpDescriptor->GetPageObjectFactory().CreateViewObjectContact (
            rObjectContact,
            *this);
    DBG_ASSERT (pResult!=NULL,
        "PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
    return *pResult;
}

const SdrPage* PageObjectViewContact::GetPage (void) const
{
    if (mbIsValid)
        return GetReferencedPage();
    else
        return NULL;
}

void PageObjectViewContact::CalcPaintRectangle (void)
{
    ViewContactOfPageObj::CalcPaintRectangle();
    if (mbIsValid)
    {
        OSL_ASSERT(mpDescriptor.get()!=NULL);

        maPageObjectBoundingBox = maPaintRectangle;
        SvBorder aBorder (mpDescriptor->GetModelBorder());
        maPaintRectangle.Left() -= aBorder.Left();
        maPaintRectangle.Right() += aBorder.Right();
        maPaintRectangle.Top() -= aBorder.Top();
        maPaintRectangle.Bottom() += aBorder.Bottom();
    }
}

Rectangle PageObjectViewContact::GetPageRectangle (void)
{
    return GetPageObj().GetCurrentBoundRect();
}

void PageObjectViewContact::ActionChanged (void)
{
    ViewContactOfPageObj::ActionChanged();
}

Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
    return maPageObjectBoundingBox;
}

SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
    return ViewContactOfPageObj::GetPageObj();
}

void PageObjectViewContact::PrepareDelete (void)
{
    mbIsValid = false;
}

} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS aw033 (1.7.46); FILE MERGED 2008/07/10 12:56:27 aw 1.7.46.7: #i39532# XOutputDevice removed, PrepareDelete removed 2008/06/24 15:34:31 aw 1.7.46.6: #i39532# corrections 2008/05/27 15:18:03 aw 1.7.46.5: #i39532# changes DEV300 m12 resync corrections 2008/05/16 13:06:05 aw 1.7.46.4: adaptions after resync 2008/05/14 14:51:19 aw 1.7.46.3: RESYNC: (1.7-1.9); FILE MERGED 2008/01/29 10:34:21 aw 1.7.46.2: updated refresh for ActionChanged(), diverse removals 2008/01/22 12:16:42 aw 1.7.46.1: adaptions and 1st stripping<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: SlsPageObjectViewContact.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "view/SlsPageObjectViewContact.hxx"

#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"

#include <svx/svdopage.hxx>
#include <tools/debug.hxx>

#include <basegfx/polygon/b2dpolygontools.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>

using namespace ::sdr::contact;

namespace sd { namespace slidesorter { namespace view {

PageObjectViewContact::PageObjectViewContact (
    SdrPageObj& rPageObj,
    const model::SharedPageDescriptor& rpDescriptor)
    : ViewContactOfPageObj (rPageObj),
      mbInDestructor(false),
      mpDescriptor(rpDescriptor)
{
}

PageObjectViewContact::~PageObjectViewContact (void)
{
    // remember that this instance is in destruction
    mbInDestructor = true;
}

ViewObjectContact&
    PageObjectViewContact::CreateObjectSpecificViewObjectContact(
        ObjectContact& rObjectContact)
{
    OSL_ASSERT(mpDescriptor.get()!=NULL);

    ViewObjectContact* pResult
        = mpDescriptor->GetPageObjectFactory().CreateViewObjectContact (
            rObjectContact,
            *this);
    DBG_ASSERT (pResult!=NULL,
        "PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
    return *pResult;
}

const SdrPage* PageObjectViewContact::GetPage (void) const
{
    // when this instance itself is in destruction, do no longer
    // provide the referenced page to VOC childs of this OC. This
    // happens e.g. in destructor which destroys all child-VOCs which
    // may in their implementation still reference their VC from
    // their own destructor
    if (!mbInDestructor)
        return GetReferencedPage();
    else
        return NULL;
}

void PageObjectViewContact::ActionChanged (void)
{
    ViewContactOfPageObj::ActionChanged();
}

Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
    // use model data directly here
    OSL_ASSERT(mpDescriptor.get()!=NULL);
    Rectangle aRetval(GetPageObject().GetLastBoundRect());
    const SvBorder aPageDescriptorBorder(mpDescriptor->GetModelBorder());

    aRetval.Left() -= aPageDescriptorBorder.Left();
    aRetval.Top() -= aPageDescriptorBorder.Top();
    aRetval.Right() += aPageDescriptorBorder.Right();
    aRetval.Bottom() += aPageDescriptorBorder.Bottom();

    return aRetval;
}

SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
    return ViewContactOfPageObj::GetPageObj();
}

drawinglayer::primitive2d::Primitive2DSequence PageObjectViewContact::createViewIndependentPrimitive2DSequence() const
{
    // ceate graphical visualisation data. Since this is the view-independent version which should not be used,
    // create a replacement graphic visualisation here. Use GetLastBoundRect to access the model data directly
    // which is aOutRect for SdrPageObj.
    OSL_ASSERT(mpDescriptor.get()!=NULL);
    Rectangle aModelRectangle(GetPageObj().GetLastBoundRect());
    const SvBorder aBorder(mpDescriptor->GetModelBorder());

    aModelRectangle.Left() -= aBorder.Left();
    aModelRectangle.Right() += aBorder.Right();
    aModelRectangle.Top() -= aBorder.Top();
    aModelRectangle.Bottom() += aBorder.Bottom();

    const basegfx::B2DRange aModelRange(aModelRectangle.Left(), aModelRectangle.Top(), aModelRectangle.Right(), aModelRectangle.Bottom());
    const basegfx::B2DPolygon aOutline(basegfx::tools::createPolygonFromRect(aModelRange));
    const basegfx::BColor aYellow(1.0, 1.0, 0.0);
    const drawinglayer::primitive2d::Primitive2DReference xReference(new drawinglayer::primitive2d::PolygonHairlinePrimitive2D(aOutline, aYellow));

    return drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);
}

} } } // end of namespace ::sd::slidesorter::view

// eof
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#undef SC_DLLIMPLEMENTATION

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "shtabdlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"

//==================================================================

ScShowTabDlg::ScShowTabDlg( Window* pParent ) :
    ModalDialog     ( pParent, ScResId( RID_SCDLG_SHOW_TAB ) ),
    aLb             ( this, ScResId( LB_ENTRYLIST ) ),
    aBtnOk          ( this, ScResId( BTN_OK ) ),
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, ScResId( BTN_HELP ) ),
    aFtLbTitle      ( this, ScResId( FT_LABEL ) )
{
    aLb.Clear();
    aLb.SetDoubleClickHdl( LINK( this, ScShowTabDlg, DblClkHdl ) );

    //-------------
    FreeResource();
}

//------------------------------------------------------------------------

void ScShowTabDlg::SetDescription(
        const String& rTitle, const String& rFixedText,
        ULONG nDlgHelpId, ULONG nLbHelpId )
{
    SetText( rTitle );
    aFtLbTitle.SetText( rFixedText );
    // FIXME: HELPID
    SetHelpId( ""/*nDlgHelpId*/ );
    // FIXME: HELPID
    aLb.SetHelpId( ""/*nLbHelpId*/ );
}

void ScShowTabDlg::Insert( const String& rString, BOOL bSelected )
{
    aLb.InsertEntry( rString );
    if( bSelected )
        aLb.SelectEntryPos( aLb.GetEntryCount() - 1 );
}

//------------------------------------------------------------------------

USHORT ScShowTabDlg::GetSelectEntryCount() const
{
    return aLb.GetSelectEntryCount();
}

String ScShowTabDlg::GetSelectEntry(USHORT nPos) const
{
    return aLb.GetSelectEntry(nPos);
}

USHORT ScShowTabDlg::GetSelectEntryPos(USHORT nPos) const
{
    return aLb.GetSelectEntryPos(nPos);
}

//------------------------------------------------------------------------

IMPL_LINK_INLINE_START( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )
{
    EndDialog( RET_OK );
    return 0;
}
IMPL_LINK_INLINE_END( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )

__EXPORT ScShowTabDlg::~ScShowTabDlg()
{
}

<commit_msg>fix warnings<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#undef SC_DLLIMPLEMENTATION

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "shtabdlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"

//==================================================================

ScShowTabDlg::ScShowTabDlg( Window* pParent ) :
    ModalDialog     ( pParent, ScResId( RID_SCDLG_SHOW_TAB ) ),
    aLb             ( this, ScResId( LB_ENTRYLIST ) ),
    aBtnOk          ( this, ScResId( BTN_OK ) ),
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, ScResId( BTN_HELP ) ),
    aFtLbTitle      ( this, ScResId( FT_LABEL ) )
{
    aLb.Clear();
    aLb.SetDoubleClickHdl( LINK( this, ScShowTabDlg, DblClkHdl ) );

    //-------------
    FreeResource();
}

//------------------------------------------------------------------------

void ScShowTabDlg::SetDescription(
        const String& rTitle, const String& rFixedText,
        ULONG nDlgHelpId, ULONG nLbHelpId )
{
    SetText( rTitle );
    aFtLbTitle.SetText( rFixedText );
    // FIXME: HELPID
    SetHelpId( ""/*nDlgHelpId*/ );
    (void)nDlgHelpId;
    // FIXME: HELPID
    aLb.SetHelpId( ""/*nLbHelpId*/ );
    (void)nLbHelpId;
}

void ScShowTabDlg::Insert( const String& rString, BOOL bSelected )
{
    aLb.InsertEntry( rString );
    if( bSelected )
        aLb.SelectEntryPos( aLb.GetEntryCount() - 1 );
}

//------------------------------------------------------------------------

USHORT ScShowTabDlg::GetSelectEntryCount() const
{
    return aLb.GetSelectEntryCount();
}

String ScShowTabDlg::GetSelectEntry(USHORT nPos) const
{
    return aLb.GetSelectEntry(nPos);
}

USHORT ScShowTabDlg::GetSelectEntryPos(USHORT nPos) const
{
    return aLb.GetSelectEntryPos(nPos);
}

//------------------------------------------------------------------------

IMPL_LINK_INLINE_START( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )
{
    EndDialog( RET_OK );
    return 0;
}
IMPL_LINK_INLINE_END( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )

__EXPORT ScShowTabDlg::~ScShowTabDlg()
{
}

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "mitkTestDICOMLoading.h"
#include "mitkTestingMacros.h"

bool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)
{
  MITK_TEST_CONDITION_REQUIRED(list and otherList, "Comparison is passed two non-empty property lists")

  const mitk::PropertyList::PropertyMap* listM = list->GetMap();
  const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();

  bool equal = true;
  for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();
        iter != listM->end();
        ++iter )
  {
    std::string key = iter->first;
    mitk::BaseProperty* property = iter->second;

    mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );
    MITK_TEST_CONDITION( otherEntry != otherListM->end(), "  Property '" << key << "' is contained in other list" )

    mitk::BaseProperty* otherProperty = otherEntry->second;
    MITK_TEST_CONDITION( equal &= (*property == *otherProperty), "  Property '" << key << "' is equal in both list" )
  }

  return equal;
}

bool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)
{
  bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);
  MITK_TEST_CONDITION(allTestPropsInReference, "All test properties found in reference properties")
  bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);
  MITK_TEST_CONDITION(allReferencePropsInTest, "All reference properties found in test properties")
  return allTestPropsInReference && allReferencePropsInTest;
}

int mitkDICOMPreloadedVolumeTest(int argc, char** const argv)
{
  MITK_TEST_BEGIN("DICOMPreloadedVolume")

  mitk::TestDICOMLoading loader;
  mitk::TestDICOMLoading::StringContainer files;

  // adapt expectations depending on configuration
  std::string configuration = mitk::DicomSeriesReader::GetConfigurationString();
  MITK_TEST_OUTPUT(<< "Configuration: " << configuration)

  // load files from commandline
  for (int arg = 1; arg < argc; ++arg)
  {
    MITK_TEST_OUTPUT(<< "Test file " << argv[arg])
    files.push_back( argv[arg] );
  }

  // verify all files are DICOM
  for (mitk::TestDICOMLoading::StringContainer::const_iterator fileIter = files.begin();
       fileIter != files.end();
       ++fileIter)
  {
    MITK_TEST_CONDITION_REQUIRED( mitk::DicomSeriesReader::IsDicom(*fileIter) , *fileIter << " is recognized as loadable DICOM object" )

  }

  // load for a first time
  mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);
  MITK_TEST_OUTPUT(<< "Loaded " << images.size() << " images. Remembering properties of the first one for later comparison.")
  mitk::Image::Pointer firstImage = images.front();

  mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); // save the original
  firstImage->SetPropertyList( mitk::PropertyList::New() ); // clear image properties
  // what about DEFAULT properties? currently ONLY nodes get default properties

  // load for a second time, this time provide the image volume as a pointer
  // expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)
  mitk::TestDICOMLoading::ImageList reloadedImages = loader.LoadFiles(files, firstImage);
  MITK_TEST_OUTPUT(<< "Again loaded " << reloadedImages.size() << " images. Comparing to previously loaded version.")
  mitk::Image::Pointer reloadedImage = reloadedImages.front();

  mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); // get the version of the second load attempt

  bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);
  MITK_TEST_CONDITION(listsAreEqual, "LoadDicomSeries generates a valid property list when provided a pre-loaded image");

  MITK_TEST_END()
}

<commit_msg>COMP: use "&&" instead of "and"<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "mitkTestDICOMLoading.h"
#include "mitkTestingMacros.h"

bool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)
{
  MITK_TEST_CONDITION_REQUIRED(list && otherList, "Comparison is passed two non-empty property lists")

  const mitk::PropertyList::PropertyMap* listM = list->GetMap();
  const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();

  bool equal = true;
  for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();
        iter != listM->end();
        ++iter )
  {
    std::string key = iter->first;
    mitk::BaseProperty* property = iter->second;

    mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );
    MITK_TEST_CONDITION( otherEntry != otherListM->end(), "  Property '" << key << "' is contained in other list" )

    mitk::BaseProperty* otherProperty = otherEntry->second;
    MITK_TEST_CONDITION( equal &= (*property == *otherProperty), "  Property '" << key << "' is equal in both list" )
  }

  return equal;
}

bool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)
{
  bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);
  MITK_TEST_CONDITION(allTestPropsInReference, "All test properties found in reference properties")
  bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);
  MITK_TEST_CONDITION(allReferencePropsInTest, "All reference properties found in test properties")
  return allTestPropsInReference && allReferencePropsInTest;
}

int mitkDICOMPreloadedVolumeTest(int argc, char** const argv)
{
  MITK_TEST_BEGIN("DICOMPreloadedVolume")

  mitk::TestDICOMLoading loader;
  mitk::TestDICOMLoading::StringContainer files;

  // adapt expectations depending on configuration
  std::string configuration = mitk::DicomSeriesReader::GetConfigurationString();
  MITK_TEST_OUTPUT(<< "Configuration: " << configuration)

  // load files from commandline
  for (int arg = 1; arg < argc; ++arg)
  {
    MITK_TEST_OUTPUT(<< "Test file " << argv[arg])
    files.push_back( argv[arg] );
  }

  // verify all files are DICOM
  for (mitk::TestDICOMLoading::StringContainer::const_iterator fileIter = files.begin();
       fileIter != files.end();
       ++fileIter)
  {
    MITK_TEST_CONDITION_REQUIRED( mitk::DicomSeriesReader::IsDicom(*fileIter) , *fileIter << " is recognized as loadable DICOM object" )

  }

  // load for a first time
  mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);
  MITK_TEST_OUTPUT(<< "Loaded " << images.size() << " images. Remembering properties of the first one for later comparison.")
  mitk::Image::Pointer firstImage = images.front();

  mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); // save the original
  firstImage->SetPropertyList( mitk::PropertyList::New() ); // clear image properties
  // what about DEFAULT properties? currently ONLY nodes get default properties

  // load for a second time, this time provide the image volume as a pointer
  // expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)
  mitk::TestDICOMLoading::ImageList reloadedImages = loader.LoadFiles(files, firstImage);
  MITK_TEST_OUTPUT(<< "Again loaded " << reloadedImages.size() << " images. Comparing to previously loaded version.")
  mitk::Image::Pointer reloadedImage = reloadedImages.front();

  mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); // get the version of the second load attempt

  bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);
  MITK_TEST_CONDITION(listsAreEqual, "LoadDicomSeries generates a valid property list when provided a pre-loaded image");

  MITK_TEST_END()
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdint.h>
#include <string>

#include "application_manager/commands/mobile/add_sub_menu_request.h"

#include "gtest/gtest.h"
#include "application_manager/commands/commands_test.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application_manager.h"
#include "application_manager/mock_application.h"
#include "application_manager/mock_message_helper.h"
#include "application_manager/event_engine/event.h"
#include "application_manager/mock_hmi_interface.h"

namespace test {
namespace components {
namespace commands_test {
namespace mobile_commands_test {
namespace add_sub_menu_request {

namespace am = ::application_manager;
using am::commands::AddSubMenuRequest;
using am::commands::MessageSharedPtr;
using am::event_engine::Event;
using ::testing::_;
using ::testing::Return;

typedef SharedPtr<AddSubMenuRequest> AddSubMenuPtr;

namespace {
const uint32_t kConnectionKey = 2u;
}  // namespace

class AddSubMenuRequestTest
    : public CommandRequestTest<CommandsTestMocks::kIsNice> {};

TEST_F(AddSubMenuRequestTest, OnEvent_UI_UNSUPPORTED_RESOURCE) {
  const uint32_t menu_id = 10u;
  MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
  (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
  (*msg)[am::strings::msg_params][am::strings::menu_id] = menu_id;

  utils::SharedPtr<AddSubMenuRequest> command =
      CreateCommand<AddSubMenuRequest>(msg);

  MockAppPtr mock_app = CreateMockApp();
  ON_CALL(app_mngr_, application(kConnectionKey))
      .WillByDefault(Return(mock_app));
  ON_CALL(*mock_app, app_id()).WillByDefault(Return(kConnectionKey));
  EXPECT_CALL(*mock_app, AddSubMenu(menu_id, _));
  EXPECT_CALL(*mock_app, UpdateHash());

  MessageSharedPtr ev_msg = CreateMessage(smart_objects::SmartType_Map);
  (*ev_msg)[am::strings::params][am::hmi_response::code] =
      hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;
  (*ev_msg)[am::strings::msg_params][am::strings::info] = "info";

  Event event(hmi_apis::FunctionID::UI_AddSubMenu);
  event.set_smart_object(*ev_msg);

  MessageSharedPtr ui_command_result;
  EXPECT_CALL(
      app_mngr_,
      ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
      .WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));
  command->Init();
  command->on_event(event);

  EXPECT_EQ((*ui_command_result)[am::strings::msg_params][am::strings::success]
                .asBool(),
            true);
  EXPECT_EQ(
      (*ui_command_result)[am::strings::msg_params][am::strings::result_code]
          .asInt(),
      static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));
  if ((*ui_command_result)[am::strings::msg_params].keyExists(
          am::strings::info)) {
    EXPECT_FALSE(
        (*ui_command_result)[am::strings::msg_params][am::strings::info]
            .asString()
            .empty());
  }
}

}  // namespace add_sub_menu_request
}  // namespace mobile_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace test
<commit_msg>updates for unit test<commit_after>/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdint.h>
#include <string>

#include "application_manager/commands/mobile/add_sub_menu_request.h"

#include "gtest/gtest.h"
#include "application_manager/commands/commands_test.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application_manager.h"
#include "application_manager/mock_application.h"
#include "application_manager/mock_message_helper.h"
#include "application_manager/event_engine/event.h"
#include "application_manager/mock_hmi_interface.h"

namespace test {
namespace components {
namespace commands_test {
namespace mobile_commands_test {
namespace add_sub_menu_request {

namespace am = ::application_manager;
using am::commands::AddSubMenuRequest;
using am::commands::MessageSharedPtr;
using am::event_engine::Event;
using ::testing::_;
using ::testing::Return;

typedef SharedPtr<AddSubMenuRequest> AddSubMenuPtr;

namespace {
const uint32_t kConnectionKey = 2u;
const uint32_t kAppId = 1u;
}  // namespace

class AddSubMenuRequestTest
    : public CommandRequestTest<CommandsTestMocks::kIsNice> {
 public:
  AddSubMenuRequestTest()
      : mock_app(CreateMockApp()) {
      EXPECT_CALL(app_mngr_, application(kConnectionKey))
              .WillRepeatedly(Return(mock_app));
  }

  MockAppPtr mock_app;

  MessageSharedPtr CreateMsgParams() {
        MessageSharedPtr msg = CreateMessage();
        (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
        (*msg)[am::strings::msg_params][am::strings::app_id] = kAppId;
        return msg;
  }
};

TEST_F(AddSubMenuRequestTest, Run_ImageVerificationFailed_EXPECT_INVALID_DATA) {
  const uint32_t menu_id = 10u;
  MessageSharedPtr msg = CreateMsgParams();
  SmartObject& msg_params = (*msg)[am::strings::msg_params];

  msg_params[am::strings::menu_icon] = 1;
  msg_params[am::strings::menu_icon][am::strings::value] = "10";
  msg_params[am::strings::menu_id] = menu_id;
  msg_params[am::strings::menu_name] = "test";
  SmartObject& image = msg_params[am::strings::menu_icon];

  EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _))
  .WillOnce(Return(mobile_apis::Result::INVALID_DATA));
  EXPECT_CALL(app_mngr_,
            ManageMobileCommand(MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _));
  utils::SharedPtr<AddSubMenuRequest> request_ptr =
      CreateCommand<AddSubMenuRequest>(msg);

  request_ptr->Run();
}

TEST_F(AddSubMenuRequestTest, OnEvent_UI_UNSUPPORTED_RESOURCE) {
  const uint32_t menu_id = 10u;
  MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
  (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
  (*msg)[am::strings::msg_params][am::strings::menu_id] = menu_id;

  utils::SharedPtr<AddSubMenuRequest> command =
      CreateCommand<AddSubMenuRequest>(msg);

  ON_CALL(app_mngr_, application(kConnectionKey))
      .WillByDefault(Return(mock_app));
  ON_CALL(*mock_app, app_id()).WillByDefault(Return(kConnectionKey));
  EXPECT_CALL(*mock_app, AddSubMenu(menu_id, _));
  EXPECT_CALL(*mock_app, UpdateHash());

  MessageSharedPtr ev_msg = CreateMessage(smart_objects::SmartType_Map);
  (*ev_msg)[am::strings::params][am::hmi_response::code] =
      hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;
  (*ev_msg)[am::strings::msg_params][am::strings::info] = "info";

  Event event(hmi_apis::FunctionID::UI_AddSubMenu);
  event.set_smart_object(*ev_msg);

  MessageSharedPtr ui_command_result;
  EXPECT_CALL(
      app_mngr_,
      ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
      .WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));
  command->Init();
  command->on_event(event);

  EXPECT_EQ((*ui_command_result)[am::strings::msg_params][am::strings::success]
                .asBool(),
            true);
  EXPECT_EQ(
      (*ui_command_result)[am::strings::msg_params][am::strings::result_code]
          .asInt(),
      static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));
  if ((*ui_command_result)[am::strings::msg_params].keyExists(
          am::strings::info)) {
    EXPECT_FALSE(
        (*ui_command_result)[am::strings::msg_params][am::strings::info]
            .asString()
            .empty());
  }
}

}  // namespace add_sub_menu_request
}  // namespace mobile_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace test
<|endoftext|>