<commit_before>/***************************************************************************
 *  The Kernel-Machine Library                                             *
 *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *
 *                                                                         *
 *  This program is free software; you can redistribute it and/or          *
 *  modify it under the terms of the GNU General Public License            *
 *  as published by the Free Software Foundation; either version 2         *
 *  of the License, or (at your option) any later version.                 *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program; if not, write to the Free Software            *
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *
 ***************************************************************************/

#ifndef REGRESSION_HPP
#define REGRESSION_HPP

#include <boost/mpl/bool.hpp>

namespace mpl = boost::mpl;

namespace kml {

/*! \brief Defines a regression problem.

	\param I the input type
	\param O the output type

	\section example Examples
	\code
    typedef kml::regression< ublas::vector<double>, double > problem;
	\endcode
    The problem defined as above can then be used as a template parameter in
	defining kernel machines:
	\code
    kml::rvm< problem, kml::gaussian > my_machine( 1.6 );
	\endcode

	\sa classification, ranking
	\ingroup problem
*/
// template<typename I, typename O>
// class regression {
// public:
// 	typedef regression type;
// 	typedef I input_type;
// 	typedef O output_type;
// };

template<typename T>
class regression {
public:
	typedef regression type;
	typedef typename T::first_type input_type;
	typedef typename T::second_type output_type;
};

// define is_regression so we can recognise the regression type of problems
// for (partial) specialisations

template<typename T>
struct is_regression: mpl::bool_<false> {};

template<typename T>
struct is_regression<regression<T> >: mpl::bool_<true> {};

}

#endif

<commit_msg>added an example typedef to the regression type<commit_after>/***************************************************************************
 *  The Kernel-Machine Library                                             *
 *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *
 *                                                                         *
 *  This program is free software; you can redistribute it and/or          *
 *  modify it under the terms of the GNU General Public License            *
 *  as published by the Free Software Foundation; either version 2         *
 *  of the License, or (at your option) any later version.                 *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program; if not, write to the Free Software            *
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *
 ***************************************************************************/

#ifndef REGRESSION_HPP
#define REGRESSION_HPP

#include <boost/mpl/bool.hpp>

namespace mpl = boost::mpl;

namespace kml {

/*! \brief Defines a regression problem.

	\param I the input type
	\param O the output type

	\section example Examples
	\code
    typedef kml::regression< ublas::vector<double>, double > problem;
	\endcode
    The problem defined as above can then be used as a template parameter in
	defining kernel machines:
	\code
    kml::rvm< problem, kml::gaussian > my_machine( 1.6 );
	\endcode

	\sa classification, ranking
	\ingroup problem
*/
// template<typename I, typename O>
// class regression {
// public:
// 	typedef regression type;
// 	typedef I input_type;
// 	typedef O output_type;
// };

template<typename T>
class regression {
public:
	typedef regression type;
	typedef typename T example_type;
	typedef typename T::first_type input_type;
	typedef typename T::second_type output_type;
};

// define is_regression so we can recognise the regression type of problems
// for (partial) specialisations

template<typename T>
struct is_regression: mpl::bool_<false> {};

template<typename T>
struct is_regression<regression<T> >: mpl::bool_<true> {};

}

#endif

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id: */

//_________________________________________________________________________
//  Hits class for EMCAL
//  A hit in EMCAL is the sum of all hits in a single segment
//  from a single enterring particle
//*-- Author: Sahal Yacoob (LBL / UCT)
// Based on AliPHOSHit

// --- Standard library ---
#include <Riostream.h>

// --- ROOT system ---

// --- AliRoot header files ---
#include "AliEMCALHit.h"

ClassImp(AliEMCALHit)

//______________________________________________________________________
AliEMCALHit::AliEMCALHit(){
    // Default ctor

    fId      = 0;
    fELOS    = 0.0;
    fTime    = 0.0;
    fPrimary = 0;
    fTrack   = 0;
    fX       = 0.0;
    fY       = 0.0;
    fZ       = 0.0;
    fPx      = 0.0;
    fPy      = 0.0;
    fPz      = 0.0;
    fPe      = 0.0;
    fIparent = 0;
    fIenergy = 0.0;
}
//______________________________________________________________________
AliEMCALHit::AliEMCALHit(const AliEMCALHit & hit) : AliHit(hit){
    // copy ctor

    fId      = hit.fId ;
    fELOS    = hit.fELOS ;
    fPrimary = hit.fPrimary ;
    fTrack   = hit.fTrack ;
    fX       = hit.fX;
    fY       = hit.fY;
    fZ       = hit.fZ;
    fPx       = hit.fPx;
    fPy       = hit.fPy;
    fPz       = hit.fPz;
    fPe       = hit.fPe;
    fIparent = hit.fIparent;
    fIenergy = hit.fIenergy;
    fTime    = hit.fTime  ;
}
//______________________________________________________________________
AliEMCALHit::AliEMCALHit(Int_t shunt, Int_t primary, Int_t track,Int_t iparent, Float_t ienergy, Int_t id,
			 Float_t *hits,Float_t *p):AliHit(shunt, track){
    //
    // Create an EMCAL  hit object
    //
    fX          = hits[0];
    fY          = hits[1];
    fZ          = hits[2];
    fTime       = hits[3] ;
    fId         = id;
    fELOS       = hits[4];
    fPrimary    = primary;
    fPx          = p[0];
    fPy          = p[1];
    fPz          = p[2];
    fPe          = p[3];
    fIparent    = iparent;
    fIenergy    = ienergy;
}

//______________________________________________________________________
Bool_t AliEMCALHit::operator==(AliEMCALHit const &rValue) const{
    // Two hits are identical if they have the same Id and originat
    // from the same enterring Particle
    Bool_t rv = kFALSE;

    if ( (fId == rValue.GetId()) && ( fIparent == rValue.GetIparent()) )
	rv = kTRUE;

    return rv;
}
//______________________________________________________________________
AliEMCALHit AliEMCALHit::operator+(const AliEMCALHit &rValue){
    // Add the energy of the hit

    fELOS += rValue.GetEnergy() ;

    if(rValue.GetTime() < fTime)
      fTime = rValue.GetTime() ;

    return *this;

}
//______________________________________________________________________
ostream& operator << (ostream& out,AliEMCALHit& hit){
    // Print out Id and energy

    out << "AliEMCALHit:";
    out << "id=" <<  hit.GetId();
    out << ", Eloss=" <<  hit.GetEnergy();
    out << ", Time=" << hit.GetTime();
    out << "GeV , Track no.=" << hit.GetPrimary();
    out << ", (xyz)=(" << hit.X()<< ","<< hit.Y()<< ","<<hit.Z()<<") cm";
    out << ", fTrack=" << hit.GetTrack();
    out << ", P=(" << hit.GetPx() << "," << hit.GetPy() << "," << hit.GetPz()
                  << "," <<hit.GetPe() << ") GeV"  ;
    out << ", Enterring particle ID" << hit.GetIparent();
    out << ", Enterring particle initial energy = " << hit.GetIenergy() << " GeV" ;
    out << endl;

    return out;
}
<commit_msg>Changed a comment<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id: */

//_________________________________________________________________________
//  Hits class for EMCAL
//  A hit in EMCAL is the sum of all hits in a tower
//  from a single entering particle
//*-- Author: Sahal Yacoob (LBL / UCT)
// Based on AliPHOSHit

// --- Standard library ---
#include <Riostream.h>

// --- ROOT system ---

// --- AliRoot header files ---
#include "AliEMCALHit.h"

ClassImp(AliEMCALHit)

//______________________________________________________________________
AliEMCALHit::AliEMCALHit(){
    // Default ctor

    fId      = 0;
    fELOS    = 0.0;
    fTime    = 0.0;
    fPrimary = 0;
    fTrack   = 0;
    fX       = 0.0;
    fY       = 0.0;
    fZ       = 0.0;
    fPx      = 0.0;
    fPy      = 0.0;
    fPz      = 0.0;
    fPe      = 0.0;
    fIparent = 0;
    fIenergy = 0.0;
}
//______________________________________________________________________
AliEMCALHit::AliEMCALHit(const AliEMCALHit & hit) : AliHit(hit){
    // copy ctor

    fId      = hit.fId ;
    fELOS    = hit.fELOS ;
    fPrimary = hit.fPrimary ;
    fTrack   = hit.fTrack ;
    fX       = hit.fX;
    fY       = hit.fY;
    fZ       = hit.fZ;
    fPx       = hit.fPx;
    fPy       = hit.fPy;
    fPz       = hit.fPz;
    fPe       = hit.fPe;
    fIparent = hit.fIparent;
    fIenergy = hit.fIenergy;
    fTime    = hit.fTime  ;
}
//______________________________________________________________________
AliEMCALHit::AliEMCALHit(Int_t shunt, Int_t primary, Int_t track,Int_t iparent, Float_t ienergy, Int_t id,
			 Float_t *hits,Float_t *p):AliHit(shunt, track){
    //
    // Create an EMCAL  hit object
    //
    fX          = hits[0];
    fY          = hits[1];
    fZ          = hits[2];
    fTime       = hits[3] ;
    fId         = id;
    fELOS       = hits[4];
    fPrimary    = primary;
    fPx          = p[0];
    fPy          = p[1];
    fPz          = p[2];
    fPe          = p[3];
    fIparent    = iparent;
    fIenergy    = ienergy;
}

//______________________________________________________________________
Bool_t AliEMCALHit::operator==(AliEMCALHit const &rValue) const{
    // Two hits are identical if they have the same Id and originat
    // from the same enterring Particle
    Bool_t rv = kFALSE;

    if ( (fId == rValue.GetId()) && ( fIparent == rValue.GetIparent()) )
	rv = kTRUE;

    return rv;
}
//______________________________________________________________________
AliEMCALHit AliEMCALHit::operator+(const AliEMCALHit &rValue){
    // Add the energy of the hit

    fELOS += rValue.GetEnergy() ;

    if(rValue.GetTime() < fTime)
      fTime = rValue.GetTime() ;

    return *this;

}
//______________________________________________________________________
ostream& operator << (ostream& out,AliEMCALHit& hit){
    // Print out Id and energy

    out << "AliEMCALHit:";
    out << "id=" <<  hit.GetId();
    out << ", Eloss=" <<  hit.GetEnergy();
    out << ", Time=" << hit.GetTime();
    out << "GeV , Track no.=" << hit.GetPrimary();
    out << ", (xyz)=(" << hit.X()<< ","<< hit.Y()<< ","<<hit.Z()<<") cm";
    out << ", fTrack=" << hit.GetTrack();
    out << ", P=(" << hit.GetPx() << "," << hit.GetPy() << "," << hit.GetPz()
                  << "," <<hit.GetPe() << ") GeV"  ;
    out << ", Enterring particle ID" << hit.GetIparent();
    out << ", Enterring particle initial energy = " << hit.GetIenergy() << " GeV" ;
    out << endl;

    return out;
}
<|endoftext|>


<commit_before>#include "itkAddImageFilter.h"
#include "itkWASPCommandLineOption.h"
#include "itkWASPCommandLineParser.h"
#include "itkDivideImageFilter.h"
#include "itkImage.h"
#include "itkMaskImageFilter.h"
#include "itkWASPSegmentationImageFilter.h"
#include "itkNumericSeriesFileNames.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkVectorImage.h"
#include "itkVectorIndexSelectionCastImageFilter.h"

#include <string>
#include <algorithm>
#include <vector>

template <class TFilter>
class CommandIterationUpdate : public itk::Command
{
public:
  typedef CommandIterationUpdate  Self;
  typedef itk::Command            Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  itkNewMacro( Self );
protected:
  CommandIterationUpdate()
  {
  };
public:

  void Execute(itk::Object *caller, const itk::EventObject & event)
  {
    Execute( (const itk::Object *) caller, event);
  }

  void Execute(const itk::Object * object, const itk::EventObject & event)
  {
    const TFilter * filter =
      dynamic_cast<const TFilter *>( object );

    if( typeid( event ) != typeid( itk::IterationEvent ) )
      {
      return;
      }

    std::cout << "Iteration " << filter->GetElapsedIterations()
              << " (of " << filter->GetMaximumNumberOfIterations() << "): ";
    std::cout << filter->GetCurrentConvergenceMeasurement()
              << " (threshold = " << filter->GetConvergenceThreshold()
              << ")" << std::endl;
  }
};

void ConvertToLowerCase( std::string& str )
{
  std::transform( str.begin(), str.end(), str.begin(), tolower );
// You may need to cast the above line to (int(*)(int))
// tolower - this works as is on VC 7.1 but may not work on
// other compilers
}

template <unsigned int ImageDimension>
int ApocritaSegmentation( itk::WASPCommandLineParser *parser )
{
  typedef float                                 PixelType;
  typedef itk::Image<PixelType, ImageDimension> InputImageType;

  typedef unsigned char                         LabelType;
  typedef itk::Image<LabelType, ImageDimension> LabelImageType;

  typedef  itk::WASPSegmentationImageFilter
    <InputImageType, LabelImageType> SegmentationFilterType;
  typename SegmentationFilterType::Pointer segmenter
    = SegmentationFilterType::New();

  typedef CommandIterationUpdate<SegmentationFilterType> CommandType;
  typename CommandType::Pointer observer = CommandType::New();
  segmenter->AddObserver( itk::IterationEvent(), observer );

  /**
   * Initialization
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer initializationOption =
    parser->GetOption( "initialization" );
  if( initializationOption
      && initializationOption->GetNumberOfParameters() < 2 )
    {
    std::cerr << "Incorrect point set option specification." << std::endl;
    std::cerr << "   " << initializationOption->GetDescription() << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    typedef itk::ImageFileReader<InputImageType> ReaderType;
    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(
      ( initializationOption->GetParameter( 0 ) ).c_str() );
    reader->Update();

    segmenter->SetInput( reader->GetOutput() );
    segmenter->SetNumberOfClasses( parser->Convert<unsigned int>(
                                     initializationOption->GetParameter( 1 ) ) );

    std::string initializationStrategy = initializationOption->GetValue();
    ConvertToLowerCase( initializationStrategy );

    if( !initializationStrategy.compare( std::string( "otsu" ) ) )
      {
      segmenter->SetInitializationStrategy( SegmentationFilterType::Otsu );
      }
    else if( !initializationStrategy.compare( std::string( "kmeans" ) ) )
      {
      segmenter->SetInitializationStrategy( SegmentationFilterType::KMeans );
      }
    else if( !initializationStrategy.compare( std::string( "priorprobabilities" ) ) )
      {
      segmenter->SetInitializationStrategy( SegmentationFilterType::PriorProbabilityImages );

      if( initializationOption->GetNumberOfParameters() > 3 )
        {
        segmenter->SetPriorProbabilityWeighting( parser->Convert<float>(
                                                   initializationOption->GetParameter( 3 ) ) );
        }
      if( initializationOption->GetNumberOfParameters() > 2 )
        {
        std::string filename = initializationOption->GetParameter( 2 );

        if( filename.find( std::string( "%" ) ) != std::string::npos )
          {
          itk::NumericSeriesFileNames::Pointer fileNamesCreator =
            itk::NumericSeriesFileNames::New();
          fileNamesCreator->SetStartIndex( 1 );
          fileNamesCreator->SetEndIndex( segmenter->GetNumberOfClasses() );
          fileNamesCreator->SetSeriesFormat( filename.c_str() );
          const std::vector<std::string> & imageNames
            = fileNamesCreator->GetFileNames();
          for( unsigned int k = 0; k < imageNames.size(); k++ )
            {
            typedef itk::ImageFileReader<InputImageType> ReaderType;
            typename ReaderType::Pointer reader = ReaderType::New();
            reader->SetFileName( imageNames[k].c_str() );
            reader->Update();

            segmenter->SetPriorProbabilityImage( k + 1, reader->GetOutput() );
            }
          }
        else
          {
          typedef itk::VectorImage<PixelType, ImageDimension> VectorImageType;
          typedef itk::ImageFileReader<VectorImageType>       ReaderType;
          typename ReaderType::Pointer reader = ReaderType::New();
          reader->SetFileName( filename.c_str() );
          reader->Update();

          if(  reader->GetOutput()->GetNumberOfComponentsPerPixel()
               != segmenter->GetNumberOfClasses() )
            {
            std::cerr << "The number of components does not match the number of classes." << std::endl;
            return EXIT_FAILURE;
            }

          typedef itk::VectorIndexSelectionCastImageFilter
            <VectorImageType, InputImageType> CasterType;
          typename CasterType::Pointer caster = CasterType::New();
          caster->SetInput( reader->GetOutput() );
          for( unsigned int k = 0; k < segmenter->GetNumberOfClasses(); k++ )
            {
            caster->SetIndex( k );
            caster->Update();
            segmenter->SetPriorProbabilityImage( k + 1, caster->GetOutput() );
            }
          }
        }
      }
    else if( !initializationStrategy.compare( std::string( "priorlabelimage" ) ) )
      {
      segmenter->SetInitializationStrategy( SegmentationFilterType::PriorLabelImage );

      if( initializationOption->GetNumberOfParameters() > 3 )
        {
        segmenter->SetPriorProbabilityWeighting( parser->Convert<float>(
                                                   initializationOption->GetParameter( 3 ) ) );
        }
      if( initializationOption->GetNumberOfParameters() > 2 )
        {
        std::string filename = initializationOption->GetParameter( 2 );

        typedef itk::ImageFileReader<LabelImageType> ReaderType;
        typename ReaderType::Pointer reader = ReaderType::New();
        reader->SetFileName( filename.c_str() );
        reader->Update();

        segmenter->SetPriorLabelImage( reader->GetOutput() );
        }
      }
    else
      {
      std::cerr << "Unrecognized initialization strategy request." << std::endl;
      return EXIT_FAILURE;
      }
    }

  /**
   * number of iterations
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer iterationsOption =
    parser->GetOption( "number-of-iterations" );
  if( iterationsOption )
    {
    segmenter->SetMaximumNumberOfIterations( parser->Convert<unsigned int>(
                                               iterationsOption->GetValue() ) );
    }

  /**
   * convergence threshold
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer convergenceOption =
    parser->GetOption( "convergence-threshold" );
  if( convergenceOption )
    {
    segmenter->SetConvergenceThreshold( parser->Convert<float>(
                                          convergenceOption->GetValue() ) );
    }
  std::cout << segmenter->GetConvergenceThreshold() << std::endl;

  /**
   * Mask image
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer maskOption =
    parser->GetOption( "mask-image" );
  if( maskOption && maskOption->GetNumberOfValues() )
    {
    try
      {
      typedef  itk::ImageFileReader<LabelImageType> ReaderType;
      typename ReaderType::Pointer reader = ReaderType::New();
      reader->SetFileName( ( maskOption->GetValue() ).c_str() );
      reader->Update();

      segmenter->SetMaskImage( reader->GetOutput() );
      }
    catch( ... )
      {
      }
    }

  /**
   * BSpline options
   */

  typename itk::WASPCommandLineParser::OptionType::Pointer bsplineOption =
    parser->GetOption( "bspline" );
  if( bsplineOption && bsplineOption->GetNumberOfValues() )
    {
    if( bsplineOption->GetNumberOfParameters() > 0 )
      {
      std::vector<unsigned int> numLevels = parser->ConvertVector<unsigned int>(
          bsplineOption->GetParameter( 0 ) );
      typename SegmentationFilterType::ArrayType numberOfFittingLevels;

      if( numLevels.size() == 1 )
        {
        numberOfFittingLevels.Fill( numLevels[0] );
        }
      else if( numLevels.size() == ImageDimension )
        {
        for( unsigned int d = 0; d < ImageDimension; d++ )
          {
          numberOfFittingLevels[d] = numLevels[d];
          }
        }
      else
        {
        std::cerr << "Incorrect number of levels" << std::endl;
        return EXIT_FAILURE;
        }
      segmenter->SetNumberOfLevels( numberOfFittingLevels );
      }
    if( bsplineOption->GetNumberOfParameters() > 2 )
      {
      segmenter->SetSplineOrder( parser->Convert<unsigned int>(
                                   bsplineOption->GetParameter( 2 ) ) );
      }
    if( bsplineOption->GetNumberOfParameters() > 1 )
      {
      std::vector<unsigned int> array = parser->ConvertVector<unsigned int>(
          bsplineOption->GetParameter( 1 ) );
      typename SegmentationFilterType::ArrayType numberOfControlPoints;
      if( array.size() == 1 )
        {
        numberOfControlPoints.Fill( array[0] + segmenter->GetSplineOrder() );
        }
      else if( array.size() == ImageDimension )
        {
        for( unsigned int d = 0; d < ImageDimension; d++ )
          {
          numberOfControlPoints[d] = array[d] + segmenter->GetSplineOrder();
          }
        }
      else
        {
        std::cerr << "Incorrect mesh resolution" << std::endl;
        return EXIT_FAILURE;
        }
      segmenter->SetNumberOfControlPoints( numberOfControlPoints );
      }
    }

  /**
   * label-sigma
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer labelSigmasOption =
    parser->GetOption( "label-sigma" );
  if( labelSigmasOption && labelSigmasOption->GetNumberOfValues() )
    {
    std::vector<float> labelSigmas;
    for( unsigned int n = 0; n < segmenter->GetNumberOfClasses(); n++ )
      {
      labelSigmas.push_back( 0.0 );
      }
    for( unsigned int n = 0; n < labelSigmasOption->GetNumberOfValues(); n++ )
      {
      unsigned int whichClass = parser->Convert<unsigned int>(
          labelSigmasOption->GetValue( n ) );
      if( whichClass <= labelSigmas.size() )
        {
        labelSigmas[whichClass - 1] = parser->Convert<float>(
            labelSigmasOption->GetParameter( n, 0 ) );
        }
      }
    segmenter->SetPriorLabelSigmas( labelSigmas );
    }

  /**
   * MRF options
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer mrfOption =
    parser->GetOption( "mrf" );
  if( mrfOption && mrfOption->GetNumberOfValues() )
    {
    if( mrfOption->GetNumberOfParameters() > 0 )
      {
      segmenter->SetMRFSmoothingFactor( parser->Convert<float>(
                                          mrfOption->GetParameter( 0 ) ) );
      }
    if( mrfOption->GetNumberOfParameters() > 1 )
      {
      std::vector<unsigned int> array = parser->ConvertVector<unsigned int>(
          mrfOption->GetParameter( 1 ) );
      typename SegmentationFilterType::ArrayType radius;
      if( array.size() == 1 )
        {
        radius.Fill( array[0] );
        }
      else if( array.size() == ImageDimension )
        {
        for( unsigned int d = 0; d < ImageDimension; d++ )
          {
          radius[d] = array[d];
          }
        }
      segmenter->SetMRFRadius( radius );
      }
    if( mrfOption->GetNumberOfParameters() > 2 )
      {
      segmenter->SetMRFSigmoidAlpha( parser->Convert<float>(
                                       mrfOption->GetParameter( 2 ) ) );
      }
    if( mrfOption->GetNumberOfParameters() > 3 )
      {
      segmenter->SetMRFSigmoidBeta( parser->Convert<float>(
                                      mrfOption->GetParameter( 3 ) ) );
      }
    }

  segmenter->Update();

  /**
   * output
   */
  typename itk::WASPCommandLineParser::OptionType::Pointer outputOption =
    parser->GetOption( "output" );
  if( outputOption )
    {
    if( outputOption->GetNumberOfParameters() == 0 )
      {
      typedef  itk::ImageFileWriter<LabelImageType> WriterType;
      typename WriterType::Pointer writer = WriterType::New();
      writer->SetInput( segmenter->GetOutput() );
      writer->SetFileName( ( outputOption->GetValue() ).c_str() );
      writer->Update();
      }
    if( outputOption->GetNumberOfParameters() > 0 )
      {
      typedef  itk::ImageFileWriter<LabelImageType> WriterType;
      typename WriterType::Pointer writer = WriterType::New();
      writer->SetInput( segmenter->GetOutput() );
      writer->SetFileName( ( outputOption->GetParameter( 0 ) ).c_str() );
      writer->Update();
      }
    if( outputOption->GetNumberOfParameters() > 1 )
      {
      std::string filename = outputOption->GetParameter( 1 );

      itk::NumericSeriesFileNames::Pointer fileNamesCreator =
        itk::NumericSeriesFileNames::New();
      fileNamesCreator->SetStartIndex( 1 );
      fileNamesCreator->SetEndIndex( segmenter->GetNumberOfClasses() );
      fileNamesCreator->SetSeriesFormat( filename.c_str() );
      const std::vector<std::string> & imageNames
        = fileNamesCreator->GetFileNames();
      for( unsigned int i = 0; i < imageNames.size(); i++ )
        {
        std::cout << "Writing posterior image (class " << i + 1 << ")" << std::endl;
        typename InputImageType::Pointer probabilityImage
          = segmenter->GetPosteriorImage( i ); // CalculatePosteriorProbabilityImage( i + 1 );

        if( segmenter->GetMaskImage() )
          {
          typedef itk::MaskImageFilter<InputImageType, LabelImageType, InputImageType> MaskerType;
          typename MaskerType::Pointer masker = MaskerType::New();
          masker->SetInput1( probabilityImage );
          masker->SetInput2( segmenter->GetMaskImage() );
          masker->SetOutsideValue( 0 );
          masker->Update();

          probabilityImage = masker->GetOutput();
          }

        typedef  itk::ImageFileWriter<InputImageType> WriterType;
        typename WriterType::Pointer writer = WriterType::New();
        writer->SetInput( probabilityImage );
        writer->SetFileName( imageNames[i].c_str() );
        writer->Update();
        }
      }
    if( outputOption->GetNumberOfParameters() > 2 )
      {
      std::string filename = outputOption->GetParameter( 2 );

      itk::NumericSeriesFileNames::Pointer fileNamesCreator =
        itk::NumericSeriesFileNames::New();
      fileNamesCreator->SetStartIndex( 1 );
      fileNamesCreator->SetEndIndex( segmenter->GetNumberOfClasses() );
      fileNamesCreator->SetSeriesFormat( filename.c_str() );
      const std::vector<std::string> & imageNames
        = fileNamesCreator->GetFileNames();
      for( unsigned int i = 0; i < segmenter->GetNumberOfClasses(); i++ )
        {
        if( segmenter->GetPriorProbabilityImage( i + 1 ) || segmenter->GetPriorLabelImage() )
          {
          std::cout << "Writing B-spline image (class " << i + 1 << ")" << std::endl;

          typename InputImageType::Pointer bsplineImage =
            segmenter->CalculateSmoothIntensityImageFromPriorProbabilityImage( i + 1 );

          typedef  itk::ImageFileWriter<InputImageType> WriterType;
          typename WriterType::Pointer writer = WriterType::New();
          writer->SetInput( bsplineImage );
          writer->SetFileName( imageNames[i].c_str() );
          writer->Update();
          }
        }
      }
    }

  segmenter->Print( std::cout, 5 );

  return EXIT_SUCCESS;
}

void InitializeCommandLineOptions( itk::WASPCommandLineParser *parser )
{
  typedef itk::WASPCommandLineParser::OptionType OptionType;

    {
    std::string description =
      std::string( "\n\tOption 1:  Kmeans[inputImage,numberOfClasses]\n" )
      + std::string( "\tOption 2:  Otsu[inputImage,numberOfClasses]\n" )
      + std::string( "\tOption 3:  PriorProbabilities[inputImage,numberOfClasses," )
      + std::string( "fileSeriesFormat(index=1 to numberOfClasses) or vectorImage,priorWeighting]\n" )
      + std::string( "\tOption 4:  PriorLabelImage[inputImage,numberOfClasses,labelImage,priorWeighting]" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "initialization" );
    option->SetShortName( 'i' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description = std::string( "Number of iterations" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "number-of-iterations" );
    option->SetShortName( 'n' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description = std::string( "Convergence threshold" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "convergence-threshold" );
    option->SetShortName( 'c' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description = std::string( "maskImage" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "mask-image" );
    option->SetShortName( 'x' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description
      = std::string( "[<smoothingFactor>,<radius>,<sigmoidAlpha>,<sigmoidBeta>]" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "mrf" );
    option->SetShortName( 'm' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description
      = std::string( "[<numberOfLevels>,<initialMeshResolution>,<splineOrder>]" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "bspline" );
    option->SetShortName( 'b' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description
      = std::string( "whichLabel[sigma]" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "label-sigma" );
    option->SetShortName( 'l' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description
      = std::string( "[classifiedImage," )
        + std::string( "<posteriorProbabilityImageFileNameFormat>," )
        + std::string( "<bSplineImageFileNameFormat>]" );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "output" );
    option->SetShortName( 'o' );
    option->SetDescription( description );
    parser->AddOption( option );
    }

    {
    std::string description
      = std::string( "Print menu." );

    OptionType::Pointer option = OptionType::New();
    option->SetLongName( "help" );
    option->SetShortName( 'h' );
    option->AddValue( std::string( "0" ) );
    option->SetDescription( description );
    parser->AddOption( option );
    }
}

int main( int argc, char *argv[] )
{
  if( argc < 2 )
    {
    //   std::cout << " WASP : Wieldy Atlas-based Segmentation Protocol -- stinging the segmentation problem in the
    // behind. " << std::endl;
//	std::cout << " wieldy [weel-dee] " << std::endl;
//     std::cout <<  " –adjective: readily wielded or managed, as in use or action. " << std::endl;
    std::cout
    << " Apocrita Segmentation :  A priori classification with registration initialized template assistance "
    << std::endl;
    std::cout << "Usage: " << argv[0] << " imageDimension args" << std::endl;
    std::cout << "call: " << argv[0] << " -h " << std::endl;
    std::cout << " this program has not been evaluated " << std::endl;
    exit( 1 );
    }

  itk::WASPCommandLineParser::Pointer parser = itk::WASPCommandLineParser::New();
  parser->SetCommand( argv[0] );

  parser->SetCommandDescription( "Apocrita segmentation." );
  InitializeCommandLineOptions( parser );

  parser->Parse( argc, argv );

  if( argc < 3 || parser->Convert<bool>(
        parser->GetOption( "help" )->GetValue() ) )
    {
    parser->PrintMenu( std::cout, 5 );
    exit( EXIT_FAILURE );
    }

  switch( atoi( argv[1] ) )
    {
    case 2:
      ApocritaSegmentation<2>( parser );
      break;
    case 3:
      ApocritaSegmentation<3>( parser );
      break;
    default:
      std::cerr << "Unsupported dimension" << std::endl;
      exit( EXIT_FAILURE );
    }
}
<commit_msg>Deleting Apocrita class which has been replaced by Atropos.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-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 <string>

#include "app/l10n_util.h"
#include "base/file_path.h"
#include "base/gfx/rect.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/automation_constants.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 "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "views/event.h"

class BlockedPopupContainerInteractiveTest : public UITest {
 protected:
  BlockedPopupContainerInteractiveTest() {
    show_window_ = true;
  }

  virtual void SetUp() {
    UITest::SetUp();

    browser_ = automation()->GetBrowserWindow(0);
    ASSERT_TRUE(browser_.get());

    window_ = browser_->GetWindow();
    ASSERT_TRUE(window_.get());

    tab_ = browser_->GetTab(0);
    ASSERT_TRUE(tab_.get());
  }

  void NavigateMainTabTo(const std::wstring& file_name) {
    FilePath filename(test_data_directory_);
    filename = filename.AppendASCII("constrained_files");
    filename = filename.Append(FilePath::FromWStringHack(file_name));
    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));
  }

  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {
    gfx::Rect tab_view_bounds;
    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                      &tab_view_bounds, true));

    // Simulate a click of the actual link to force user_gesture to be
    // true; if we don't, the resulting popup will be constrained, which
    // isn't what we want to test.
    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                                        views::Event::EF_LEFT_BUTTON_DOWN));
  }

  scoped_refptr<BrowserProxy> browser_;
  scoped_refptr<WindowProxy> window_;
  scoped_refptr<TabProxy> tab_;
};

TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {
  NavigateMainTabTo(L"constrained_window_onload_resizeto.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser != NULL);
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window != NULL);

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);

#if !defined(OS_LINUX)
  // TODO(estade): This is a real failure; we create popups with the wrong size.
  // Fix it. Note: it appears that we are setting the window's bounds to 300,320
  // instead of setting the content's bounds to 300,320.
  EXPECT_EQ(300, rect.width());
  EXPECT_EQ(320, rect.height());
#endif

  SimulateClickInCenterOf(popup_window);

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  PlatformThread::Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_LT(rect.width(), 200);
  EXPECT_LT(rect.height(), 200);
}

// TODO(estade): port.
#if !defined(OS_LINUX)
// Helper function used to get the number of blocked popups out of the window
// title.
bool ParseCountOutOfTitle(const std::wstring& title, int* output) {
  // Since we will be reading the number of popup windows open by grabbing the
  // number out of the window title, and that format string is localized, we
  // need to find out the offset into that string.
  const wchar_t* placeholder = L"XXXX";
  size_t offset =
      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).
      find(placeholder);

  std::wstring number;
  while (offset < title.size() && iswdigit(title[offset])) {
    number += title[offset];
    offset++;
  }

  return StringToInt(WideToUTF16(number), output);
}

// Tests that in the window.open() equivalent of a fork bomb, we stop building
// windows.
TEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) {
  NavigateMainTabTo(L"infinite_popups.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  // And now we spin, waiting to make sure that we don't spawn popup
  // windows endlessly. The current limit is 25, so allowing for possible race
  // conditions and one off errors, don't break out until we go over 30 popup
  // windows (in which case we are bork bork bork).
  const int kMaxPopupWindows = 30;

  int popup_window_count = 0;
  int new_popup_window_count = 0;
  int times_slept = 0;
  bool continuing = true;
  while (continuing && popup_window_count < kMaxPopupWindows) {
    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));
    if (new_popup_window_count == popup_window_count) {
      if (times_slept == 10) {
        continuing = false;
      } else {
        // Nothing intereseting is going on wait it out.
        PlatformThread::Sleep(automation::kSleepTime);
        times_slept++;
      }
    } else {
      times_slept = 0;
    }

    EXPECT_GE(new_popup_window_count, popup_window_count);
    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);
    popup_window_count = new_popup_window_count;
  }
}

// Make sure that we refuse to close windows when a constrained popup is
// displayed.
TEST_F(BlockedPopupContainerInteractiveTest, WindowOpenWindowClosePopup) {
  NavigateMainTabTo(L"openclose_main.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  // Make sure we have a blocked popup notification
  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());
  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));

  // Ensure we didn't close the first popup window.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));
}

TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {
  NavigateMainTabTo(L"block_alert.html");

  // Wait for there to be an app modal dialog (and fail if it's shown).
  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));

  // Ensure one browser window.
  int browser_window_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  ASSERT_EQ(1, browser_window_count);

  // Ensure one blocked popup window: the popup didn't escape.
  int popup_count = 0;
  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));
  ASSERT_EQ(1, popup_count);
}

TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {
  NavigateMainTabTo(L"show_alert.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  SimulateClickInCenterOf(popup_window);

  // Wait for there to be an app modal dialog.
  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));
}

// Make sure that window focus works while creating a popup window so that we
// don't
TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {
  NavigateMainTabTo(L"window_blur_test.html");
  SimulateClickInCenterOf(window_);

  // Wait for the popup window to open.
  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  // We popup shouldn't be closed by the onblur handler.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));
}
#endif
<commit_msg>Disable some blocked popup container tests to green the tree.<commit_after>// Copyright (c) 2006-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 <string>

#include "app/l10n_util.h"
#include "base/file_path.h"
#include "base/gfx/rect.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/automation_constants.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 "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "views/event.h"

class BlockedPopupContainerInteractiveTest : public UITest {
 protected:
  BlockedPopupContainerInteractiveTest() {
    show_window_ = true;
  }

  virtual void SetUp() {
    UITest::SetUp();

    browser_ = automation()->GetBrowserWindow(0);
    ASSERT_TRUE(browser_.get());

    window_ = browser_->GetWindow();
    ASSERT_TRUE(window_.get());

    tab_ = browser_->GetTab(0);
    ASSERT_TRUE(tab_.get());
  }

  void NavigateMainTabTo(const std::wstring& file_name) {
    FilePath filename(test_data_directory_);
    filename = filename.AppendASCII("constrained_files");
    filename = filename.Append(FilePath::FromWStringHack(file_name));
    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));
  }

  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {
    gfx::Rect tab_view_bounds;
    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                      &tab_view_bounds, true));

    // Simulate a click of the actual link to force user_gesture to be
    // true; if we don't, the resulting popup will be constrained, which
    // isn't what we want to test.
    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                                        views::Event::EF_LEFT_BUTTON_DOWN));
  }

  scoped_refptr<BrowserProxy> browser_;
  scoped_refptr<WindowProxy> window_;
  scoped_refptr<TabProxy> tab_;
};

TEST_F(BlockedPopupContainerInteractiveTest, DISABLED_TestOpenAndResizeTo) {
  NavigateMainTabTo(L"constrained_window_onload_resizeto.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser != NULL);
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window != NULL);

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);

#if !defined(OS_LINUX)
  // TODO(estade): This is a real failure; we create popups with the wrong size.
  // Fix it. Note: it appears that we are setting the window's bounds to 300,320
  // instead of setting the content's bounds to 300,320.
  EXPECT_EQ(300, rect.width());
  EXPECT_EQ(320, rect.height());
#endif

  SimulateClickInCenterOf(popup_window);

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  PlatformThread::Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_LT(rect.width(), 200);
  EXPECT_LT(rect.height(), 200);
}

// TODO(estade): port.
#if !defined(OS_LINUX)
// Helper function used to get the number of blocked popups out of the window
// title.
bool ParseCountOutOfTitle(const std::wstring& title, int* output) {
  // Since we will be reading the number of popup windows open by grabbing the
  // number out of the window title, and that format string is localized, we
  // need to find out the offset into that string.
  const wchar_t* placeholder = L"XXXX";
  size_t offset =
      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).
      find(placeholder);

  std::wstring number;
  while (offset < title.size() && iswdigit(title[offset])) {
    number += title[offset];
    offset++;
  }

  return StringToInt(WideToUTF16(number), output);
}

// Tests that in the window.open() equivalent of a fork bomb, we stop building
// windows.
TEST_F(BlockedPopupContainerInteractiveTest, DISABLED_DontSpawnEndlessPopups) {
  NavigateMainTabTo(L"infinite_popups.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  // And now we spin, waiting to make sure that we don't spawn popup
  // windows endlessly. The current limit is 25, so allowing for possible race
  // conditions and one off errors, don't break out until we go over 30 popup
  // windows (in which case we are bork bork bork).
  const int kMaxPopupWindows = 30;

  int popup_window_count = 0;
  int new_popup_window_count = 0;
  int times_slept = 0;
  bool continuing = true;
  while (continuing && popup_window_count < kMaxPopupWindows) {
    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));
    if (new_popup_window_count == popup_window_count) {
      if (times_slept == 10) {
        continuing = false;
      } else {
        // Nothing intereseting is going on wait it out.
        PlatformThread::Sleep(automation::kSleepTime);
        times_slept++;
      }
    } else {
      times_slept = 0;
    }

    EXPECT_GE(new_popup_window_count, popup_window_count);
    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);
    popup_window_count = new_popup_window_count;
  }
}

// Make sure that we refuse to close windows when a constrained popup is
// displayed.
TEST_F(BlockedPopupContainerInteractiveTest, DISABLED_WindowOpenWindowClosePopup) {
  NavigateMainTabTo(L"openclose_main.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  // Make sure we have a blocked popup notification
  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());
  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));

  // Ensure we didn't close the first popup window.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));
}

TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {
  NavigateMainTabTo(L"block_alert.html");

  // Wait for there to be an app modal dialog (and fail if it's shown).
  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));

  // Ensure one browser window.
  int browser_window_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  ASSERT_EQ(1, browser_window_count);

  // Ensure one blocked popup window: the popup didn't escape.
  int popup_count = 0;
  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));
  ASSERT_EQ(1, popup_count);
}

TEST_F(BlockedPopupContainerInteractiveTest, DISABLED_ShowAlertFromNormalPopup) {
  NavigateMainTabTo(L"show_alert.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  SimulateClickInCenterOf(popup_window);

  // Wait for there to be an app modal dialog.
  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));
}

// Make sure that window focus works while creating a popup window so that we
// don't
TEST_F(BlockedPopupContainerInteractiveTest, DISABLED_DontBreakOnBlur) {
  NavigateMainTabTo(L"window_blur_test.html");
  SimulateClickInCenterOf(window_);

  // Wait for the popup window to open.
  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  // We popup shouldn't be closed by the onblur handler.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));
}
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2006-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 <string>

#include "app/l10n_util.h"
#include "base/file_path.h"
#include "base/gfx/rect.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/automation_constants.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 "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "views/event.h"

class BlockedPopupContainerInteractiveTest : public UITest {
 protected:
  BlockedPopupContainerInteractiveTest() {
    show_window_ = true;
  }

  virtual void SetUp() {
    UITest::SetUp();

    browser_ = automation()->GetBrowserWindow(0);
    ASSERT_TRUE(browser_.get());

    window_ = browser_->GetWindow();
    ASSERT_TRUE(window_.get());

    tab_ = browser_->GetTab(0);
    ASSERT_TRUE(tab_.get());
  }

  void NavigateMainTabTo(const std::string& file_name) {
    FilePath filename(test_data_directory_);
    filename = filename.AppendASCII("constrained_files");
    filename = filename.AppendASCII(file_name);
    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));
  }

  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {
    gfx::Rect tab_view_bounds;
    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                      &tab_view_bounds, true));

    // Simulate a click of the actual link to force user_gesture to be
    // true; if we don't, the resulting popup will be constrained, which
    // isn't what we want to test.
    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                                        views::Event::EF_LEFT_BUTTON_DOWN));
  }

  scoped_refptr<BrowserProxy> browser_;
  scoped_refptr<WindowProxy> window_;
  scoped_refptr<TabProxy> tab_;
};

TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {
  NavigateMainTabTo("constrained_window_onload_resizeto.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser != NULL);
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window != NULL);

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_EQ(300, rect.width());
  EXPECT_EQ(320, rect.height());

#if defined(OS_LINUX)
  // It seems we have to wait a little bit for the widgets to spin up before
  // we can start clicking on them.
  PlatformThread::Sleep(500);
#endif

  SimulateClickInCenterOf(popup_window);

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  PlatformThread::Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_LT(rect.height(), 200);
#if defined(OS_LINUX)
  // On Linux we may run in an environment where there is no window frame. In
  // this case our width might be exactly 200. The height will still be less
  // because we have to show the location bar.
  EXPECT_LE(rect.width(), 200);
#else
  EXPECT_LT(rect.width(), 200);
#endif
}

// Helper function used to get the number of blocked popups out of the window
// title.
bool ParseCountOutOfTitle(const std::wstring& title, int* output) {
  // Since we will be reading the number of popup windows open by grabbing the
  // number out of the window title, and that format string is localized, we
  // need to find out the offset into that string.
  const wchar_t* placeholder = L"XXXX";
  size_t offset =
      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).
      find(placeholder);

  std::wstring number;
  while (offset < title.size() && iswdigit(title[offset])) {
    number += title[offset];
    offset++;
  }

  return StringToInt(WideToUTF16(number), output);
}

// Tests that in the window.open() equivalent of a fork bomb, we stop building
// windows.
TEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) {
  NavigateMainTabTo("infinite_popups.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  // And now we spin, waiting to make sure that we don't spawn popup
  // windows endlessly. The current limit is 25, so allowing for possible race
  // conditions and one off errors, don't break out until we go over 30 popup
  // windows (in which case we are bork bork bork).
  const int kMaxPopupWindows = 30;

  int popup_window_count = 0;
  int new_popup_window_count = 0;
  int times_slept = 0;
  bool continuing = true;
  while (continuing && popup_window_count < kMaxPopupWindows) {
    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));
    if (new_popup_window_count == popup_window_count) {
      if (times_slept == 10) {
        continuing = false;
      } else {
        // Nothing intereseting is going on wait it out.
        PlatformThread::Sleep(automation::kSleepTime);
        times_slept++;
      }
    } else {
      times_slept = 0;
    }

    EXPECT_GE(new_popup_window_count, popup_window_count);
    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);
    popup_window_count = new_popup_window_count;
  }
}

// Make sure that we refuse to close windows when a constrained popup is
// displayed.
TEST_F(BlockedPopupContainerInteractiveTest, FLAKY_WindowOpenWindowClosePopup) {
  NavigateMainTabTo("openclose_main.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  // Make sure we have a blocked popup notification
  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());
  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));

  // Ensure we didn't close the first popup window.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));
}

TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {
  NavigateMainTabTo("block_alert.html");

  // Wait for there to be an app modal dialog (and fail if it's shown).
  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));

  // Ensure one browser window.
  int browser_window_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  ASSERT_EQ(1, browser_window_count);

  // Ensure one blocked popup window: the popup didn't escape.
  int popup_count = 0;
  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));
  ASSERT_EQ(1, popup_count);
}

TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {
  NavigateMainTabTo("show_alert.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

#if defined(OS_LINUX)
  // It seems we have to wait a little bit for the widgets to spin up before
  // we can start clicking on them.
  PlatformThread::Sleep(500);
#endif

  SimulateClickInCenterOf(popup_window);

  // Wait for there to be an app modal dialog.
  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));
}

// Make sure that window focus works while creating a popup window so that we
// don't
TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {
  NavigateMainTabTo("window_blur_test.html");
  SimulateClickInCenterOf(window_);

  // Wait for the popup window to open.
  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  // We popup shouldn't be closed by the onblur handler.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));
}

// Tests that tab related keyboard accelerators are reserved by the app.

class BrowserInteractiveTest : public UITest {
};

TEST_F(BrowserInteractiveTest, ReserveKeyboardAccelerators) {
  const std::string kBadPage =
      "";
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  browser->AppendTab(GURL("data:text/html," + kBadPage));
  int tab_count = 0;
  ASSERT_TRUE(browser->GetTabCount(&tab_count));
  ASSERT_EQ(tab_count, 2);

  int active_tab = 0;
  ASSERT_TRUE(browser->GetActiveTabIndex(&active_tab));
  ASSERT_EQ(active_tab, 1);

  scoped_refptr<WindowProxy> window(browser->GetWindow());
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_TAB, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));

#if !defined(OS_MACOSX)  // see BrowserWindowCocoa::GetCommandId
  ASSERT_TRUE(browser->ActivateTab(1));
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_W, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
#endif
}
<commit_msg>Mark BlockedPopupContainerInteractiveTest.DontSpawnEndlessPopups as FLAKY.<commit_after>// Copyright (c) 2006-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 <string>

#include "app/l10n_util.h"
#include "base/file_path.h"
#include "base/gfx/rect.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/automation_constants.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 "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "views/event.h"

class BlockedPopupContainerInteractiveTest : public UITest {
 protected:
  BlockedPopupContainerInteractiveTest() {
    show_window_ = true;
  }

  virtual void SetUp() {
    UITest::SetUp();

    browser_ = automation()->GetBrowserWindow(0);
    ASSERT_TRUE(browser_.get());

    window_ = browser_->GetWindow();
    ASSERT_TRUE(window_.get());

    tab_ = browser_->GetTab(0);
    ASSERT_TRUE(tab_.get());
  }

  void NavigateMainTabTo(const std::string& file_name) {
    FilePath filename(test_data_directory_);
    filename = filename.AppendASCII("constrained_files");
    filename = filename.AppendASCII(file_name);
    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));
  }

  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {
    gfx::Rect tab_view_bounds;
    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                      &tab_view_bounds, true));

    // Simulate a click of the actual link to force user_gesture to be
    // true; if we don't, the resulting popup will be constrained, which
    // isn't what we want to test.
    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                                        views::Event::EF_LEFT_BUTTON_DOWN));
  }

  scoped_refptr<BrowserProxy> browser_;
  scoped_refptr<WindowProxy> window_;
  scoped_refptr<TabProxy> tab_;
};

TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {
  NavigateMainTabTo("constrained_window_onload_resizeto.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser != NULL);
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window != NULL);

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_EQ(300, rect.width());
  EXPECT_EQ(320, rect.height());

#if defined(OS_LINUX)
  // It seems we have to wait a little bit for the widgets to spin up before
  // we can start clicking on them.
  PlatformThread::Sleep(500);
#endif

  SimulateClickInCenterOf(popup_window);

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  PlatformThread::Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_LT(rect.height(), 200);
#if defined(OS_LINUX)
  // On Linux we may run in an environment where there is no window frame. In
  // this case our width might be exactly 200. The height will still be less
  // because we have to show the location bar.
  EXPECT_LE(rect.width(), 200);
#else
  EXPECT_LT(rect.width(), 200);
#endif
}

// Helper function used to get the number of blocked popups out of the window
// title.
bool ParseCountOutOfTitle(const std::wstring& title, int* output) {
  // Since we will be reading the number of popup windows open by grabbing the
  // number out of the window title, and that format string is localized, we
  // need to find out the offset into that string.
  const wchar_t* placeholder = L"XXXX";
  size_t offset =
      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).
      find(placeholder);

  std::wstring number;
  while (offset < title.size() && iswdigit(title[offset])) {
    number += title[offset];
    offset++;
  }

  return StringToInt(WideToUTF16(number), output);
}

// Tests that in the window.open() equivalent of a fork bomb, we stop building
// windows.
// Flaky, http://crbug.com/26692.
TEST_F(BlockedPopupContainerInteractiveTest, FLAKY_DontSpawnEndlessPopups) {
  NavigateMainTabTo("infinite_popups.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  // And now we spin, waiting to make sure that we don't spawn popup
  // windows endlessly. The current limit is 25, so allowing for possible race
  // conditions and one off errors, don't break out until we go over 30 popup
  // windows (in which case we are bork bork bork).
  const int kMaxPopupWindows = 30;

  int popup_window_count = 0;
  int new_popup_window_count = 0;
  int times_slept = 0;
  bool continuing = true;
  while (continuing && popup_window_count < kMaxPopupWindows) {
    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));
    if (new_popup_window_count == popup_window_count) {
      if (times_slept == 10) {
        continuing = false;
      } else {
        // Nothing intereseting is going on wait it out.
        PlatformThread::Sleep(automation::kSleepTime);
        times_slept++;
      }
    } else {
      times_slept = 0;
    }

    EXPECT_GE(new_popup_window_count, popup_window_count);
    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);
    popup_window_count = new_popup_window_count;
  }
}

// Make sure that we refuse to close windows when a constrained popup is
// displayed.
TEST_F(BlockedPopupContainerInteractiveTest, FLAKY_WindowOpenWindowClosePopup) {
  NavigateMainTabTo("openclose_main.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  // Make sure we have a blocked popup notification
  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());
  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));

  // Ensure we didn't close the first popup window.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));
}

TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {
  NavigateMainTabTo("block_alert.html");

  // Wait for there to be an app modal dialog (and fail if it's shown).
  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));

  // Ensure one browser window.
  int browser_window_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  ASSERT_EQ(1, browser_window_count);

  // Ensure one blocked popup window: the popup didn't escape.
  int popup_count = 0;
  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));
  ASSERT_EQ(1, popup_count);
}

TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {
  NavigateMainTabTo("show_alert.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

#if defined(OS_LINUX)
  // It seems we have to wait a little bit for the widgets to spin up before
  // we can start clicking on them.
  PlatformThread::Sleep(500);
#endif

  SimulateClickInCenterOf(popup_window);

  // Wait for there to be an app modal dialog.
  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));
}

// Make sure that window focus works while creating a popup window so that we
// don't
TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {
  NavigateMainTabTo("window_blur_test.html");
  SimulateClickInCenterOf(window_);

  // Wait for the popup window to open.
  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  // We popup shouldn't be closed by the onblur handler.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));
}

// Tests that tab related keyboard accelerators are reserved by the app.

class BrowserInteractiveTest : public UITest {
};

TEST_F(BrowserInteractiveTest, ReserveKeyboardAccelerators) {
  const std::string kBadPage =
      "";
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  browser->AppendTab(GURL("data:text/html," + kBadPage));
  int tab_count = 0;
  ASSERT_TRUE(browser->GetTabCount(&tab_count));
  ASSERT_EQ(tab_count, 2);

  int active_tab = 0;
  ASSERT_TRUE(browser->GetActiveTabIndex(&active_tab));
  ASSERT_EQ(active_tab, 1);

  scoped_refptr<WindowProxy> window(browser->GetWindow());
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_TAB, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));

#if !defined(OS_MACOSX)  // see BrowserWindowCocoa::GetCommandId
  ASSERT_TRUE(browser->ActivateTab(1));
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_W, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
#endif
}
<|endoftext|>


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

#include "chrome/browser/ui/views/ash/caps_lock_handler.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
using namespace chromeos::input_method;
#endif

namespace {

#if defined(OS_CHROMEOS)
class DummyXKeyboard : public XKeyboard {
 public:
  explicit DummyXKeyboard(bool initial_caps_lock_state)
      : caps_lock_is_enabled_(initial_caps_lock_state) {}
  virtual ~DummyXKeyboard() {}

  // Overridden from chrome::input_method::XKeyboard:
  virtual bool SetCurrentKeyboardLayoutByName(
      const std::string& layout_name) OVERRIDE {
    return true;
  }
  virtual bool RemapModifierKeys(const ModifierMap& modifier_map) OVERRIDE {
    return true;
  }
  virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE {
    return true;
  }
  virtual void ReapplyCurrentModifierLockStatus() OVERRIDE {}
  virtual void SetLockedModifiers(
      ModifierLockStatus new_caps_lock_status,
      ModifierLockStatus new_num_lock_status) OVERRIDE {}
  virtual void SetNumLockEnabled(bool enable_num_lock) OVERRIDE {}
  virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE {
    caps_lock_is_enabled_ = enable_caps_lock;
  }
  virtual bool NumLockIsEnabled() OVERRIDE {
    return true;
  }
  virtual bool CapsLockIsEnabled() OVERRIDE {
    return caps_lock_is_enabled_;
  }
  virtual std::string CreateFullXkbLayoutName(
      const std::string& layout_name,
      const ModifierMap& modifire_map) OVERRIDE {
    return "";
  }
  virtual unsigned int GetNumLockMask() OVERRIDE {
    return 0;
  }
  virtual void GetLockedModifiers(bool* out_caps_lock_enabled,
                                  bool* out_num_lock_enabled) OVERRIDE {}

 private:
  bool caps_lock_is_enabled_;

  DISALLOW_COPY_AND_ASSIGN(DummyXKeyboard);
};

class CapsLockHandlerTest : public InProcessBrowserTest {
 public:
  CapsLockHandlerTest()
      : initial_caps_lock_state_(false),
        xkeyboard_(initial_caps_lock_state_) {
  }
  virtual void SetUp() OVERRIDE {
    handler_.reset(new CapsLockHandler(&xkeyboard_));
    // Force CapsLockHandler::HandleToggleCapsLock() to toggle the lock state.
    handler_->set_is_running_on_chromeos_for_test(true);
  }
  virtual void TearDown() OVERRIDE {
    handler_.reset();
  }

 protected:
  const bool initial_caps_lock_state_;
  DummyXKeyboard xkeyboard_;
  scoped_ptr<CapsLockHandler> handler_;

  DISALLOW_COPY_AND_ASSIGN(CapsLockHandlerTest);
};
#endif

}  // namespace

#if defined(OS_CHROMEOS)
// Check if HandleToggleCapsLock() really changes the lock state.
IN_PROC_BROWSER_TEST_F(CapsLockHandlerTest, TestCapsLock) {
  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());
  EXPECT_TRUE(handler_->HandleToggleCapsLock());
  EXPECT_EQ(!initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());
  handler_->OnCapsLockChange(!initial_caps_lock_state_);
  EXPECT_EQ(!initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());
  EXPECT_TRUE(handler_->HandleToggleCapsLock());
  handler_->OnCapsLockChange(initial_caps_lock_state_);
  EXPECT_EQ(initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());
  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());
}
#endif
<commit_msg>cleanup: Use MockXKeyboard in caps_lock_handler_browsertest.cc.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/ash/caps_lock_handler.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/input_method/mock_xkeyboard.h"
using namespace chromeos::input_method;
#endif

namespace {

#if defined(OS_CHROMEOS)
class CapsLockHandlerTest : public InProcessBrowserTest {
 public:
  CapsLockHandlerTest()
      : initial_caps_lock_state_(false) {
  }
  virtual void SetUp() OVERRIDE {
    handler_.reset(new CapsLockHandler(&xkeyboard_));
    // Force CapsLockHandler::HandleToggleCapsLock() to toggle the lock state.
    handler_->set_is_running_on_chromeos_for_test(true);
  }
  virtual void TearDown() OVERRIDE {
    handler_.reset();
  }

 protected:
  const bool initial_caps_lock_state_;
  MockXKeyboard xkeyboard_;
  scoped_ptr<CapsLockHandler> handler_;

  DISALLOW_COPY_AND_ASSIGN(CapsLockHandlerTest);
};
#endif

}  // namespace

#if defined(OS_CHROMEOS)
// Check if HandleToggleCapsLock() really changes the lock state.
IN_PROC_BROWSER_TEST_F(CapsLockHandlerTest, TestCapsLock) {
  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());
  EXPECT_TRUE(handler_->HandleToggleCapsLock());
  EXPECT_EQ(!initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());
  handler_->OnCapsLockChange(!initial_caps_lock_state_);
  EXPECT_EQ(!initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());
  EXPECT_TRUE(handler_->HandleToggleCapsLock());
  handler_->OnCapsLockChange(initial_caps_lock_state_);
  EXPECT_EQ(initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());
  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());
}
#endif
<|endoftext|>


<commit_before><commit_msg>Operand with prefix<commit_after><|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlprojectruncontrol.h"
#include "qmlprojectrunconfiguration.h"
#include "qmlprojectconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/applicationlauncher.h>
#include <utils/environment.h>
#include <utils/qtcassert.h>

#include <debugger/debuggerrunner.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerconstants.h>
#include <debugger/debuggeruiswitcher.h>
#include <debugger/debuggerengine.h>
#include <qmljsinspector/qmljsinspectorconstants.h>

#include <QDir>
#include <QLabel>
#include <QMessageBox>

using ProjectExplorer::RunConfiguration;
using ProjectExplorer::RunControl;

namespace QmlProjectManager {
namespace Internal {

QmlRunControl::QmlRunControl(QmlProjectRunConfiguration *runConfiguration, QString mode)
    : RunControl(runConfiguration, mode)
{
    Utils::Environment environment = Utils::Environment::systemEnvironment();

    m_applicationLauncher.setEnvironment(environment.toStringList());
    m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());

    m_executable = runConfiguration->viewerPath();
    m_commandLineArguments = runConfiguration->viewerArguments();

    connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,bool)),
            this, SLOT(slotError(QString, bool)));
    connect(&m_applicationLauncher, SIGNAL(appendOutput(QString, bool)),
            this, SLOT(slotAddToOutputWindow(QString, bool)));
    connect(&m_applicationLauncher, SIGNAL(processExited(int)),
            this, SLOT(processExited(int)));
    connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
            this, SLOT(slotBringApplicationToForeground(qint64)));
}

QmlRunControl::~QmlRunControl()
{
}

void QmlRunControl::start()
{
    m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_executable,
                                m_commandLineArguments);

    emit started();
    emit appendMessage(this, tr("Starting %1 %2").arg(QDir::toNativeSeparators(m_executable),
                                                      m_commandLineArguments.join(QLatin1String(" "))), false);
}

RunControl::StopResult QmlRunControl::stop()
{
    m_applicationLauncher.stop();
    return StoppedSynchronously;
}

bool QmlRunControl::isRunning() const
{
    return m_applicationLauncher.isRunning();
}

void QmlRunControl::slotBringApplicationToForeground(qint64 pid)
{
    bringApplicationToForeground(pid);
}

void QmlRunControl::slotError(const QString &err, bool isError)
{
    emit appendMessage(this, err, isError);
    emit finished();
}

void QmlRunControl::slotAddToOutputWindow(const QString &line, bool onStdErr)
{
    emit addToOutputWindowInline(this, line, onStdErr);
}

void QmlRunControl::processExited(int exitCode)
{
    emit appendMessage(this, tr("%1 exited with code %2").arg(QDir::toNativeSeparators(m_executable)).arg(exitCode), exitCode != 0);
    emit finished();
}

QmlRunControlFactory::QmlRunControlFactory(QObject *parent)
    : IRunControlFactory(parent)
{
}

QmlRunControlFactory::~QmlRunControlFactory()
{
}

bool QmlRunControlFactory::canRun(RunConfiguration *runConfiguration,
                                  const QString &mode) const
{
    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration*>(runConfiguration);
    if (mode == ProjectExplorer::Constants::RUNMODE) {
        return config != 0;
    } else if (mode == ProjectExplorer::Constants::DEBUGMODE) {
        bool qmlDebugSupportInstalled = Debugger::DebuggerUISwitcher::instance()->supportedLanguages()
                                        & Debugger::QmlLanguage;
        return (config != 0) && qmlDebugSupportInstalled;
    }

    return false;
}

RunControl *QmlRunControlFactory::create(RunConfiguration *runConfiguration,
                                         const QString &mode)
{
    QTC_ASSERT(canRun(runConfiguration, mode), return 0);

    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration *>(runConfiguration);
    RunControl *runControl = 0;
    if (mode == ProjectExplorer::Constants::RUNMODE) {
       runControl = new QmlRunControl(config, mode);
    } else {
        runControl = createDebugRunControl(config);
    }
    return runControl;
}

QString QmlRunControlFactory::displayName() const
{
    return tr("Run");
}

QWidget *QmlRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)
{
    Q_UNUSED(runConfiguration)
    return new QLabel("TODO add Configuration widget");
}

ProjectExplorer::RunControl *QmlRunControlFactory::createDebugRunControl(QmlProjectRunConfiguration *runConfig)
{
    Utils::Environment environment = Utils::Environment::systemEnvironment();
    Debugger::DebuggerStartParameters params;
    params.startMode = Debugger::StartInternal;
    params.executable = runConfig->viewerPath();
    params.qmlServerAddress = "127.0.0.1";
    params.qmlServerPort = runConfig->qmlDebugServerPort();
    params.qmlObserverAvailable = runConfig->qmlObserverAvailable();
    params.processArgs = runConfig->viewerArguments();
    params.processArgs.append(QLatin1String("-qmljsdebugger=port:") + QString::number(runConfig->qmlDebugServerPort()));
    params.workingDirectory = runConfig->workingDirectory();
    params.environment = environment.toStringList();
    params.displayName = runConfig->displayName();

    Debugger::DebuggerRunControl *debuggerRunControl = Debugger::DebuggerPlugin::createDebugger(params, runConfig);
    return debuggerRunControl;
}

} // namespace Internal
} // namespace QmlProjectManager

<commit_msg>QmlProject: Stop program when exiting creator<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlprojectruncontrol.h"
#include "qmlprojectrunconfiguration.h"
#include "qmlprojectconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/applicationlauncher.h>
#include <utils/environment.h>
#include <utils/qtcassert.h>

#include <debugger/debuggerrunner.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerconstants.h>
#include <debugger/debuggeruiswitcher.h>
#include <debugger/debuggerengine.h>
#include <qmljsinspector/qmljsinspectorconstants.h>

#include <QDir>
#include <QLabel>
#include <QMessageBox>

using ProjectExplorer::RunConfiguration;
using ProjectExplorer::RunControl;

namespace QmlProjectManager {
namespace Internal {

QmlRunControl::QmlRunControl(QmlProjectRunConfiguration *runConfiguration, QString mode)
    : RunControl(runConfiguration, mode)
{
    Utils::Environment environment = Utils::Environment::systemEnvironment();

    m_applicationLauncher.setEnvironment(environment.toStringList());
    m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());

    m_executable = runConfiguration->viewerPath();
    m_commandLineArguments = runConfiguration->viewerArguments();

    connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,bool)),
            this, SLOT(slotError(QString, bool)));
    connect(&m_applicationLauncher, SIGNAL(appendOutput(QString, bool)),
            this, SLOT(slotAddToOutputWindow(QString, bool)));
    connect(&m_applicationLauncher, SIGNAL(processExited(int)),
            this, SLOT(processExited(int)));
    connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
            this, SLOT(slotBringApplicationToForeground(qint64)));
}

QmlRunControl::~QmlRunControl()
{
    stop();
}

void QmlRunControl::start()
{
    m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_executable,
                                m_commandLineArguments);

    emit started();
    emit appendMessage(this, tr("Starting %1 %2").arg(QDir::toNativeSeparators(m_executable),
                                                      m_commandLineArguments.join(QLatin1String(" "))), false);
}

RunControl::StopResult QmlRunControl::stop()
{
    m_applicationLauncher.stop();
    return StoppedSynchronously;
}

bool QmlRunControl::isRunning() const
{
    return m_applicationLauncher.isRunning();
}

void QmlRunControl::slotBringApplicationToForeground(qint64 pid)
{
    bringApplicationToForeground(pid);
}

void QmlRunControl::slotError(const QString &err, bool isError)
{
    emit appendMessage(this, err, isError);
    emit finished();
}

void QmlRunControl::slotAddToOutputWindow(const QString &line, bool onStdErr)
{
    emit addToOutputWindowInline(this, line, onStdErr);
}

void QmlRunControl::processExited(int exitCode)
{
    emit appendMessage(this, tr("%1 exited with code %2").arg(QDir::toNativeSeparators(m_executable)).arg(exitCode), exitCode != 0);
    emit finished();
}

QmlRunControlFactory::QmlRunControlFactory(QObject *parent)
    : IRunControlFactory(parent)
{
}

QmlRunControlFactory::~QmlRunControlFactory()
{
}

bool QmlRunControlFactory::canRun(RunConfiguration *runConfiguration,
                                  const QString &mode) const
{
    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration*>(runConfiguration);
    if (mode == ProjectExplorer::Constants::RUNMODE) {
        return config != 0;
    } else if (mode == ProjectExplorer::Constants::DEBUGMODE) {
        bool qmlDebugSupportInstalled = Debugger::DebuggerUISwitcher::instance()->supportedLanguages()
                                        & Debugger::QmlLanguage;
        return (config != 0) && qmlDebugSupportInstalled;
    }

    return false;
}

RunControl *QmlRunControlFactory::create(RunConfiguration *runConfiguration,
                                         const QString &mode)
{
    QTC_ASSERT(canRun(runConfiguration, mode), return 0);

    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration *>(runConfiguration);
    RunControl *runControl = 0;
    if (mode == ProjectExplorer::Constants::RUNMODE) {
       runControl = new QmlRunControl(config, mode);
    } else {
        runControl = createDebugRunControl(config);
    }
    return runControl;
}

QString QmlRunControlFactory::displayName() const
{
    return tr("Run");
}

QWidget *QmlRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)
{
    Q_UNUSED(runConfiguration)
    return new QLabel("TODO add Configuration widget");
}

ProjectExplorer::RunControl *QmlRunControlFactory::createDebugRunControl(QmlProjectRunConfiguration *runConfig)
{
    Utils::Environment environment = Utils::Environment::systemEnvironment();
    Debugger::DebuggerStartParameters params;
    params.startMode = Debugger::StartInternal;
    params.executable = runConfig->viewerPath();
    params.qmlServerAddress = "127.0.0.1";
    params.qmlServerPort = runConfig->qmlDebugServerPort();
    params.qmlObserverAvailable = runConfig->qmlObserverAvailable();
    params.processArgs = runConfig->viewerArguments();
    params.processArgs.append(QLatin1String("-qmljsdebugger=port:") + QString::number(runConfig->qmlDebugServerPort()));
    params.workingDirectory = runConfig->workingDirectory();
    params.environment = environment.toStringList();
    params.displayName = runConfig->displayName();

    Debugger::DebuggerRunControl *debuggerRunControl = Debugger::DebuggerPlugin::createDebugger(params, runConfig);
    return debuggerRunControl;
}

} // namespace Internal
} // namespace QmlProjectManager

<|endoftext|>