<commit_before>//
// This class is the task for connecting together
// MC information and the RC information
//
// The task is a wrapper over two components
// AliGenInfoMaker
// AliESDRecInfoMaker.h

// ROOT includes
#include <TChain.h>
#include <TMath.h>

// ALIROOT includes
#include <TTreeStream.h>
#include <AliAnalysisManager.h>
#include <AliESDInputHandler.h>
#include "AliStack.h"
#include "AliMCEvent.h"
#include "AliMCEventHandler.h"

#include <AliESD.h>
#include "AliGenInfoTask.h"
#include "AliGenInfoMaker.h"
#include "AliHelix.h"

//
#include "AliMCInfo.h"
#include "AliComparisonObject.h"
#include "AliESDRecInfo.h"
#include "AliTPCParamSR.h"
#include "TSystem.h"
#include "TTimeStamp.h"
#include "TFile.h"
#include "AliTPCseed.h"

// STL includes
#include <iostream>

using namespace std;

ClassImp(AliGenInfoTask)

//________________________________________________________________________
AliGenInfoTask::AliGenInfoTask() :
  AliAnalysisTask(),
  fMCinfo(0),     //! MC event handler
  fESD(0),
  fCompList(0),         //array of comparison objects
  fGenTracksArray(0),  //clones array with filtered particles
  fGenKinkArray(0),    //clones array with filtered Kinks
  fGenV0Array(0),      //clones array with filtered V0s
  fRecTracksArray(0),  //clones array with filtered particles
  fDebugStreamer(0),
  fStreamLevel(0),
  fDebugLevel(0),
  fDebugOutputPath()
{
  //
  // Default constructor (should not be used)
  //
}

AliGenInfoTask::AliGenInfoTask(const AliGenInfoTask& /*info*/) :
  AliAnalysisTask(),
  fMCinfo(0),     //! MC event handler
  fESD(0),
  fCompList(0),
  fGenTracksArray(0),  //clones array with filtered particles
  fGenKinkArray(0),    //clones array with filtered Kinks
  fGenV0Array(0),      //clones array with filtered V0s
  fRecTracksArray(0),  //clones array with filtered particles
  //
  fDebugStreamer(0),
  fStreamLevel(0),
  fDebugLevel(),
  fDebugOutputPath()
{
  //
  // Default constructor
  //
}

//________________________________________________________________________
AliGenInfoTask::AliGenInfoTask(const char *name) :
  AliAnalysisTask(name, "AliGenInfoTask"),
  fMCinfo(0),     //! MC event handler
  fESD(0),
  fCompList(0),
  fGenTracksArray(0),  //clones array with filtered particles
  fGenKinkArray(0),    //clones array with filtered Kinks
  fGenV0Array(0),      //clones array with filtered V0s
  fRecTracksArray(0),  //clones array with filtered particles
  fDebugStreamer(0),
  fStreamLevel(0),
  fDebugLevel(0),
  fDebugOutputPath()
{
  //
  // Normal constructor
  //
  // Input slot #0 works with a TChain
  DefineInput(0, TChain::Class());
  // Output slot #0 writes into a TList
  DefineOutput(0, TObjArray::Class());
  //
  //
  fCompList = new TObjArray;
}

AliGenInfoTask::~AliGenInfoTask(){
  //
  //
  //
  if (fDebugLevel>0)  printf("AliGenInfoTask::~AliGenInfoTask\n");
  if (fDebugStreamer) delete fDebugStreamer;
  fDebugStreamer=0;
  if(fCompList)   delete fCompList;
  fCompList =0;
}

//________________________________________________________________________
void AliGenInfoTask::ConnectInputData(Option_t *)
{
  //
  // Connect the input data
  //
  if(fDebugLevel>3)
    cout << "AnalysisTaskTPCCluster::ConnectInputData()" << endl;

  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
  if (!tree) {
    //Printf("ERROR: Could not read chain from input slot 0");
  }
  else {
    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    if (!esdH) {
      //Printf("ERROR: Could not get ESDInputHandler");
    }
    else {
      fESD = esdH->GetEvent();
      fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
      fESD->SetESDfriend(fESDfriend);
      //Printf("*** CONNECTED NEW EVENT ****");
    }
  }
  AliMCEventHandler* mcinfo = (AliMCEventHandler*) (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
  mcinfo->SetReadTR(kTRUE);

  fMCinfo = mcinfo->MCEvent();

}

//_____________________________________________________________________________
Bool_t AliGenInfoTask::AddComparisonObject(AliComparisonObject *pObj)
{
  // add comparison object to the list
  if(pObj == 0) {
      Printf("ERROR: Could not add comparison object");
	  return kFALSE;
  }
  // add object to the list
  fCompList->AddLast(pObj);
  return kTRUE;
}

//________________________________________________________________________
void AliGenInfoTask::CreateOutputObjects()
{
  //
  // Connect the output objects
  //
  if(fDebugLevel>3)
    cout << "AnalysisTaskTPCCluster::CreateOutputObjects()" << endl;

}

//________________________________________________________________________
void AliGenInfoTask::Exec(Option_t *) {
  //
  // Execute analysis for current event
  //

  if(fDebugLevel>3)
    cout << "AliGenInfoTask::Exec()" << endl;

  // If MC has been connected
  if (fGenTracksArray) fGenTracksArray->Delete();
  if (fRecTracksArray) fRecTracksArray->Delete();

  if (!fMCinfo){
    cout << "Not MC info\n" << endl;
  }else{
    //mcinfo->Print();
    ProcessMCInfo();
    ProcessESDInfo();
    DumpInfo();
    ProcessComparison();
  }
  //
}

//________________________________________________________________________
void AliGenInfoTask::Terminate(Option_t *) {
    //
    // Terminate loop
    //
  if(fDebugLevel>3)
    printf("AliGenInfoTask: Terminate() \n");
  //
  if (fDebugLevel>0) printf("AliTPCcalibBase::Terminate\n");
  if (fDebugStreamer) delete fDebugStreamer;
  fDebugStreamer = 0;
  return;
}

TTreeSRedirector *AliGenInfoTask::GetDebugStreamer(){
  //
  // Get Debug streamer
  // In case debug streamer not yet initialized and StreamLevel>0 create new one
  //
  if (fStreamLevel==0) return 0;
  if (fDebugStreamer) return fDebugStreamer;
  TString dsName;
  dsName=GetName();
  dsName+="Debug.root";
  dsName.ReplaceAll(" ","");
  fDebugStreamer = new TTreeSRedirector(dsName.Data());
  return fDebugStreamer;
}

AliMCInfo*  AliGenInfoTask::GetTrack(Int_t index, Bool_t force){
  //
  // Get the MC info for given track
  //
  if (!fGenTracksArray) fGenTracksArray = new TClonesArray("AliMCInfo",1000);
  if (index>fGenTracksArray->GetEntriesFast()) fGenTracksArray->Expand(index*2+10);
  AliMCInfo * info = (AliMCInfo*)fGenTracksArray->At(index);
  if (!force) return info;
  if (!info){
    info = new ((*fGenTracksArray)[index]) AliMCInfo;
  }
  return info;
}

AliESDRecInfo*  AliGenInfoTask::GetRecTrack(Int_t index, Bool_t force){
  //
  // Get the MC info for given track
  //
  if (!fRecTracksArray) fRecTracksArray = new TClonesArray("AliESDRecInfo",1000);
  if (index>fRecTracksArray->GetEntriesFast()) fRecTracksArray->Expand(index*2+10);
  AliESDRecInfo * info = (AliESDRecInfo*)fRecTracksArray->At(index);
  if (!force) return info;
  if (!info){
    info = new ((*fRecTracksArray)[index]) AliESDRecInfo;
  }
  return info;
}

void  AliGenInfoTask::ProcessMCInfo(){
  //
  // Dump information from MC to the array
  //
  //
  TParticle * particle= new TParticle;
  TClonesArray * trefs = new TClonesArray("AliTrackReference");
  //
  //
  // Process tracks
  //
  Int_t npart = fMCinfo->GetNumberOfTracks();
  if (npart==0) return;
  Double_t vertex[4]={0,0,0,0};
  fMCinfo->GetParticleAndTR(0, particle, trefs);
  if (particle){
    vertex[0]=particle->Vx();
    vertex[1]=particle->Vy();
    vertex[2]=particle->Vz();
    vertex[3]=particle->R();
  }

  for (Int_t ipart=0;ipart<npart;ipart++){
    Int_t status = fMCinfo->GetParticleAndTR(ipart, particle, trefs);
    if (status<0) continue;
    if (!particle) continue;
    if (!trefs) continue;
    if (!AcceptParticle(particle)) continue;
    //if (trefs->GetEntries()<1) continue;
    AliMCInfo * mcinfo = GetTrack(ipart,kTRUE);
    mcinfo->Update(particle,trefs,vertex,ipart);
    //
    TTreeSRedirector *pcstream = GetDebugStreamer();
    if (pcstream){
      (*pcstream)<<"MC"<<
	"p.="<<particle<<
	"MC.="<<mcinfo<<
	"\n";
    }
  }
}

void AliGenInfoTask::ProcessESDInfo(){
  //
  //
  //
  static AliTPCParamSR param;
  fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
  if (!fESDfriend) {
    //Printf("ERROR: fESDfriend not available");
    return;
  }
  fESD->SetESDfriend(fESDfriend);
  //
  //
  if (!fESD) return;
  Int_t ntracks = fESD->GetNumberOfTracks();
  for (Int_t itrack=0; itrack<ntracks; itrack++){
    AliESDtrack *track = fESD->GetTrack(itrack);
    Int_t label = TMath::Abs(track->GetLabel());
    AliMCInfo * mcinfo = GetTrack(label,kFALSE);
    if (!mcinfo) continue;
    AliESDRecInfo *recInfo= GetRecTrack(label,kTRUE);
    recInfo->AddESDtrack(track,mcinfo);
    recInfo->Update(mcinfo,&param,kTRUE);
  }
  //

}

void AliGenInfoTask::ProcessComparison(){
  //
  //
  //
  static AliESDRecInfo dummy;
  Int_t npart = fMCinfo->GetNumberOfTracks();
  for (Int_t ipart=0;ipart<npart;ipart++){
    AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);
    if (!mcinfo) continue;
    AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);
    if (!recInfo) recInfo=&dummy;
    //
    for (Int_t icomp = 0; icomp<fCompList->GetEntries(); icomp++){
      AliComparisonObject *pObj= (AliComparisonObject *)fCompList->At(icomp);
      if (pObj){
	pObj->Exec(mcinfo,recInfo);
      }
    }
  }
  PostData(0, fCompList);
}

void AliGenInfoTask::DumpInfo(){
  //
  //
  //

  static AliESDRecInfo dummy;
  Int_t npart = fMCinfo->GetNumberOfTracks();
  for (Int_t ipart=0;ipart<npart;ipart++){
    AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);
    if (!mcinfo) continue;
    AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);
    //
  //   AliTPCseed *tpctrack=0;
//     if (recInfo) {
//       AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(recInfo->GetESDtrack()->GetID());
//       if (friendTrack) {
// 	TObject *calibObject=0;
// 	AliTPCseed *seed=0;
// 	for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
// 	  if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
// 	    break;
// 	tpctrack=seed;
//       }
//     }
//     if (!tpctrack) continue;
    if (!recInfo) recInfo=&dummy;
    TTreeSRedirector *pcstream = GetDebugStreamer();
    if (pcstream){
      (*pcstream)<<"RC"<<
	"MC.="<<mcinfo<<
	"RC.="<<recInfo<<
	//	"tr.="<<tpctrack<<
	"\n";
    }
  }
}

Bool_t AliGenInfoTask::AcceptParticle(TParticle *part){
  //
  /*
    MC cuts
    TCut cutPt("p.Pt()>0.1");
    TCut cutZ("abs(p.Vz())<250");
    TCut cutR("abs(p.R())<250");
    //
  */
  //
  //
  if (part->Pt()<0.1) return kFALSE;
  if (TMath::Abs(part->Vz())>250) return kFALSE;
  if (part->R()>360)  return kFALSE;
  if (part->GetPDG()){
    if (part->GetPDG()->Charge()==0) return kFALSE;
  }
  return kTRUE;
}

void AliGenInfoTask::FinishTaskOutput()
{
  //
  // According description in AliAnalisysTask this method is call
  // on the slaves before sending data
  //
  Terminate("slave");
  RegisterDebugOutput(fDebugOutputPath.Data());

}

void AliGenInfoTask::RegisterDebugOutput(const char *path){
  //
  // store  - copy debug output to the destination position
  // currently ONLY for local copy
  TString dsName;
  dsName=GetName();
  dsName+="Debug.root";
  dsName.ReplaceAll(" ","");
  TString dsName2=fDebugOutputPath.Data();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+="/";;
  dsName2+=gSystem->HostName();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+="/";
  dsName2+=gSystem->BaseName(gSystem->pwd());
  dsName2+="/";
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+=dsName;
  AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
  printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
  TFile::Cp(dsName.Data(),dsName2.Data());
}
<commit_msg>Fix warning<commit_after>//
// This class is the task for connecting together
// MC information and the RC information
//
// The task is a wrapper over two components
// AliGenInfoMaker
// AliESDRecInfoMaker.h

// ROOT includes
#include <TChain.h>
#include <TMath.h>

// ALIROOT includes
#include <TTreeStream.h>
#include <AliAnalysisManager.h>
#include <AliESDInputHandler.h>
#include "AliStack.h"
#include "AliMCEvent.h"
#include "AliMCEventHandler.h"

#include <AliESD.h>
#include "AliGenInfoTask.h"
#include "AliGenInfoMaker.h"
#include "AliHelix.h"

//
#include "AliMCInfo.h"
#include "AliComparisonObject.h"
#include "AliESDRecInfo.h"
#include "AliTPCParamSR.h"
#include "TSystem.h"
#include "TTimeStamp.h"
#include "TFile.h"
#include "AliTPCseed.h"

// STL includes
#include <iostream>

using namespace std;

ClassImp(AliGenInfoTask)

//________________________________________________________________________
AliGenInfoTask::AliGenInfoTask() :
  AliAnalysisTask(),
  fMCinfo(0),     //! MC event handler
  fESD(0),
  fESDfriend(0),
  fCompList(0),         //array of comparison objects
  fGenTracksArray(0),  //clones array with filtered particles
  fGenKinkArray(0),    //clones array with filtered Kinks
  fGenV0Array(0),      //clones array with filtered V0s
  fRecTracksArray(0),  //clones array with filtered particles
  fDebugStreamer(0),
  fStreamLevel(0),
  fDebugLevel(0),
  fDebugOutputPath()
{
  //
  // Default constructor (should not be used)
  //
}

AliGenInfoTask::AliGenInfoTask(const AliGenInfoTask& /*info*/) :
  AliAnalysisTask(),
  fMCinfo(0),     //! MC event handler
  fESD(0),
  fESDfriend(0),
  fCompList(0),
  fGenTracksArray(0),  //clones array with filtered particles
  fGenKinkArray(0),    //clones array with filtered Kinks
  fGenV0Array(0),      //clones array with filtered V0s
  fRecTracksArray(0),  //clones array with filtered particles
  //
  fDebugStreamer(0),
  fStreamLevel(0),
  fDebugLevel(),
  fDebugOutputPath()
{
  //
  // Default constructor
  //
}

//________________________________________________________________________
AliGenInfoTask::AliGenInfoTask(const char *name) :
  AliAnalysisTask(name, "AliGenInfoTask"),
  fMCinfo(0),     //! MC event handler
  fESD(0),
  fESDfriend(0),
  fCompList(0),
  fGenTracksArray(0),  //clones array with filtered particles
  fGenKinkArray(0),    //clones array with filtered Kinks
  fGenV0Array(0),      //clones array with filtered V0s
  fRecTracksArray(0),  //clones array with filtered particles
  fDebugStreamer(0),
  fStreamLevel(0),
  fDebugLevel(0),
  fDebugOutputPath()
{
  //
  // Normal constructor
  //
  // Input slot #0 works with a TChain
  DefineInput(0, TChain::Class());
  // Output slot #0 writes into a TList
  DefineOutput(0, TObjArray::Class());
  //
  //
  fCompList = new TObjArray;
}

AliGenInfoTask::~AliGenInfoTask(){
  //
  //
  //
  if (fDebugLevel>0)  printf("AliGenInfoTask::~AliGenInfoTask\n");
  if (fDebugStreamer) delete fDebugStreamer;
  fDebugStreamer=0;
  if(fCompList)   delete fCompList;
  fCompList =0;
}

//________________________________________________________________________
void AliGenInfoTask::ConnectInputData(Option_t *)
{
  //
  // Connect the input data
  //
  if(fDebugLevel>3)
    cout << "AnalysisTaskTPCCluster::ConnectInputData()" << endl;

  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
  if (!tree) {
    //Printf("ERROR: Could not read chain from input slot 0");
  }
  else {
    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    if (!esdH) {
      //Printf("ERROR: Could not get ESDInputHandler");
    }
    else {
      fESD = esdH->GetEvent();
      fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
      fESD->SetESDfriend(fESDfriend);
      //Printf("*** CONNECTED NEW EVENT ****");
    }
  }
  AliMCEventHandler* mcinfo = (AliMCEventHandler*) (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
  mcinfo->SetReadTR(kTRUE);

  fMCinfo = mcinfo->MCEvent();

}

//_____________________________________________________________________________
Bool_t AliGenInfoTask::AddComparisonObject(AliComparisonObject *pObj)
{
  // add comparison object to the list
  if(pObj == 0) {
      Printf("ERROR: Could not add comparison object");
	  return kFALSE;
  }
  // add object to the list
  fCompList->AddLast(pObj);
  return kTRUE;
}

//________________________________________________________________________
void AliGenInfoTask::CreateOutputObjects()
{
  //
  // Connect the output objects
  //
  if(fDebugLevel>3)
    cout << "AnalysisTaskTPCCluster::CreateOutputObjects()" << endl;

}

//________________________________________________________________________
void AliGenInfoTask::Exec(Option_t *) {
  //
  // Execute analysis for current event
  //

  if(fDebugLevel>3)
    cout << "AliGenInfoTask::Exec()" << endl;

  // If MC has been connected
  if (fGenTracksArray) fGenTracksArray->Delete();
  if (fRecTracksArray) fRecTracksArray->Delete();

  if (!fMCinfo){
    cout << "Not MC info\n" << endl;
  }else{
    //mcinfo->Print();
    ProcessMCInfo();
    ProcessESDInfo();
    DumpInfo();
    ProcessComparison();
  }
  //
}

//________________________________________________________________________
void AliGenInfoTask::Terminate(Option_t *) {
    //
    // Terminate loop
    //
  if(fDebugLevel>3)
    printf("AliGenInfoTask: Terminate() \n");
  //
  if (fDebugLevel>0) printf("AliTPCcalibBase::Terminate\n");
  if (fDebugStreamer) delete fDebugStreamer;
  fDebugStreamer = 0;
  return;
}

TTreeSRedirector *AliGenInfoTask::GetDebugStreamer(){
  //
  // Get Debug streamer
  // In case debug streamer not yet initialized and StreamLevel>0 create new one
  //
  if (fStreamLevel==0) return 0;
  if (fDebugStreamer) return fDebugStreamer;
  TString dsName;
  dsName=GetName();
  dsName+="Debug.root";
  dsName.ReplaceAll(" ","");
  fDebugStreamer = new TTreeSRedirector(dsName.Data());
  return fDebugStreamer;
}

AliMCInfo*  AliGenInfoTask::GetTrack(Int_t index, Bool_t force){
  //
  // Get the MC info for given track
  //
  if (!fGenTracksArray) fGenTracksArray = new TClonesArray("AliMCInfo",1000);
  if (index>fGenTracksArray->GetEntriesFast()) fGenTracksArray->Expand(index*2+10);
  AliMCInfo * info = (AliMCInfo*)fGenTracksArray->At(index);
  if (!force) return info;
  if (!info){
    info = new ((*fGenTracksArray)[index]) AliMCInfo;
  }
  return info;
}

AliESDRecInfo*  AliGenInfoTask::GetRecTrack(Int_t index, Bool_t force){
  //
  // Get the MC info for given track
  //
  if (!fRecTracksArray) fRecTracksArray = new TClonesArray("AliESDRecInfo",1000);
  if (index>fRecTracksArray->GetEntriesFast()) fRecTracksArray->Expand(index*2+10);
  AliESDRecInfo * info = (AliESDRecInfo*)fRecTracksArray->At(index);
  if (!force) return info;
  if (!info){
    info = new ((*fRecTracksArray)[index]) AliESDRecInfo;
  }
  return info;
}

void  AliGenInfoTask::ProcessMCInfo(){
  //
  // Dump information from MC to the array
  //
  //
  TParticle * particle= new TParticle;
  TClonesArray * trefs = new TClonesArray("AliTrackReference");
  //
  //
  // Process tracks
  //
  Int_t npart = fMCinfo->GetNumberOfTracks();
  if (npart==0) return;
  Double_t vertex[4]={0,0,0,0};
  fMCinfo->GetParticleAndTR(0, particle, trefs);
  if (particle){
    vertex[0]=particle->Vx();
    vertex[1]=particle->Vy();
    vertex[2]=particle->Vz();
    vertex[3]=particle->R();
  }

  for (Int_t ipart=0;ipart<npart;ipart++){
    Int_t status = fMCinfo->GetParticleAndTR(ipart, particle, trefs);
    if (status<0) continue;
    if (!particle) continue;
    if (!trefs) continue;
    if (!AcceptParticle(particle)) continue;
    //if (trefs->GetEntries()<1) continue;
    AliMCInfo * mcinfo = GetTrack(ipart,kTRUE);
    mcinfo->Update(particle,trefs,vertex,ipart);
    //
    TTreeSRedirector *pcstream = GetDebugStreamer();
    if (pcstream){
      (*pcstream)<<"MC"<<
	"p.="<<particle<<
	"MC.="<<mcinfo<<
	"\n";
    }
  }
}

void AliGenInfoTask::ProcessESDInfo(){
  //
  //
  //
  static AliTPCParamSR param;
  fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
  if (!fESDfriend) {
    //Printf("ERROR: fESDfriend not available");
    return;
  }
  fESD->SetESDfriend(fESDfriend);
  //
  //
  if (!fESD) return;
  Int_t ntracks = fESD->GetNumberOfTracks();
  for (Int_t itrack=0; itrack<ntracks; itrack++){
    AliESDtrack *track = fESD->GetTrack(itrack);
    Int_t label = TMath::Abs(track->GetLabel());
    AliMCInfo * mcinfo = GetTrack(label,kFALSE);
    if (!mcinfo) continue;
    AliESDRecInfo *recInfo= GetRecTrack(label,kTRUE);
    recInfo->AddESDtrack(track,mcinfo);
    recInfo->Update(mcinfo,&param,kTRUE);
  }
  //

}

void AliGenInfoTask::ProcessComparison(){
  //
  //
  //
  static AliESDRecInfo dummy;
  Int_t npart = fMCinfo->GetNumberOfTracks();
  for (Int_t ipart=0;ipart<npart;ipart++){
    AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);
    if (!mcinfo) continue;
    AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);
    if (!recInfo) recInfo=&dummy;
    //
    for (Int_t icomp = 0; icomp<fCompList->GetEntries(); icomp++){
      AliComparisonObject *pObj= (AliComparisonObject *)fCompList->At(icomp);
      if (pObj){
	pObj->Exec(mcinfo,recInfo);
      }
    }
  }
  PostData(0, fCompList);
}

void AliGenInfoTask::DumpInfo(){
  //
  //
  //

  static AliESDRecInfo dummy;
  Int_t npart = fMCinfo->GetNumberOfTracks();
  for (Int_t ipart=0;ipart<npart;ipart++){
    AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);
    if (!mcinfo) continue;
    AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);
    //
  //   AliTPCseed *tpctrack=0;
//     if (recInfo) {
//       AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(recInfo->GetESDtrack()->GetID());
//       if (friendTrack) {
// 	TObject *calibObject=0;
// 	AliTPCseed *seed=0;
// 	for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
// 	  if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
// 	    break;
// 	tpctrack=seed;
//       }
//     }
//     if (!tpctrack) continue;
    if (!recInfo) recInfo=&dummy;
    TTreeSRedirector *pcstream = GetDebugStreamer();
    if (pcstream){
      (*pcstream)<<"RC"<<
	"MC.="<<mcinfo<<
	"RC.="<<recInfo<<
	//	"tr.="<<tpctrack<<
	"\n";
    }
  }
}

Bool_t AliGenInfoTask::AcceptParticle(TParticle *part){
  //
  /*
    MC cuts
    TCut cutPt("p.Pt()>0.1");
    TCut cutZ("abs(p.Vz())<250");
    TCut cutR("abs(p.R())<250");
    //
  */
  //
  //
  if (part->Pt()<0.1) return kFALSE;
  if (TMath::Abs(part->Vz())>250) return kFALSE;
  if (part->R()>360)  return kFALSE;
  if (part->GetPDG()){
    if (part->GetPDG()->Charge()==0) return kFALSE;
  }
  return kTRUE;
}

void AliGenInfoTask::FinishTaskOutput()
{
  //
  // According description in AliAnalisysTask this method is call
  // on the slaves before sending data
  //
  Terminate("slave");
  RegisterDebugOutput(fDebugOutputPath.Data());

}

void AliGenInfoTask::RegisterDebugOutput(const char */*path*/){
  //
  // store  - copy debug output to the destination position
  // currently ONLY for local copy
  TString dsName;
  dsName=GetName();
  dsName+="Debug.root";
  dsName.ReplaceAll(" ","");
  TString dsName2=fDebugOutputPath.Data();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+="/";;
  dsName2+=gSystem->HostName();
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+="/";
  dsName2+=gSystem->BaseName(gSystem->pwd());
  dsName2+="/";
  gSystem->MakeDirectory(dsName2.Data());
  dsName2+=dsName;
  AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
  printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
  TFile::Cp(dsName.Data(),dsName2.Data());
}
<|endoftext|>


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

#include <gdk/gdkkeysyms.h>
#include <X11/XF86keysym.h>

#include "chrome/browser/accelerator_table_linux.h"

#include "base/basictypes.h"
#include "chrome/app/chrome_dll_resource.h"

namespace browser {

// Keep this in sync with various context menus which display the accelerators.
const AcceleratorMapping kAcceleratorMap[] = {
  // Focus.
  { GDK_k, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
  { GDK_e, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
  { XF86XK_Search, IDC_FOCUS_SEARCH, GdkModifierType(0) },
  { GDK_l, IDC_FOCUS_LOCATION, GDK_CONTROL_MASK },
  { GDK_d, IDC_FOCUS_LOCATION, GDK_MOD1_MASK },
  { GDK_F6, IDC_FOCUS_LOCATION, GdkModifierType(0) },
  { XF86XK_OpenURL, IDC_FOCUS_LOCATION, GdkModifierType(0) },
  { XF86XK_Go, IDC_FOCUS_LOCATION, GdkModifierType(0) },

  // Tab/window controls.
  { GDK_Page_Down, IDC_SELECT_NEXT_TAB, GDK_CONTROL_MASK },
  { GDK_Page_Up, IDC_SELECT_PREVIOUS_TAB, GDK_CONTROL_MASK },
  { GDK_w, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
  { GDK_t, IDC_RESTORE_TAB,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },

  { GDK_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },
  { GDK_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },
  { GDK_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },
  { GDK_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },
  { GDK_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },
  { GDK_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },
  { GDK_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },
  { GDK_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },
  { GDK_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },

  { GDK_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },
  { GDK_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },
  { GDK_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },
  { GDK_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },
  { GDK_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },
  { GDK_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },
  { GDK_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },
  { GDK_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },
  { GDK_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },

  { GDK_F4, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
  { GDK_F4, IDC_CLOSE_WINDOW, GDK_MOD1_MASK },

  // Zoom level.
  { GDK_plus, IDC_ZOOM_PLUS,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
  { GDK_equal, IDC_ZOOM_PLUS, GDK_CONTROL_MASK },
  { XF86XK_ZoomIn, IDC_ZOOM_PLUS, GdkModifierType(0) },
  { GDK_0, IDC_ZOOM_NORMAL, GDK_CONTROL_MASK },
  { GDK_minus, IDC_ZOOM_MINUS, GDK_CONTROL_MASK },
  { GDK_underscore, IDC_ZOOM_MINUS,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
  { XF86XK_ZoomOut, IDC_ZOOM_MINUS, GdkModifierType(0) },

  // Find in page.
  { GDK_g, IDC_FIND_NEXT, GDK_CONTROL_MASK },
  { GDK_F3, IDC_FIND_NEXT, GdkModifierType(0) },
  { GDK_g, IDC_FIND_PREVIOUS,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
  { GDK_F3, IDC_FIND_PREVIOUS, GDK_SHIFT_MASK },

  // Navigation / toolbar buttons.
  { GDK_Home, IDC_HOME, GDK_MOD1_MASK },
  { XF86XK_HomePage, IDC_HOME, GdkModifierType(0) },
  { GDK_Escape, IDC_STOP, GdkModifierType(0) },
  { XF86XK_Stop, IDC_STOP, GdkModifierType(0) },
  { GDK_Left, IDC_BACK, GDK_MOD1_MASK },
  { GDK_BackSpace, IDC_BACK, GdkModifierType(0) },
  { XF86XK_Back, IDC_BACK, GdkModifierType(0) },
  { GDK_Right, IDC_FORWARD, GDK_MOD1_MASK },
  { GDK_BackSpace, IDC_FORWARD, GDK_SHIFT_MASK },
  { XF86XK_Forward, IDC_FORWARD, GdkModifierType(0) },
  { GDK_r, IDC_RELOAD, GDK_CONTROL_MASK },
  { GDK_F5, IDC_RELOAD, GdkModifierType(0) },
  { GDK_F5, IDC_RELOAD, GDK_CONTROL_MASK },
  { GDK_F5, IDC_RELOAD, GDK_SHIFT_MASK },
  { XF86XK_Reload, IDC_RELOAD, GdkModifierType(0) },
  { XF86XK_Refresh, IDC_RELOAD, GdkModifierType(0) },

  // Miscellany.
  { GDK_d, IDC_STAR, GDK_CONTROL_MASK },
  { XF86XK_AddFavorite, IDC_STAR, GdkModifierType(0) },
  { XF86XK_Favorites, IDC_SHOW_BOOKMARK_BAR, GdkModifierType(0) },
  { XF86XK_History, IDC_SHOW_HISTORY, GdkModifierType(0) },
  { GDK_o, IDC_OPEN_FILE, GDK_CONTROL_MASK },
  { GDK_F11, IDC_FULLSCREEN, GdkModifierType(0) },
  { GDK_u, IDC_VIEW_SOURCE, GDK_CONTROL_MASK },
  { GDK_p, IDC_PRINT, GDK_CONTROL_MASK },
  { GDK_Escape, IDC_TASK_MANAGER, GDK_SHIFT_MASK },

#if defined(OS_CHROMEOS)
  { GDK_f, IDC_FULLSCREEN,
    GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
  { GDK_Delete, IDC_TASK_MANAGER,
    GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
  { GDK_comma, IDC_CONTROL_PANEL, GdkModifierType(GDK_CONTROL_MASK) },
#endif
};

const size_t kAcceleratorMapLength = arraysize(kAcceleratorMap);

}  // namespace browser
<commit_msg>GTK: Allow keypad to be used for all tab selection accelerators.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gdk/gdkkeysyms.h>
#include <X11/XF86keysym.h>

#include "chrome/browser/accelerator_table_linux.h"

#include "base/basictypes.h"
#include "chrome/app/chrome_dll_resource.h"

namespace browser {

// Keep this in sync with various context menus which display the accelerators.
const AcceleratorMapping kAcceleratorMap[] = {
  // Focus.
  { GDK_k, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
  { GDK_e, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
  { XF86XK_Search, IDC_FOCUS_SEARCH, GdkModifierType(0) },
  { GDK_l, IDC_FOCUS_LOCATION, GDK_CONTROL_MASK },
  { GDK_d, IDC_FOCUS_LOCATION, GDK_MOD1_MASK },
  { GDK_F6, IDC_FOCUS_LOCATION, GdkModifierType(0) },
  { XF86XK_OpenURL, IDC_FOCUS_LOCATION, GdkModifierType(0) },
  { XF86XK_Go, IDC_FOCUS_LOCATION, GdkModifierType(0) },

  // Tab/window controls.
  { GDK_Page_Down, IDC_SELECT_NEXT_TAB, GDK_CONTROL_MASK },
  { GDK_Page_Up, IDC_SELECT_PREVIOUS_TAB, GDK_CONTROL_MASK },
  { GDK_w, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
  { GDK_t, IDC_RESTORE_TAB,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },

  { GDK_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },
  { GDK_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },
  { GDK_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },
  { GDK_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },
  { GDK_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },
  { GDK_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },
  { GDK_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },
  { GDK_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },
  { GDK_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },

  { GDK_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },
  { GDK_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },
  { GDK_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },
  { GDK_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },
  { GDK_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },
  { GDK_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },
  { GDK_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },
  { GDK_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },
  { GDK_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },

  { GDK_KP_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },
  { GDK_KP_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },
  { GDK_KP_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },
  { GDK_KP_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },
  { GDK_KP_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },
  { GDK_KP_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },
  { GDK_KP_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },
  { GDK_KP_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },
  { GDK_KP_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },

  { GDK_KP_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },
  { GDK_KP_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },
  { GDK_KP_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },
  { GDK_KP_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },
  { GDK_KP_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },
  { GDK_KP_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },
  { GDK_KP_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },
  { GDK_KP_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },
  { GDK_KP_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },

  { GDK_F4, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
  { GDK_F4, IDC_CLOSE_WINDOW, GDK_MOD1_MASK },

  // Zoom level.
  { GDK_plus, IDC_ZOOM_PLUS,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
  { GDK_equal, IDC_ZOOM_PLUS, GDK_CONTROL_MASK },
  { XF86XK_ZoomIn, IDC_ZOOM_PLUS, GdkModifierType(0) },
  { GDK_0, IDC_ZOOM_NORMAL, GDK_CONTROL_MASK },
  { GDK_minus, IDC_ZOOM_MINUS, GDK_CONTROL_MASK },
  { GDK_underscore, IDC_ZOOM_MINUS,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
  { XF86XK_ZoomOut, IDC_ZOOM_MINUS, GdkModifierType(0) },

  // Find in page.
  { GDK_g, IDC_FIND_NEXT, GDK_CONTROL_MASK },
  { GDK_F3, IDC_FIND_NEXT, GdkModifierType(0) },
  { GDK_g, IDC_FIND_PREVIOUS,
    GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
  { GDK_F3, IDC_FIND_PREVIOUS, GDK_SHIFT_MASK },

  // Navigation / toolbar buttons.
  { GDK_Home, IDC_HOME, GDK_MOD1_MASK },
  { XF86XK_HomePage, IDC_HOME, GdkModifierType(0) },
  { GDK_Escape, IDC_STOP, GdkModifierType(0) },
  { XF86XK_Stop, IDC_STOP, GdkModifierType(0) },
  { GDK_Left, IDC_BACK, GDK_MOD1_MASK },
  { GDK_BackSpace, IDC_BACK, GdkModifierType(0) },
  { XF86XK_Back, IDC_BACK, GdkModifierType(0) },
  { GDK_Right, IDC_FORWARD, GDK_MOD1_MASK },
  { GDK_BackSpace, IDC_FORWARD, GDK_SHIFT_MASK },
  { XF86XK_Forward, IDC_FORWARD, GdkModifierType(0) },
  { GDK_r, IDC_RELOAD, GDK_CONTROL_MASK },
  { GDK_F5, IDC_RELOAD, GdkModifierType(0) },
  { GDK_F5, IDC_RELOAD, GDK_CONTROL_MASK },
  { GDK_F5, IDC_RELOAD, GDK_SHIFT_MASK },
  { XF86XK_Reload, IDC_RELOAD, GdkModifierType(0) },
  { XF86XK_Refresh, IDC_RELOAD, GdkModifierType(0) },

  // Miscellany.
  { GDK_d, IDC_STAR, GDK_CONTROL_MASK },
  { XF86XK_AddFavorite, IDC_STAR, GdkModifierType(0) },
  { XF86XK_Favorites, IDC_SHOW_BOOKMARK_BAR, GdkModifierType(0) },
  { XF86XK_History, IDC_SHOW_HISTORY, GdkModifierType(0) },
  { GDK_o, IDC_OPEN_FILE, GDK_CONTROL_MASK },
  { GDK_F11, IDC_FULLSCREEN, GdkModifierType(0) },
  { GDK_u, IDC_VIEW_SOURCE, GDK_CONTROL_MASK },
  { GDK_p, IDC_PRINT, GDK_CONTROL_MASK },
  { GDK_Escape, IDC_TASK_MANAGER, GDK_SHIFT_MASK },

#if defined(OS_CHROMEOS)
  { GDK_f, IDC_FULLSCREEN,
    GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
  { GDK_Delete, IDC_TASK_MANAGER,
    GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
  { GDK_comma, IDC_CONTROL_PANEL, GdkModifierType(GDK_CONTROL_MASK) },
#endif
};

const size_t kAcceleratorMapLength = arraysize(kAcceleratorMap);

}  // namespace browser
<|endoftext|>


<commit_before>// Ouzel by Elviss Strazdins

#ifndef OUZEL_AUDIO_MIXER_STREAM_HPP
#define OUZEL_AUDIO_MIXER_STREAM_HPP

#include "Object.hpp"
#include "Bus.hpp"
#include "Data.hpp"

namespace ouzel::audio::mixer
{
    class Bus;
    class Data;

    class Stream: public Object
    {
        friend Bus;
    public:
        explicit Stream(Data& initData) noexcept:
            data{initData}
        {
        }

        ~Stream() override
        {
            if (output) output->removeInput(this);
        }

        Stream(const Stream&) = delete;
        Stream& operator=(const Object&) = delete;

        Stream(Stream&&) = delete;
        Stream& operator=(Stream&&) = delete;

        auto& getData() const noexcept { return data; }

        void setOutput(Bus* newOutput)
        {
            if (output) output->removeInput(this);
            output = newOutput;
            if (output) output->addInput(this);
        }

        auto isPlaying() const noexcept { return playing; }
        void play() { playing = true; }

        void stop(bool shouldReset)
        {
            playing = false;
            if (shouldReset) reset();
        }

        virtual void reset() = 0;

        virtual void generateSamples(std::uint32_t frames, std::vector<float>& samples) = 0;

    protected:
        Data& data;
        Bus* output = nullptr;
        bool playing = false;
    };
}

#endif // OUZEL_AUDIO_MIXER_STREAM_HPP
<commit_msg>Make play noexcept<commit_after>// Ouzel by Elviss Strazdins

#ifndef OUZEL_AUDIO_MIXER_STREAM_HPP
#define OUZEL_AUDIO_MIXER_STREAM_HPP

#include "Object.hpp"
#include "Bus.hpp"
#include "Data.hpp"

namespace ouzel::audio::mixer
{
    class Bus;
    class Data;

    class Stream: public Object
    {
        friend Bus;
    public:
        explicit Stream(Data& initData) noexcept:
            data{initData}
        {
        }

        ~Stream() override
        {
            if (output) output->removeInput(this);
        }

        Stream(const Stream&) = delete;
        Stream& operator=(const Object&) = delete;

        Stream(Stream&&) = delete;
        Stream& operator=(Stream&&) = delete;

        auto& getData() const noexcept { return data; }

        void setOutput(Bus* newOutput)
        {
            if (output) output->removeInput(this);
            output = newOutput;
            if (output) output->addInput(this);
        }

        auto isPlaying() const noexcept { return playing; }
        void play() noexcept { playing = true; }

        void stop(bool shouldReset)
        {
            playing = false;
            if (shouldReset) reset();
        }

        virtual void reset() = 0;

        virtual void generateSamples(std::uint32_t frames, std::vector<float>& samples) = 0;

    protected:
        Data& data;
        Bus* output = nullptr;
        bool playing = false;
    };
}

#endif // OUZEL_AUDIO_MIXER_STREAM_HPP
<|endoftext|>


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

#include "chrome/browser/cookie_modal_dialog.h"

#include "app/l10n_util.h"
#include "base/logging.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/views/cookie_prompt_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/gtk_util.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"

void CookiePromptModalDialog::CreateAndShowDialog() {
  dialog_ = CreateNativeDialog();
  gtk_widget_show_all(GTK_WIDGET(GTK_DIALOG(dialog_)));

  // Suggest a minimum size.
  gint width;
  GtkRequisition req;
  gtk_widget_size_request(dialog_, &req);
  gtk_util::GetWidgetSizeFromResources(dialog_, IDS_ALERT_DIALOG_WIDTH_CHARS, 0,
                                       &width, NULL);
  if (width > req.width)
    gtk_widget_set_size_request(dialog_, width, -1);
}

int CookiePromptModalDialog::GetDialogButtons() {
  return 0;
}

void CookiePromptModalDialog::AcceptWindow() {
  HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);
}

void CookiePromptModalDialog::CancelWindow() {
  HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_REJECT);
}

NativeDialog CookiePromptModalDialog::CreateNativeDialog() {
  gfx::NativeWindow window = tab_contents_->GetMessageBoxRootWindow();
  CookiePromptModalDialog::DialogType type = dialog_type();
  NativeDialog dialog = gtk_dialog_new_with_buttons(
      l10n_util::GetStringFUTF8(
          type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?
          IDS_COOKIE_ALERT_TITLE : IDS_DATA_ALERT_TITLE,
          UTF8ToUTF16(origin().host())).c_str(),
      window,
      GTK_DIALOG_MODAL,
      l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_BLOCK_BUTTON).c_str(),
      GTK_RESPONSE_REJECT,
      l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ALLOW_BUTTON).c_str(),
      GTK_RESPONSE_ACCEPT,
      NULL);

  GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  string16 display_host = UTF8ToUTF16(origin().host());
  GtkWidget* label = gtk_label_new(
      l10n_util::GetStringFUTF8(
          type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?
          IDS_COOKIE_ALERT_LABEL : IDS_DATA_ALERT_LABEL,
          display_host).c_str());

  gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0);

  // Create a vbox for all the radio buttons so they aren't too far away from
  // each other.
  GtkWidget* radio_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  remember_radio_ = gtk_radio_button_new_with_label(NULL,
      l10n_util::GetStringFUTF8(IDS_COOKIE_ALERT_REMEMBER_RADIO,
                                display_host).c_str());
  gtk_box_pack_start(GTK_BOX(radio_box), remember_radio_, FALSE, FALSE, 0);

  GtkWidget* ask_radio = gtk_radio_button_new_with_label_from_widget(
      GTK_RADIO_BUTTON(remember_radio_),
      l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ASK_RADIO).c_str());
  gtk_box_pack_start(GTK_BOX(radio_box), ask_radio, FALSE, FALSE, 0);

  gtk_box_pack_start(GTK_BOX(content_area), radio_box, FALSE, FALSE, 0);

  // Now we create the details link and align it left in the button box.
  GtkWidget* details_button = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_COOKIE_SHOW_DETAILS_LABEL).c_str());
  gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
                     details_button, FALSE, FALSE, 0);
  gtk_widget_set_sensitive(details_button, FALSE);
  gtk_button_box_set_child_secondary(
      GTK_BUTTON_BOX(GTK_DIALOG(dialog)->action_area),
      details_button,
      TRUE);

  // TODO(erg): http://crbug.com/35178 : Needs to implement the cookie details
  // box here.

  gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);
  g_signal_connect(dialog, "response",
                   G_CALLBACK(AppModalDialog::OnDialogResponse),
                   reinterpret_cast<AppModalDialog*>(this));

  gtk_util::MakeAppModalWindowGroup();

  return dialog;
}

void CookiePromptModalDialog::HandleDialogResponse(GtkDialog* dialog,
                                                   gint response_id) {
  bool remember_radio = gtk_toggle_button_get_active(
      GTK_TOGGLE_BUTTON(remember_radio_));
  if (response_id == GTK_RESPONSE_REJECT) {
    BlockSiteData(remember_radio);
  } else if (response_id == GTK_RESPONSE_ACCEPT) {
    // TODO(erg): Needs to use |session_expire_| instead of true.
    AllowSiteData(remember_radio, true);
  } else {
    BlockSiteData(false);
  }
  gtk_widget_destroy(GTK_WIDGET(dialog));

  CompleteDialog();

  gtk_util::AppModalDismissedUngroupWindows();
  delete this;
}
<commit_msg>linux: touchups on the cookie prompt dialog<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/cookie_modal_dialog.h"

#include "app/l10n_util.h"
#include "base/logging.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/views/cookie_prompt_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/gtk_util.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"

void CookiePromptModalDialog::CreateAndShowDialog() {
  dialog_ = CreateNativeDialog();
  gtk_widget_show_all(GTK_WIDGET(GTK_DIALOG(dialog_)));

  // Suggest a minimum size.
  gint width;
  GtkRequisition req;
  gtk_widget_size_request(dialog_, &req);
  gtk_util::GetWidgetSizeFromResources(dialog_, IDS_ALERT_DIALOG_WIDTH_CHARS, 0,
                                       &width, NULL);
  if (width > req.width)
    gtk_widget_set_size_request(dialog_, width, -1);
}

int CookiePromptModalDialog::GetDialogButtons() {
  return 0;
}

void CookiePromptModalDialog::AcceptWindow() {
  HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);
}

void CookiePromptModalDialog::CancelWindow() {
  HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_REJECT);
}

NativeDialog CookiePromptModalDialog::CreateNativeDialog() {
  gfx::NativeWindow window = tab_contents_->GetMessageBoxRootWindow();
  CookiePromptModalDialog::DialogType type = dialog_type();
  NativeDialog dialog = gtk_dialog_new_with_buttons(
      l10n_util::GetStringFUTF8(
          type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?
          IDS_COOKIE_ALERT_TITLE : IDS_DATA_ALERT_TITLE,
          UTF8ToUTF16(origin().host())).c_str(),
      window,
      static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_BLOCK_BUTTON).c_str(),
      GTK_RESPONSE_REJECT,
      l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ALLOW_BUTTON).c_str(),
      GTK_RESPONSE_ACCEPT,
      NULL);
  gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);

  GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  string16 display_host = UTF8ToUTF16(origin().host());
  GtkWidget* label = gtk_util::LeftAlignMisc(gtk_label_new(
      l10n_util::GetStringFUTF8(
          type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?
          IDS_COOKIE_ALERT_LABEL : IDS_DATA_ALERT_LABEL,
          display_host).c_str()));
  gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0);

  // Create a vbox for all the radio buttons so they aren't too far away from
  // each other.
  GtkWidget* radio_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  remember_radio_ = gtk_radio_button_new_with_label(NULL,
      l10n_util::GetStringFUTF8(IDS_COOKIE_ALERT_REMEMBER_RADIO,
                                display_host).c_str());
  gtk_box_pack_start(GTK_BOX(radio_box), remember_radio_, FALSE, FALSE, 0);

  GtkWidget* ask_radio = gtk_radio_button_new_with_label_from_widget(
      GTK_RADIO_BUTTON(remember_radio_),
      l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ASK_RADIO).c_str());
  gtk_box_pack_start(GTK_BOX(radio_box), ask_radio, FALSE, FALSE, 0);

  gtk_box_pack_start(GTK_BOX(content_area), radio_box, FALSE, FALSE, 0);

  // Now we create the details link and align it left in the button box.
  GtkWidget* details_button = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_COOKIE_SHOW_DETAILS_LABEL).c_str());
  gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
                     details_button, FALSE, FALSE, 0);
  gtk_widget_set_sensitive(details_button, FALSE);
  gtk_button_box_set_child_secondary(
      GTK_BUTTON_BOX(GTK_DIALOG(dialog)->action_area),
      details_button,
      TRUE);

  // TODO(erg): http://crbug.com/35178 : Needs to implement the cookie details
  // box here.

  gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);
  g_signal_connect(dialog, "response",
                   G_CALLBACK(AppModalDialog::OnDialogResponse),
                   reinterpret_cast<AppModalDialog*>(this));

  gtk_util::MakeAppModalWindowGroup();

  return dialog;
}

void CookiePromptModalDialog::HandleDialogResponse(GtkDialog* dialog,
                                                   gint response_id) {
  bool remember_radio = gtk_toggle_button_get_active(
      GTK_TOGGLE_BUTTON(remember_radio_));
  if (response_id == GTK_RESPONSE_REJECT) {
    BlockSiteData(remember_radio);
  } else if (response_id == GTK_RESPONSE_ACCEPT) {
    // TODO(erg): Needs to use |session_expire_| instead of true.
    AllowSiteData(remember_radio, true);
  } else {
    BlockSiteData(false);
  }
  gtk_widget_destroy(GTK_WIDGET(dialog));

  CompleteDialog();

  gtk_util::AppModalDismissedUngroupWindows();
  delete this;
}
<|endoftext|>


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

// Navigates the browser to server and client redirect pages and makes sure
// that the correct redirects are reflected in the history database. Errors
// here might indicate that WebKit changed the calls our glue layer gets in
// the case of redirects. It may also mean problems with the history system.

#include "base/file_util.h"
#include "base/platform_thread.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "views/event.h"

namespace {

class RedirectTest : public UITest {
 public:
  RedirectTest()
      : test_server_(net::TestServer::TYPE_HTTP,
                     FilePath(FILE_PATH_LITERAL("chrome/test/data"))) {
  }

 protected:
  net::TestServer test_server_;
};

// Tests a single server redirect
TEST_F(RedirectTest, Server) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  GURL first_url = test_server_.GetURL(
      "server-redirect?" + final_url.spec());

  NavigateToURL(first_url);

  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());

  std::vector<GURL> redirects;
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));

  ASSERT_EQ(1U, redirects.size());
  EXPECT_EQ(final_url.spec(), redirects[0].spec());
}

// Tests a single client redirect.
TEST_F(RedirectTest, Client) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  GURL first_url = test_server_.GetURL(
      "client-redirect?" + final_url.spec());

  // The client redirect appears as two page visits in the browser.
  NavigateToURLBlockUntilNavigationsComplete(first_url, 2);

  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());

  std::vector<GURL> redirects;
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));

  ASSERT_EQ(1U, redirects.size());
  EXPECT_EQ(final_url.spec(), redirects[0].spec());

  // The address bar should display the final URL.
  GURL tab_url;
  EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
  EXPECT_TRUE(final_url == tab_url);

  // Navigate one more time.
  NavigateToURLBlockUntilNavigationsComplete(first_url, 2);

  // The address bar should still display the final URL.
  EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
  EXPECT_TRUE(final_url == tab_url);
}

TEST_F(RedirectTest, ClientEmptyReferer) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("file_client_redirect.html");
  GURL first_url = net::FilePathToFileURL(test_file);

  // The client redirect appears as two page visits in the browser.
  NavigateToURLBlockUntilNavigationsComplete(first_url, 2);

  std::vector<GURL> redirects;
  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
  ASSERT_EQ(1U, redirects.size());
  EXPECT_EQ(final_url.spec(), redirects[0].spec());
}

// Tests to make sure a location change when a pending redirect exists isn't
// flagged as a redirect.
#if defined(OS_MACOSX)
// SimulateOSClick is broken on the Mac: http://crbug.com/45162
#define MAYBE_ClientCancelled DISABLED_ClientCancelled
#elif defined(OS_WIN)
// http://crbug.com/53091
#define MAYBE_ClientCancelled FAILS_ClientCancelled
#else
#define MAYBE_ClientCancelled ClientCancelled
#endif

TEST_F(RedirectTest, MAYBE_ClientCancelled) {
  FilePath first_path(test_data_directory_);
  first_path = first_path.AppendASCII("cancelled_redirect_test.html");
  ASSERT_TRUE(file_util::AbsolutePath(&first_path));
  GURL first_url = net::FilePathToFileURL(first_path);

  NavigateToURLBlockUntilNavigationsComplete(first_url, 1);

  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  ASSERT_TRUE(window.get());
  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  int64 last_nav_time = 0;
  EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
  // Simulate a click to force to make a user-initiated location change;
  // otherwise, a non user-initiated in-page location change will be treated
  // as client redirect and the redirect will be recoreded, which can cause
  // this test failed.
  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(browser->BringToFront());
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  ASSERT_TRUE(
      window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                              views::Event::EF_LEFT_BUTTON_DOWN));
  EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));

  std::vector<GURL> redirects;
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));

  // There should be no redirects from first_url, because the anchor location
  // change that occurs should not be flagged as a redirect and the meta-refresh
  // won't have fired yet.
  ASSERT_EQ(0U, redirects.size());
  GURL current_url;
  ASSERT_TRUE(tab_proxy->GetCurrentURL(&current_url));

  // Need to test final path and ref separately since constructing a file url
  // containing an anchor using FilePathToFileURL will escape the anchor as
  // %23, but in current_url the anchor will be '#'.
  std::string final_ref = "myanchor";
  FilePath current_path;
  ASSERT_TRUE(net::FileURLToFilePath(current_url, &current_path));
  ASSERT_TRUE(file_util::AbsolutePath(&current_path));
  // Path should remain unchanged.
  EXPECT_EQ(StringToLowerASCII(first_path.value()),
            StringToLowerASCII(current_path.value()));
  EXPECT_EQ(final_ref, current_url.ref());
}

// Tests a client->server->server redirect
TEST_F(RedirectTest, ClientServerServer) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  GURL next_to_last = test_server_.GetURL(
      "server-redirect?" + final_url.spec());
  GURL second_url = test_server_.GetURL(
      "server-redirect?" + next_to_last.spec());
  GURL first_url = test_server_.GetURL(
      "client-redirect?" + second_url.spec());
  std::vector<GURL> redirects;

  // We need the sleep for the client redirects, because it appears as two
  // page visits in the browser.
  NavigateToURL(first_url);

  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
    ASSERT_TRUE(tab_proxy.get());
    ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
    if (!redirects.empty())
      break;
  }

  ASSERT_EQ(3U, redirects.size());
  EXPECT_EQ(second_url.spec(), redirects[0].spec());
  EXPECT_EQ(next_to_last.spec(), redirects[1].spec());
  EXPECT_EQ(final_url.spec(), redirects[2].spec());
}

// Tests that the "#reference" gets preserved across server redirects.
TEST_F(RedirectTest, ServerReference) {
  ASSERT_TRUE(test_server_.Start());

  const std::string ref("reference");

  GURL final_url = test_server_.GetURL(std::string());
  GURL initial_url = test_server_.GetURL(
      "server-redirect?" + final_url.spec() + "#" + ref);

  NavigateToURL(initial_url);

  GURL url = GetActiveTabURL();
  EXPECT_EQ(ref, url.ref());
}

// Test that redirect from http:// to file:// :
// A) does not crash the browser or confuse the redirect chain, see bug 1080873
// B) does not take place.
TEST_F(RedirectTest, NoHttpToFile) {
  ASSERT_TRUE(test_server_.Start());
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("http_to_file.html");
  GURL file_url = net::FilePathToFileURL(test_file);

  GURL initial_url = test_server_.GetURL(
      "client-redirect?" + file_url.spec());

  NavigateToURL(initial_url);
  // UITest will check for crashes. We make sure the title doesn't match the
  // title from the file, because the nav should not have taken place.
  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  std::wstring actual_title;
  ASSERT_TRUE(tab_proxy->GetTabTitle(&actual_title));
  EXPECT_NE("File!", WideToUTF8(actual_title));
}

// Ensures that non-user initiated location changes (within page) are
// flagged as client redirects. See bug 1139823.
TEST_F(RedirectTest, ClientFragments) {
  ASSERT_TRUE(test_server_.Start());

  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("ref_redirect.html");
  GURL first_url = net::FilePathToFileURL(test_file);
  std::vector<GURL> redirects;

  NavigateToURL(first_url);

  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
  EXPECT_EQ(1U, redirects.size());
  EXPECT_EQ(first_url.spec() + "#myanchor", redirects[0].spec());
}

// TODO(timsteele): This is disabled because our current testserver can't
// handle multiple requests in parallel, making it hang on the first request
// to /slow?60. It's unable to serve our second request for files/title2.html
// until /slow? completes, which doesn't give the desired behavior. We could
// alternatively load the second page from disk, but we would need to start
// the browser for this testcase with --process-per-tab, and I don't think
// we can do this at test-case-level granularity at the moment.
// http://crbug.com/45056
TEST_F(RedirectTest,
       DISABLED_ClientCancelledByNewNavigationAfterProvisionalLoad) {
  // We want to initiate a second navigation after the provisional load for
  // the client redirect destination has started, but before this load is
  // committed. To achieve this, we tell the browser to load a slow page,
  // which causes it to start a provisional load, and while it is waiting
  // for the response (which means it hasn't committed the load for the client
  // redirect destination page yet), we issue a new navigation request.
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL("files/title2.html");
  GURL slow = test_server_.GetURL("slow?60");
  GURL first_url = test_server_.GetURL(
      "client-redirect?" + slow.spec());
  std::vector<GURL> redirects;

  NavigateToURL(first_url);
  // We don't sleep here - the first navigation won't have been committed yet
  // because we told the server to wait a minute. This means the browser has
  // started it's provisional load for the client redirect destination page but
  // hasn't completed. Our time is now!
  NavigateToURL(final_url);

  std::wstring tab_title;
  std::wstring final_url_title = UTF8ToWide("Title Of Awesomeness");
  // Wait till the final page has been loaded.
  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
    ASSERT_TRUE(tab_proxy.get());
    ASSERT_TRUE(tab_proxy->GetTabTitle(&tab_title));
    if (tab_title == final_url_title) {
      ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
      break;
    }
  }

  // Check to make sure the navigation did in fact take place and we are
  // at the expected page.
  EXPECT_EQ(final_url_title, tab_title);

  bool final_navigation_not_redirect = true;
  // Check to make sure our request for files/title2.html doesn't get flagged
  // as a client redirect from the first (/client-redirect?) page.
  for (std::vector<GURL>::iterator it = redirects.begin();
       it != redirects.end(); ++it) {
    if (final_url.spec() == it->spec()) {
      final_navigation_not_redirect = false;
      break;
    }
  }
  EXPECT_TRUE(final_navigation_not_redirect);
}

}  // namespace
<commit_msg>Marking RedirectTest.Client as FLAKY<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Navigates the browser to server and client redirect pages and makes sure
// that the correct redirects are reflected in the history database. Errors
// here might indicate that WebKit changed the calls our glue layer gets in
// the case of redirects. It may also mean problems with the history system.

#include "base/file_util.h"
#include "base/platform_thread.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "views/event.h"

namespace {

class RedirectTest : public UITest {
 public:
  RedirectTest()
      : test_server_(net::TestServer::TYPE_HTTP,
                     FilePath(FILE_PATH_LITERAL("chrome/test/data"))) {
  }

 protected:
  net::TestServer test_server_;
};

// Tests a single server redirect
TEST_F(RedirectTest, Server) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  GURL first_url = test_server_.GetURL(
      "server-redirect?" + final_url.spec());

  NavigateToURL(first_url);

  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());

  std::vector<GURL> redirects;
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));

  ASSERT_EQ(1U, redirects.size());
  EXPECT_EQ(final_url.spec(), redirects[0].spec());
}

// Tests a single client redirect.
// Flaky: see crbug.com/55380
TEST_F(RedirectTest, FLAKY_Client) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  GURL first_url = test_server_.GetURL(
      "client-redirect?" + final_url.spec());

  // The client redirect appears as two page visits in the browser.
  NavigateToURLBlockUntilNavigationsComplete(first_url, 2);

  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());

  std::vector<GURL> redirects;
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));

  ASSERT_EQ(1U, redirects.size());
  EXPECT_EQ(final_url.spec(), redirects[0].spec());

  // The address bar should display the final URL.
  GURL tab_url;
  EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
  EXPECT_TRUE(final_url == tab_url);

  // Navigate one more time.
  NavigateToURLBlockUntilNavigationsComplete(first_url, 2);

  // The address bar should still display the final URL.
  EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
  EXPECT_TRUE(final_url == tab_url);
}

TEST_F(RedirectTest, ClientEmptyReferer) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("file_client_redirect.html");
  GURL first_url = net::FilePathToFileURL(test_file);

  // The client redirect appears as two page visits in the browser.
  NavigateToURLBlockUntilNavigationsComplete(first_url, 2);

  std::vector<GURL> redirects;
  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
  ASSERT_EQ(1U, redirects.size());
  EXPECT_EQ(final_url.spec(), redirects[0].spec());
}

// Tests to make sure a location change when a pending redirect exists isn't
// flagged as a redirect.
#if defined(OS_MACOSX)
// SimulateOSClick is broken on the Mac: http://crbug.com/45162
#define MAYBE_ClientCancelled DISABLED_ClientCancelled
#elif defined(OS_WIN)
// http://crbug.com/53091
#define MAYBE_ClientCancelled FAILS_ClientCancelled
#else
#define MAYBE_ClientCancelled ClientCancelled
#endif

TEST_F(RedirectTest, MAYBE_ClientCancelled) {
  FilePath first_path(test_data_directory_);
  first_path = first_path.AppendASCII("cancelled_redirect_test.html");
  ASSERT_TRUE(file_util::AbsolutePath(&first_path));
  GURL first_url = net::FilePathToFileURL(first_path);

  NavigateToURLBlockUntilNavigationsComplete(first_url, 1);

  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  ASSERT_TRUE(window.get());
  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  int64 last_nav_time = 0;
  EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
  // Simulate a click to force to make a user-initiated location change;
  // otherwise, a non user-initiated in-page location change will be treated
  // as client redirect and the redirect will be recoreded, which can cause
  // this test failed.
  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(browser->BringToFront());
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  ASSERT_TRUE(
      window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                              views::Event::EF_LEFT_BUTTON_DOWN));
  EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));

  std::vector<GURL> redirects;
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));

  // There should be no redirects from first_url, because the anchor location
  // change that occurs should not be flagged as a redirect and the meta-refresh
  // won't have fired yet.
  ASSERT_EQ(0U, redirects.size());
  GURL current_url;
  ASSERT_TRUE(tab_proxy->GetCurrentURL(&current_url));

  // Need to test final path and ref separately since constructing a file url
  // containing an anchor using FilePathToFileURL will escape the anchor as
  // %23, but in current_url the anchor will be '#'.
  std::string final_ref = "myanchor";
  FilePath current_path;
  ASSERT_TRUE(net::FileURLToFilePath(current_url, &current_path));
  ASSERT_TRUE(file_util::AbsolutePath(&current_path));
  // Path should remain unchanged.
  EXPECT_EQ(StringToLowerASCII(first_path.value()),
            StringToLowerASCII(current_path.value()));
  EXPECT_EQ(final_ref, current_url.ref());
}

// Tests a client->server->server redirect
TEST_F(RedirectTest, ClientServerServer) {
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL(std::string());
  GURL next_to_last = test_server_.GetURL(
      "server-redirect?" + final_url.spec());
  GURL second_url = test_server_.GetURL(
      "server-redirect?" + next_to_last.spec());
  GURL first_url = test_server_.GetURL(
      "client-redirect?" + second_url.spec());
  std::vector<GURL> redirects;

  // We need the sleep for the client redirects, because it appears as two
  // page visits in the browser.
  NavigateToURL(first_url);

  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
    ASSERT_TRUE(tab_proxy.get());
    ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
    if (!redirects.empty())
      break;
  }

  ASSERT_EQ(3U, redirects.size());
  EXPECT_EQ(second_url.spec(), redirects[0].spec());
  EXPECT_EQ(next_to_last.spec(), redirects[1].spec());
  EXPECT_EQ(final_url.spec(), redirects[2].spec());
}

// Tests that the "#reference" gets preserved across server redirects.
TEST_F(RedirectTest, ServerReference) {
  ASSERT_TRUE(test_server_.Start());

  const std::string ref("reference");

  GURL final_url = test_server_.GetURL(std::string());
  GURL initial_url = test_server_.GetURL(
      "server-redirect?" + final_url.spec() + "#" + ref);

  NavigateToURL(initial_url);

  GURL url = GetActiveTabURL();
  EXPECT_EQ(ref, url.ref());
}

// Test that redirect from http:// to file:// :
// A) does not crash the browser or confuse the redirect chain, see bug 1080873
// B) does not take place.
TEST_F(RedirectTest, NoHttpToFile) {
  ASSERT_TRUE(test_server_.Start());
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("http_to_file.html");
  GURL file_url = net::FilePathToFileURL(test_file);

  GURL initial_url = test_server_.GetURL(
      "client-redirect?" + file_url.spec());

  NavigateToURL(initial_url);
  // UITest will check for crashes. We make sure the title doesn't match the
  // title from the file, because the nav should not have taken place.
  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  std::wstring actual_title;
  ASSERT_TRUE(tab_proxy->GetTabTitle(&actual_title));
  EXPECT_NE("File!", WideToUTF8(actual_title));
}

// Ensures that non-user initiated location changes (within page) are
// flagged as client redirects. See bug 1139823.
TEST_F(RedirectTest, ClientFragments) {
  ASSERT_TRUE(test_server_.Start());

  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("ref_redirect.html");
  GURL first_url = net::FilePathToFileURL(test_file);
  std::vector<GURL> redirects;

  NavigateToURL(first_url);

  scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
  EXPECT_EQ(1U, redirects.size());
  EXPECT_EQ(first_url.spec() + "#myanchor", redirects[0].spec());
}

// TODO(timsteele): This is disabled because our current testserver can't
// handle multiple requests in parallel, making it hang on the first request
// to /slow?60. It's unable to serve our second request for files/title2.html
// until /slow? completes, which doesn't give the desired behavior. We could
// alternatively load the second page from disk, but we would need to start
// the browser for this testcase with --process-per-tab, and I don't think
// we can do this at test-case-level granularity at the moment.
// http://crbug.com/45056
TEST_F(RedirectTest,
       DISABLED_ClientCancelledByNewNavigationAfterProvisionalLoad) {
  // We want to initiate a second navigation after the provisional load for
  // the client redirect destination has started, but before this load is
  // committed. To achieve this, we tell the browser to load a slow page,
  // which causes it to start a provisional load, and while it is waiting
  // for the response (which means it hasn't committed the load for the client
  // redirect destination page yet), we issue a new navigation request.
  ASSERT_TRUE(test_server_.Start());

  GURL final_url = test_server_.GetURL("files/title2.html");
  GURL slow = test_server_.GetURL("slow?60");
  GURL first_url = test_server_.GetURL(
      "client-redirect?" + slow.spec());
  std::vector<GURL> redirects;

  NavigateToURL(first_url);
  // We don't sleep here - the first navigation won't have been committed yet
  // because we told the server to wait a minute. This means the browser has
  // started it's provisional load for the client redirect destination page but
  // hasn't completed. Our time is now!
  NavigateToURL(final_url);

  std::wstring tab_title;
  std::wstring final_url_title = UTF8ToWide("Title Of Awesomeness");
  // Wait till the final page has been loaded.
  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
    ASSERT_TRUE(tab_proxy.get());
    ASSERT_TRUE(tab_proxy->GetTabTitle(&tab_title));
    if (tab_title == final_url_title) {
      ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
      break;
    }
  }

  // Check to make sure the navigation did in fact take place and we are
  // at the expected page.
  EXPECT_EQ(final_url_title, tab_title);

  bool final_navigation_not_redirect = true;
  // Check to make sure our request for files/title2.html doesn't get flagged
  // as a client redirect from the first (/client-redirect?) page.
  for (std::vector<GURL>::iterator it = redirects.begin();
       it != redirects.end(); ++it) {
    if (final_url.spec() == it->spec()) {
      final_navigation_not_redirect = false;
      break;
    }
  }
  EXPECT_TRUE(final_navigation_not_redirect);
}

}  // namespace
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/sbe/p9_sbe_ext_defs.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p9_sbe_ext_defs.H
/// @brief This file will has structures and constants that can be treated as
//         the external interfaces of the SBE.

#ifndef _P9_SBE_EXT_DEFS_H_
#define _P9_SBE_EXT_DEFS_H_

/// @brief A structure (bitfield) representing the SBE messaging register
typedef union sbeMsgReg
{
    struct
    {
#ifdef _BIG_ENDIAN
        uint32_t sbeBooted : 1; ///< SBE control loop initialized
        uint32_t reserved1 : 3; ///< Reserved
        uint32_t prevState : 4; ///< Previous SBE state
        uint32_t currState : 4; ///< Current SBE state
        uint32_t majorStep : 8; ///< Last major istep executed by the SBE
        uint32_t minorStep : 6; ///< Last minor istep executed by the SBE
        uint32_t reserved2 : 6; ///< Reserved
#else
        uint32_t reserved2 : 6; ///< Reserved
        uint32_t minorStep : 6; ///< Last minor istep executed by the SBE
        uint32_t majorStep : 8; ///< Last major istep executed by the SBE
        uint32_t currState : 4; ///< Current SBE state
        uint32_t prevState : 4; ///< Previous SBE state
        uint32_t reserved1 : 3; ///< Reserved
        uint32_t sbeBooted : 1; ///< SBE control loop initialized
#endif
    };
    uint32_t reg; ///< The complete SBE messaging register as a uint32
} sbeMsgReg_t;

/**
 * @brief Enumeration of SBE states
*/
typedef enum sbeState
{
    SBE_STATE_UNKNOWN = 0x0, // Unkown, initial state
    SBE_STATE_IPLING  = 0x1, // IPL'ing - autonomous mode (transient)
    SBE_STATE_ISTEP   = 0x2, // ISTEP - Running IPL by steps (transient)
    SBE_STATE_MPIPL   = 0x3, // MPIPL
    SBE_STATE_RUNTIME = 0x4, // SBE Runtime
    SBE_STATE_DMT     = 0x5, // Dead Man Timer State (transient)
    SBE_STATE_DUMP    = 0x6, // Dumping
    SBE_STATE_FAILURE = 0x7, // Internal SBE failure
    SBE_STATE_QUIESCE = 0x8, // Final state - needs SBE reset to get out

    // Max States, Always keep it at the last of the enum and sequential
    SBE_MAX_STATE     = 0x9,
    // Don't count this in the state, just to intialize the state variables
    SBE_INVALID_STATE = 0xF,
} sbeState_t;

#endif //_P9_SBE_EXT_DEFS_H_
<commit_msg>Support for async bit<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/sbe/p9_sbe_ext_defs.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p9_sbe_ext_defs.H
/// @brief This file will has structures and constants that can be treated as
//         the external interfaces of the SBE.

#ifndef _P9_SBE_EXT_DEFS_H_
#define _P9_SBE_EXT_DEFS_H_

/// @brief A structure (bitfield) representing the SBE messaging register
typedef union sbeMsgReg
{
    struct
    {
#ifdef _BIG_ENDIAN
        uint32_t sbeBooted : 1; ///< SBE control loop initialized
        uint32_t asyncFFDC : 1; // < async ffdc present on sbe
        uint32_t reserved1 : 2; ///< Reserved
        uint32_t prevState : 4; ///< Previous SBE state
        uint32_t currState : 4; ///< Current SBE state
        uint32_t majorStep : 8; ///< Last major istep executed by the SBE
        uint32_t minorStep : 6; ///< Last minor istep executed by the SBE
        uint32_t reserved2 : 6; ///< Reserved
#else
        uint32_t reserved2 : 6; ///< Reserved
        uint32_t minorStep : 6; ///< Last minor istep executed by the SBE
        uint32_t majorStep : 8; ///< Last major istep executed by the SBE
        uint32_t currState : 4; ///< Current SBE state
        uint32_t prevState : 4; ///< Previous SBE state
        uint32_t reserved1 : 2; ///< Reserved
        uint32_t asyncFFDC : 1; // < async ffdc present on sbe
        uint32_t sbeBooted : 1; ///< SBE control loop initialized
#endif
    };
    uint32_t reg; ///< The complete SBE messaging register as a uint32
} sbeMsgReg_t;

/**
 * @brief Enumeration of SBE states
*/
typedef enum sbeState
{
    SBE_STATE_UNKNOWN = 0x0, // Unkown, initial state
    SBE_STATE_IPLING  = 0x1, // IPL'ing - autonomous mode (transient)
    SBE_STATE_ISTEP   = 0x2, // ISTEP - Running IPL by steps (transient)
    SBE_STATE_MPIPL   = 0x3, // MPIPL
    SBE_STATE_RUNTIME = 0x4, // SBE Runtime
    SBE_STATE_DMT     = 0x5, // Dead Man Timer State (transient)
    SBE_STATE_DUMP    = 0x6, // Dumping
    SBE_STATE_FAILURE = 0x7, // Internal SBE failure
    SBE_STATE_QUIESCE = 0x8, // Final state - needs SBE reset to get out

    // Max States, Always keep it at the last of the enum and sequential
    SBE_MAX_STATE     = 0x9,
    // Don't count this in the state, just to intialize the state variables
    SBE_INVALID_STATE = 0xF,
} sbeState_t;

#endif //_P9_SBE_EXT_DEFS_H_
<|endoftext|>


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

#include "chrome_frame/test/test_mock_with_web_server.h"

#include "base/scoped_variant_win.h"
#include "base/utf_string_conversions.h"
#include "chrome_frame/test/simulate_input.h"
#include "chrome_frame/test/test_with_web_server.h"

using chrome_frame_test::CloseIeAtEndOfScope;
using chrome_frame_test::ComStackObjectWithUninitialize;
using chrome_frame_test::kChromeFrameLongNavigationTimeoutInSeconds;
using testing::_;

namespace {

// The same as MockWebBrowserEventSink, except OnDocumentComplete is added.
// This class can be merged with its base class, but it would require some
// modification to most of the test cases.
class MockWebBrowserEventSink
    : public chrome_frame_test::MockWebBrowserEventSink {
 public:
  // This method is called for each OnDocumentComplete event in which the
  // document is rendered by IE and not CF.
  MOCK_METHOD1(OnIELoad, void (const wchar_t* url));  // NOLINT

  // The OnDocumentComplete event is received for every document load,
  // regardless of whether IE or CF is hosting. This method will call
  // OnIELoad iff the document was loaded in an IE renderer.
  STDMETHOD_(void, OnDocumentComplete)(IDispatch* dispatch,
                                       VARIANT* url_variant) {
    ScopedVariant url;
    if (url_variant)
      url.Reset(*url_variant);
    // To determine if the document is loaded in IE or CF, check if
    // IHTMLDocument2 can be retrieved. If so, call OnIELoad.
    ScopedComPtr<IWebBrowser2> web_browser2;
    web_browser2.QueryFrom(dispatch);
    EXPECT_TRUE(web_browser2);
    if (web_browser2) {
      ScopedComPtr<IDispatch> doc_dispatch;
      HRESULT hr = web_browser2->get_Document(doc_dispatch.Receive());
      EXPECT_HRESULT_SUCCEEDED(hr);
      EXPECT_TRUE(doc_dispatch);
      if (doc_dispatch) {
        ScopedComPtr<IHTMLDocument2> doc;
        doc.QueryFrom(doc_dispatch);
        if (doc) {
          OnIELoad(V_BSTR(&url));
        }
      }
    }
  }
};

// Fixture for tests which ensure that Chrome Frame does not interfere with
// normal IE operation.
// TODO(kkania): Move this fixture to test_mock_with_web_server.h and change
// those tests to use this too.
class NoInterferenceTest : public ChromeFrameTestWithWebServer {
 protected:
  // Launches IE and navigates to |url|, then waits until receiving a quit
  // message or the timeout is exceeded.
  void LaunchIEAndNavigate(const std::wstring& url) {
    EXPECT_CALL(mock_, OnQuit())
        .Times(testing::AtMost(1))
        .WillOnce(QUIT_LOOP(loop_));
    HRESULT hr = mock_.LaunchIEAndNavigate(url);
    ASSERT_HRESULT_SUCCEEDED(hr);
    if (hr == S_FALSE)
      return;

    ASSERT_TRUE(mock_.web_browser2() != NULL);
    loop_.RunFor(kChromeFrameLongNavigationTimeoutInSeconds);
    mock_.Uninitialize();
  }

  const std::wstring GetTestUrl(const wchar_t* relative_path) {
    std::wstring path = std::wstring(L"files/no_interference/") +
        relative_path;
    return UTF8ToWide(server_.Resolve(path.c_str()).spec());
  }

  const std::wstring empty_page_url() {
    return GetTestUrl(L"empty.html");
  }

  // Returns the url for a page with a single link, which points to the
  // empty page.
  const std::wstring link_page_url() {
    return GetTestUrl(L"link.html");
  }

  CloseIeAtEndOfScope last_resort_close_ie;
  chrome_frame_test::TimedMsgLoop loop_;
  CComObjectStackEx<testing::StrictMock<MockWebBrowserEventSink> > mock_;
};

ACTION_P(ExpectIERendererWindowHasFocus, mock) {
  mock->ExpectIERendererWindowHasFocus();
}

ACTION_P6(DelaySendMouseClickToIE, mock, loop, delay, x, y, button) {
  loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(mock,
      &MockWebBrowserEventSink::SendMouseClickToIE, x, y, button), delay);
}

ACTION_P2(OpenContextMenu, loop, delay) {
  loop->PostDelayedTask(FROM_HERE, NewRunnableFunction(
      simulate_input::SendScanCode, VK_F10, simulate_input::SHIFT), delay);
}

ACTION_P3(SelectItem, loop, delay, index) {
  chrome_frame_test::DelaySendExtendedKeysEnter(loop, delay, VK_DOWN, index + 1,
      simulate_input::NONE);
}

// A new IE renderer window should have focus.
TEST_F(NoInterferenceTest, FLAKY_SimpleFocus) {
  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          ExpectIERendererWindowHasFocus(&mock_),
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(empty_page_url());
}

// Javascript window.open should open a new window with an IE renderer.
TEST_F(NoInterferenceTest, FLAKY_JavascriptWindowOpen) {
  const std::wstring kWindowOpenUrl = GetTestUrl(L"window_open.html");
  ComStackObjectWithUninitialize<
      testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;

  mock_.ExpectNavigationInIE(kWindowOpenUrl);
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kWindowOpenUrl)))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,
                                  simulate_input::LEFT),
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,
                                  simulate_input::LEFT)));

  EXPECT_CALL(mock_, OnNewWindow3(_, _, _, _, _));

  EXPECT_CALL(mock_, OnNewBrowserWindow(_, _))
      .WillOnce(testing::WithArgs<0>(testing::Invoke(CreateFunctor(
          &new_window_mock, &MockWebBrowserEventSink::Attach))));

  EXPECT_CALL(new_window_mock, OnBeforeNavigate2(_,
                  testing::Field(&VARIANT::bstrVal,
                  testing::StrCaseEq(empty_page_url())),
                  _, _, _, _, _));

  EXPECT_CALL(new_window_mock, OnFileDownload(VARIANT_TRUE, _))
      .Times(testing::AnyNumber());

  EXPECT_CALL(new_window_mock, OnNavigateComplete2(_,
                            testing::Field(&VARIANT::bstrVal,
                            testing::StrCaseEq(empty_page_url()))))
      .WillOnce(testing::DoAll(
          testing::InvokeWithoutArgs(CreateFunctor(&new_window_mock,
              &chrome_frame_test::MockWebBrowserEventSink::ExpectAddressBarUrl,
              empty_page_url())),
          DelayCloseBrowserMock(&loop_, 2000, &new_window_mock)));

  // The DocumentComplete at times fires twice for new windows. Hack to account
  // for that.
  EXPECT_CALL(new_window_mock,
              OnIELoad(testing::StrCaseEq(empty_page_url())))
      .Times(testing::AtMost(2));

  EXPECT_CALL(new_window_mock, OnQuit())
      .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &mock_));

  LaunchIEAndNavigate(kWindowOpenUrl);
}

// Redirecting with window.location in Javascript should work.
TEST_F(NoInterferenceTest, JavascriptRedirect) {
  const std::wstring kRedirectUrl = GetTestUrl(L"javascript_redirect.html");
  mock_.ExpectNavigationInIE(kRedirectUrl);
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kRedirectUrl)))
      .WillOnce(VerifyAddressBarUrl(&mock_));

  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(kRedirectUrl);
}

TEST_F(NoInterferenceTest, FLAKY_FollowLink) {
  mock_.ExpectNavigationInIE(link_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,
                                  simulate_input::LEFT),
          DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),
          DelaySendScanCode(&loop_, 1000, VK_RETURN, simulate_input::NONE)));

  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(link_page_url());
}

TEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpen) {
  mock_.ExpectNavigationInIE(link_page_url());
  // Focus the renderer window by clicking and then tab once to highlight the
  // link.
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,
                                  simulate_input::LEFT),
          DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),
          OpenContextMenu(&loop_, 1000),
          SelectItem(&loop_, 1500, 0)));

  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(link_page_url());
}

TEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpenInNewWindow) {
  ComStackObjectWithUninitialize<
      testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;
  int open_new_window_index = 2;
  if (chrome_frame_test::GetInstalledIEVersion() == IE_6)
    open_new_window_index = 1;

  // Focus the renderer window by clicking and then tab once to highlight the
  // link.
  mock_.ExpectNavigationInIE(link_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,
                                  simulate_input::LEFT),
          DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),
          OpenContextMenu(&loop_, 1000),
          SelectItem(&loop_, 1500, open_new_window_index)));

  mock_.ExpectNewWindowWithIE(empty_page_url(), &new_window_mock);
  // The DocumentComplete at times fires twice for new windows. Hack to account
  // for that.
  // TODO(kkania): Verifying the address bar is flaky with this, at least
  // on XP ie6. Fix.
  EXPECT_CALL(new_window_mock,
              OnIELoad(testing::StrCaseEq(empty_page_url())))
      .Times(testing::AtMost(2))
      .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &new_window_mock));

  EXPECT_CALL(new_window_mock, OnQuit()).WillOnce(CloseBrowserMock(&mock_));

  LaunchIEAndNavigate(link_page_url());
}

}  // namespace<commit_msg>Disable a crashing test: NoInterferenceTest.JavascriptWindowOpen<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome_frame/test/test_mock_with_web_server.h"

#include "base/scoped_variant_win.h"
#include "base/utf_string_conversions.h"
#include "chrome_frame/test/simulate_input.h"
#include "chrome_frame/test/test_with_web_server.h"

using chrome_frame_test::CloseIeAtEndOfScope;
using chrome_frame_test::ComStackObjectWithUninitialize;
using chrome_frame_test::kChromeFrameLongNavigationTimeoutInSeconds;
using testing::_;

namespace {

// The same as MockWebBrowserEventSink, except OnDocumentComplete is added.
// This class can be merged with its base class, but it would require some
// modification to most of the test cases.
class MockWebBrowserEventSink
    : public chrome_frame_test::MockWebBrowserEventSink {
 public:
  // This method is called for each OnDocumentComplete event in which the
  // document is rendered by IE and not CF.
  MOCK_METHOD1(OnIELoad, void (const wchar_t* url));  // NOLINT

  // The OnDocumentComplete event is received for every document load,
  // regardless of whether IE or CF is hosting. This method will call
  // OnIELoad iff the document was loaded in an IE renderer.
  STDMETHOD_(void, OnDocumentComplete)(IDispatch* dispatch,
                                       VARIANT* url_variant) {
    ScopedVariant url;
    if (url_variant)
      url.Reset(*url_variant);
    // To determine if the document is loaded in IE or CF, check if
    // IHTMLDocument2 can be retrieved. If so, call OnIELoad.
    ScopedComPtr<IWebBrowser2> web_browser2;
    web_browser2.QueryFrom(dispatch);
    EXPECT_TRUE(web_browser2);
    if (web_browser2) {
      ScopedComPtr<IDispatch> doc_dispatch;
      HRESULT hr = web_browser2->get_Document(doc_dispatch.Receive());
      EXPECT_HRESULT_SUCCEEDED(hr);
      EXPECT_TRUE(doc_dispatch);
      if (doc_dispatch) {
        ScopedComPtr<IHTMLDocument2> doc;
        doc.QueryFrom(doc_dispatch);
        if (doc) {
          OnIELoad(V_BSTR(&url));
        }
      }
    }
  }
};

// Fixture for tests which ensure that Chrome Frame does not interfere with
// normal IE operation.
// TODO(kkania): Move this fixture to test_mock_with_web_server.h and change
// those tests to use this too.
class NoInterferenceTest : public ChromeFrameTestWithWebServer {
 protected:
  // Launches IE and navigates to |url|, then waits until receiving a quit
  // message or the timeout is exceeded.
  void LaunchIEAndNavigate(const std::wstring& url) {
    EXPECT_CALL(mock_, OnQuit())
        .Times(testing::AtMost(1))
        .WillOnce(QUIT_LOOP(loop_));
    HRESULT hr = mock_.LaunchIEAndNavigate(url);
    ASSERT_HRESULT_SUCCEEDED(hr);
    if (hr == S_FALSE)
      return;

    ASSERT_TRUE(mock_.web_browser2() != NULL);
    loop_.RunFor(kChromeFrameLongNavigationTimeoutInSeconds);
    mock_.Uninitialize();
  }

  const std::wstring GetTestUrl(const wchar_t* relative_path) {
    std::wstring path = std::wstring(L"files/no_interference/") +
        relative_path;
    return UTF8ToWide(server_.Resolve(path.c_str()).spec());
  }

  const std::wstring empty_page_url() {
    return GetTestUrl(L"empty.html");
  }

  // Returns the url for a page with a single link, which points to the
  // empty page.
  const std::wstring link_page_url() {
    return GetTestUrl(L"link.html");
  }

  CloseIeAtEndOfScope last_resort_close_ie;
  chrome_frame_test::TimedMsgLoop loop_;
  CComObjectStackEx<testing::StrictMock<MockWebBrowserEventSink> > mock_;
};

ACTION_P(ExpectIERendererWindowHasFocus, mock) {
  mock->ExpectIERendererWindowHasFocus();
}

ACTION_P6(DelaySendMouseClickToIE, mock, loop, delay, x, y, button) {
  loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(mock,
      &MockWebBrowserEventSink::SendMouseClickToIE, x, y, button), delay);
}

ACTION_P2(OpenContextMenu, loop, delay) {
  loop->PostDelayedTask(FROM_HERE, NewRunnableFunction(
      simulate_input::SendScanCode, VK_F10, simulate_input::SHIFT), delay);
}

ACTION_P3(SelectItem, loop, delay, index) {
  chrome_frame_test::DelaySendExtendedKeysEnter(loop, delay, VK_DOWN, index + 1,
      simulate_input::NONE);
}

// A new IE renderer window should have focus.
TEST_F(NoInterferenceTest, FLAKY_SimpleFocus) {
  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          ExpectIERendererWindowHasFocus(&mock_),
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(empty_page_url());
}

// Javascript window.open should open a new window with an IE renderer.
// Disabled because of crashes.
// http://code.google.com/p/chromium/issues/detail?id=48175
TEST_F(NoInterferenceTest, DISABLED_JavascriptWindowOpen) {
  const std::wstring kWindowOpenUrl = GetTestUrl(L"window_open.html");
  ComStackObjectWithUninitialize<
      testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;

  mock_.ExpectNavigationInIE(kWindowOpenUrl);
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kWindowOpenUrl)))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,
                                  simulate_input::LEFT),
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,
                                  simulate_input::LEFT)));

  EXPECT_CALL(mock_, OnNewWindow3(_, _, _, _, _));

  EXPECT_CALL(mock_, OnNewBrowserWindow(_, _))
      .WillOnce(testing::WithArgs<0>(testing::Invoke(CreateFunctor(
          &new_window_mock, &MockWebBrowserEventSink::Attach))));

  EXPECT_CALL(new_window_mock, OnBeforeNavigate2(_,
                  testing::Field(&VARIANT::bstrVal,
                  testing::StrCaseEq(empty_page_url())),
                  _, _, _, _, _));

  EXPECT_CALL(new_window_mock, OnFileDownload(VARIANT_TRUE, _))
      .Times(testing::AnyNumber());

  EXPECT_CALL(new_window_mock, OnNavigateComplete2(_,
                            testing::Field(&VARIANT::bstrVal,
                            testing::StrCaseEq(empty_page_url()))))
      .WillOnce(testing::DoAll(
          testing::InvokeWithoutArgs(CreateFunctor(&new_window_mock,
              &chrome_frame_test::MockWebBrowserEventSink::ExpectAddressBarUrl,
              empty_page_url())),
          DelayCloseBrowserMock(&loop_, 2000, &new_window_mock)));

  // The DocumentComplete at times fires twice for new windows. Hack to account
  // for that.
  EXPECT_CALL(new_window_mock,
              OnIELoad(testing::StrCaseEq(empty_page_url())))
      .Times(testing::AtMost(2));

  EXPECT_CALL(new_window_mock, OnQuit())
      .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &mock_));

  LaunchIEAndNavigate(kWindowOpenUrl);
}

// Redirecting with window.location in Javascript should work.
TEST_F(NoInterferenceTest, JavascriptRedirect) {
  const std::wstring kRedirectUrl = GetTestUrl(L"javascript_redirect.html");
  mock_.ExpectNavigationInIE(kRedirectUrl);
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kRedirectUrl)))
      .WillOnce(VerifyAddressBarUrl(&mock_));

  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(kRedirectUrl);
}

TEST_F(NoInterferenceTest, FLAKY_FollowLink) {
  mock_.ExpectNavigationInIE(link_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,
                                  simulate_input::LEFT),
          DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),
          DelaySendScanCode(&loop_, 1000, VK_RETURN, simulate_input::NONE)));

  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(link_page_url());
}

TEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpen) {
  mock_.ExpectNavigationInIE(link_page_url());
  // Focus the renderer window by clicking and then tab once to highlight the
  // link.
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,
                                  simulate_input::LEFT),
          DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),
          OpenContextMenu(&loop_, 1000),
          SelectItem(&loop_, 1500, 0)));

  mock_.ExpectNavigationInIE(empty_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))
      .WillOnce(testing::DoAll(
          VerifyAddressBarUrl(&mock_),
          CloseBrowserMock(&mock_)));

  LaunchIEAndNavigate(link_page_url());
}

TEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpenInNewWindow) {
  ComStackObjectWithUninitialize<
      testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;
  int open_new_window_index = 2;
  if (chrome_frame_test::GetInstalledIEVersion() == IE_6)
    open_new_window_index = 1;

  // Focus the renderer window by clicking and then tab once to highlight the
  // link.
  mock_.ExpectNavigationInIE(link_page_url());
  EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))
      .WillOnce(testing::DoAll(
          DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,
                                  simulate_input::LEFT),
          DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),
          OpenContextMenu(&loop_, 1000),
          SelectItem(&loop_, 1500, open_new_window_index)));

  mock_.ExpectNewWindowWithIE(empty_page_url(), &new_window_mock);
  // The DocumentComplete at times fires twice for new windows. Hack to account
  // for that.
  // TODO(kkania): Verifying the address bar is flaky with this, at least
  // on XP ie6. Fix.
  EXPECT_CALL(new_window_mock,
              OnIELoad(testing::StrCaseEq(empty_page_url())))
      .Times(testing::AtMost(2))
      .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &new_window_mock));

  EXPECT_CALL(new_window_mock, OnQuit()).WillOnce(CloseBrowserMock(&mock_));

  LaunchIEAndNavigate(link_page_url());
}

}  // namespace
<|endoftext|>