<commit_before>//----------------------------------------------------------------------------
//Yume Engine
//Copyright (C) 2015  arkenthera
//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.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/
//----------------------------------------------------------------------------
//
// File : <Filename> YumeGraphics.h
// Date : 2.19.2016
// Comments :
//
//----------------------------------------------------------------------------
#include "YumeHeaders.h"
#include "YumeIO.h"

namespace YumeEngine
{
	YumeIO::YumeIO()
	{
	}

	YumeIO::~YumeIO()
	{
	}

	bool YumeIO::IsDirectoryExist(const FsPath& path)
	{
		return boost::filesystem::exists(path);
	}

	FsPath YumeIO::GetBinaryRoot()
	{
		FsPath current = GetCurrentPath();

		//ToDo(arkenthera) fix this by working around Debug/Release that vs uses
#if YUME_PLATFORM == YUME_PLATFORM_WIN32
		FsPath root = current / ".." / "..";
#else
		FsPath root = current / ".." / "..";
#endif
		return boost::filesystem::absolute(root);
	}

	boost::filesystem::path YumeIO::GetCurrentPath() const
	{
		return boost::filesystem::current_path();
	}

	unsigned YumeIO::GetLastModifiedTime(const YumeString& fileName) const
	{
		if(fileName.empty())
			return 0;

#ifdef _WIN32
		struct _stat st;
		if(!_stat(fileName.c_str(),&st))
			return (unsigned)st.st_mtime;
		else
			return 0;
#else
		struct stat st;
		if (!stat(fileName.c_str(), &st))
			return (unsigned)st.st_mtime;
		else
			return 0;
#endif
	}

	bool YumeIO::CreateDir(const FsPath& path)
	{
		return boost::filesystem::create_directory(path);
	}

	void SplitPath(const YumeString& fullPath,YumeString& pathName,YumeString& fileName,YumeString& extension,bool lowercaseExtension)
	{
		//Shaders/HLSL/LitSolid.hlsl
		YumeString copy = fullPath;

		size_t extensionPos = copy.find_last_of(".");
		size_t pathPos = copy.find_last_of("/");

		size_t size = copy.size();

		extension = copy.substr(extensionPos,size - extensionPos);

		copy = copy.substr(0,extensionPos);

		size = copy.size();

		fileName = copy.substr(pathPos+1,size - pathPos +1);

		pathName = copy.substr(0,pathPos+1);
	}

	YumeString GetPath(const YumeString& fullPath)
	{
		YumeString path,file,extension;
		SplitPath(fullPath,path,file,extension);
		return path;
	}

	YumeString GetFileName(const YumeString& fullPath)
	{
		YumeString path,file,extension;
		SplitPath(fullPath,path,file,extension);
		return file;
	}

	YumeString GetExtension(const YumeString& fullPath,bool lowercaseExtension)
	{
		YumeString path,file,extension;
		SplitPath(fullPath,path,file,extension,lowercaseExtension);
		return extension;
	}
}
<commit_msg>Fix path on linux<commit_after>//----------------------------------------------------------------------------
//Yume Engine
//Copyright (C) 2015  arkenthera
//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.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/
//----------------------------------------------------------------------------
//
// File : <Filename> YumeGraphics.h
// Date : 2.19.2016
// Comments :
//
//----------------------------------------------------------------------------
#include "YumeHeaders.h"
#include "YumeIO.h"

namespace YumeEngine
{
	YumeIO::YumeIO()
	{
	}

	YumeIO::~YumeIO()
	{
	}

	bool YumeIO::IsDirectoryExist(const FsPath& path)
	{
		return boost::filesystem::exists(path);
	}

	FsPath YumeIO::GetBinaryRoot()
	{
		FsPath current = GetCurrentPath();

		//ToDo(arkenthera) fix this by working around Debug/Release that vs uses
#if YUME_PLATFORM == YUME_PLATFORM_WIN32
		FsPath root = current / ".." / "..";
#else
		FsPath root = current / "..";
#endif
		return boost::filesystem::absolute(root);
	}

	boost::filesystem::path YumeIO::GetCurrentPath() const
	{
		return boost::filesystem::current_path();
	}

	unsigned YumeIO::GetLastModifiedTime(const YumeString& fileName) const
	{
		if(fileName.empty())
			return 0;

#ifdef _WIN32
		struct _stat st;
		if(!_stat(fileName.c_str(),&st))
			return (unsigned)st.st_mtime;
		else
			return 0;
#else
		struct stat st;
		if (!stat(fileName.c_str(), &st))
			return (unsigned)st.st_mtime;
		else
			return 0;
#endif
	}

	bool YumeIO::CreateDir(const FsPath& path)
	{
		return boost::filesystem::create_directory(path);
	}

	void SplitPath(const YumeString& fullPath,YumeString& pathName,YumeString& fileName,YumeString& extension,bool lowercaseExtension)
	{
		//Shaders/HLSL/LitSolid.hlsl
		YumeString copy = fullPath;

		size_t extensionPos = copy.find_last_of(".");
		size_t pathPos = copy.find_last_of("/");

		size_t size = copy.size();

		extension = copy.substr(extensionPos,size - extensionPos);

		copy = copy.substr(0,extensionPos);

		size = copy.size();

		fileName = copy.substr(pathPos+1,size - pathPos +1);

		pathName = copy.substr(0,pathPos+1);
	}

	YumeString GetPath(const YumeString& fullPath)
	{
		YumeString path,file,extension;
		SplitPath(fullPath,path,file,extension);
		return path;
	}

	YumeString GetFileName(const YumeString& fullPath)
	{
		YumeString path,file,extension;
		SplitPath(fullPath,path,file,extension);
		return file;
	}

	YumeString GetExtension(const YumeString& fullPath,bool lowercaseExtension)
	{
		YumeString path,file,extension;
		SplitPath(fullPath,path,file,extension,lowercaseExtension);
		return extension;
	}
}
<|endoftext|>


<commit_before>
#include "antsUtilities.h"
#include <algorithm>
#include <algorithm>
#include <string>
#include <fstream>
#include <iostream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"

#include "itkRedColormapFunction.h"
#include "itkGreenColormapFunction.h"
#include "itkBlueColormapFunction.h"
#include "itkGreyColormapFunction.h"
#include "itkHotColormapFunction.h"
#include "itkCoolColormapFunction.h"
#include "itkSpringColormapFunction.h"
#include "itkSummerColormapFunction.h"
#include "itkAutumnColormapFunction.h"
#include "itkWinterColormapFunction.h"
#include "itkCopperColormapFunction.h"
#include "itkHSVColormapFunction.h"
#include "itkJetColormapFunction.h"
#include "itkCustomColormapFunction.h"
#include "itkOverUnderColormapFunction.h"

#include "itkScalarToRGBColormapImageFilter.h"

namespace ants
{
template <unsigned int ImageDimension>
int ConvertScalarImageToRGB( int argc, char *argv[] )
{
  typedef unsigned int                 PixelType;
  typedef itk::RGBPixel<unsigned char> RGBPixelType;
//  typedef itk::RGBAPixel<unsigned char> RGBPixelType;

  typedef float RealType;

  typedef itk::Image<PixelType, ImageDimension>    ImageType;
  typedef itk::Image<float, ImageDimension>        RealImageType;
  typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType;

  typedef itk::ImageFileReader<RealImageType> ReaderType;
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[2] );
  reader->Update();

  typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
  typename MaskImageType::Pointer maskImage;
  typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
  typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
  maskreader->SetFileName( argv[4] );
  try
    {
    maskreader->Update();
    maskImage = maskreader->GetOutput();
    }
  catch( ... )
    {
    maskImage = NULL;
    }
  ;

  std::string colormapString( argv[5] );

  typedef itk::ScalarToRGBColormapImageFilter<RealImageType,
                                              RGBImageType> RGBFilterType;
  typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New();
  rgbfilter->SetInput( reader->GetOutput() );

  if( colormapString == "red" )
    {
    rgbfilter->SetColormap( RGBFilterType::Red );
    }
  else if( colormapString == "green"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Green );
    }
  else if( colormapString == "blue"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Blue );
    }
  else if( colormapString == "grey"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Grey );
    }
  else if( colormapString == "cool"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Cool );
    }
  else if( colormapString == "hot"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Hot );
    }
  else if( colormapString == "spring"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Spring );
    }
  else if( colormapString == "autumn"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Autumn );
    }
  else if( colormapString == "winter"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Winter );
    }
  else if( colormapString == "copper"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Copper );
    }
  else if( colormapString == "summer"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Summer );
    }
  else if( colormapString == "jet"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Jet );
//    typedef itk::Function::JetColormapFunction<typename RealImageType::PixelType,
//      typename RGBImageType::PixelType> ColormapType;
//    typename ColormapType::Pointer colormap = ColormapType::New();
//    rgbfilter->SetColormap( colormap );
    }
  else if( colormapString == "hsv"  )
    {
    rgbfilter->SetColormap( RGBFilterType::HSV );
//    typedef itk::Function::HSVColormapFunction<typename RealImageType::PixelType,
//      typename RGBImageType::PixelType> ColormapType;
//    typename ColormapType::Pointer colormap = ColormapType::New();
//    rgbfilter->SetColormap( colormap );
    }
  else if( colormapString == "overunder"  )
    {
    rgbfilter->SetColormap( RGBFilterType::OverUnder );
    }
  else if( colormapString == "custom"  )
    {
    typedef itk::Function::CustomColormapFunction<typename RealImageType::PixelType,
                                                  typename RGBImageType::PixelType> ColormapType;
    typename ColormapType::Pointer colormap = ColormapType::New();

    std::ifstream str( argv[6] );
    std::string   line;

    // Get red values
      {
      std::getline( str, line );
      std::istringstream iss( line );
      float              value;
      typename ColormapType::ChannelType channel;
      while( iss >> value )
        {
        channel.push_back( value );
        }

      colormap->SetRedChannel( channel );
      }

    // Get green values
      {
      std::getline( str, line );
      std::istringstream iss( line );
      float              value;
      typename ColormapType::ChannelType channel;
      while( iss >> value )
        {
        channel.push_back( value );
        }

      colormap->SetGreenChannel( channel );
      }
    // Get blue values
      {
      std::getline( str, line );
      std::istringstream iss( line );
      float              value;
      typename ColormapType::ChannelType channel;
      while( iss >> value )
        {
        channel.push_back( value );
        }

      colormap->SetBlueChannel( channel );
      }
    rgbfilter->SetColormap( colormap );
    }

  if( maskImage )
    {
    RealType maskMinimumValue = itk::NumericTraits<RealType>::max();
    RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin();

    itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
                                                 maskImage->GetLargestPossibleRegion() );
    itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(),
                                                 reader->GetOutput()->GetLargestPossibleRegion() );
    for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS )
      {
      if( ItM.Get() != 0 )
        {
        if( maskMinimumValue >= ItS.Get() )
          {
          maskMinimumValue = ItS.Get();
          }
        if( maskMaximumValue <= ItS.Get() )
          {
          maskMaximumValue = ItS.Get();
          }
        }
      }

    rgbfilter->SetUseInputImageExtremaForScaling( false );
    rgbfilter->GetModifiableColormap()->SetMinimumInputValue( maskMinimumValue );
    rgbfilter->GetModifiableColormap()->SetMaximumInputValue( maskMaximumValue );
    }

  rgbfilter->GetModifiableColormap()->SetMinimumRGBComponentValue(
    ( argc > 9 ) ? static_cast<
      typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 );
  rgbfilter->GetModifiableColormap()->SetMaximumRGBComponentValue(
    ( argc > 10 ) ? static_cast<
      typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 );

  if( argc > 8 )
    {
    rgbfilter->SetUseInputImageExtremaForScaling( false );
    rgbfilter->GetModifiableColormap()->SetMinimumInputValue(
      static_cast<RealType>( atof( argv[7] ) ) );
    rgbfilter->GetModifiableColormap()->SetMaximumInputValue(
      static_cast<RealType>( atof( argv[8] ) ) );
    }

  try
    {
    rgbfilter->Update();
    }
  catch( ... )
    {
    return EXIT_FAILURE;
    }

  if( maskImage )
    {
    itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
                                                 maskImage->GetLargestPossibleRegion() );
    itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(),
                                                rgbfilter->GetOutput()->GetLargestPossibleRegion() );
    itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(),
                                                 reader->GetOutput()->GetLargestPossibleRegion() );

    ItM.GoToBegin();
    ItC.GoToBegin();
    ItS.GoToBegin();

    while( !ItM.IsAtEnd() )
      {
      if( ItM.Get() == 0 )
        {
        RGBPixelType rgbpixel;

//        RealType minimumValue = rgbfilter->GetModifiableColormap()->GetMinimumInputValue();
//        RealType maximumValue = rgbfilter->GetModifiableColormap()->GetMaximumInputValue();
//
//        RealType minimumRGBValue
//          = rgbfilter->GetModifiableColormap()->GetMinimumRGBComponentValue();
//        RealType maximumRGBValue
//          = rgbfilter->GetModifiableColormap()->GetMaximumRGBComponentValue();
//
//        RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue );
//
//        rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue )
//          + minimumRGBValue );
        rgbpixel.Fill( itk::NumericTraits<typename RGBPixelType::ComponentType>::Zero );

        ItC.Set( rgbpixel );
        }
      ++ItM;
      ++ItC;
      ++ItS;
      }
    }

  typedef itk::ImageFileWriter<RGBImageType> WriterType;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetInput( rgbfilter->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();

  return EXIT_SUCCESS;
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int ConvertScalarImageToRGB( std::vector<std::string> args, std::ostream* /*out_stream = NULL */ )
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert( args.begin(), "ConvertScalarImageToRGB" );
  int     argc = args.size();
  char* * argv = new char *[args.size() + 1];
  for( unsigned int i = 0; i < args.size(); ++i )
    {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy( argv[i], args[i].c_str(), args[i].length() );
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
    }
  argv[argc] = 0;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
public:
    Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
    {
    }

    ~Cleanup_argv()
    {
      for( unsigned int i = 0; i < argc_plus_one; ++i )
        {
        delete[] argv[i];
        }
      delete[] argv;
    }

private:
    char* *      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv( argv, argc + 1 );

  // antscout->set_stream( out_stream );

  if( argc < 6 )
    {
    std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage "
             << "mask colormap [customColormapFile] [minimumInput] [maximumInput] "
             << "[minimumRGBOutput] [maximumRGBOutput]" << std::endl;
    std::cout << "  Possible colormaps: grey, red, green, blue, copper, jet, hsv, ";
    std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl;
    if( argc >= 2 &&
        ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
      {
      return EXIT_SUCCESS;
      }
    return EXIT_FAILURE;
    }

  switch( atoi( argv[1] ) )
    {
    case 2:
      {
      ConvertScalarImageToRGB<2>( argc, argv );
      }
      break;
    case 3:
      {
      ConvertScalarImageToRGB<3>( argc, argv );
      }
      break;
    default:
      std::cout << "Unsupported dimension" << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
} // namespace ants
<commit_msg>ENH:  Adding specification of \'max\' or \'min\' on the command line.<commit_after>
#include "antsUtilities.h"
#include <algorithm>
#include <algorithm>
#include <string>
#include <fstream>
#include <iostream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"

#include "itkRedColormapFunction.h"
#include "itkGreenColormapFunction.h"
#include "itkBlueColormapFunction.h"
#include "itkGreyColormapFunction.h"
#include "itkHotColormapFunction.h"
#include "itkCoolColormapFunction.h"
#include "itkSpringColormapFunction.h"
#include "itkSummerColormapFunction.h"
#include "itkAutumnColormapFunction.h"
#include "itkWinterColormapFunction.h"
#include "itkCopperColormapFunction.h"
#include "itkHSVColormapFunction.h"
#include "itkJetColormapFunction.h"
#include "itkCustomColormapFunction.h"
#include "itkOverUnderColormapFunction.h"

#include "itkScalarToRGBColormapImageFilter.h"

namespace ants
{
template <unsigned int ImageDimension>
int ConvertScalarImageToRGB( int argc, char *argv[] )
{
  typedef unsigned int                 PixelType;
  typedef itk::RGBPixel<unsigned char> RGBPixelType;
//  typedef itk::RGBAPixel<unsigned char> RGBPixelType;

  typedef float RealType;

  typedef itk::Image<PixelType, ImageDimension>    ImageType;
  typedef itk::Image<float, ImageDimension>        RealImageType;
  typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType;

  typedef itk::ImageFileReader<RealImageType> ReaderType;
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[2] );
  reader->Update();

  typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
  typename MaskImageType::Pointer maskImage;
  typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
  typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
  maskreader->SetFileName( argv[4] );
  try
    {
    maskreader->Update();
    maskImage = maskreader->GetOutput();
    }
  catch( ... )
    {
    maskImage = NULL;
    }
  ;

  std::string colormapString( argv[5] );

  typedef itk::ScalarToRGBColormapImageFilter<RealImageType,
                                              RGBImageType> RGBFilterType;
  typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New();
  rgbfilter->SetInput( reader->GetOutput() );

  if( colormapString == "red" )
    {
    rgbfilter->SetColormap( RGBFilterType::Red );
    }
  else if( colormapString == "green"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Green );
    }
  else if( colormapString == "blue"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Blue );
    }
  else if( colormapString == "grey"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Grey );
    }
  else if( colormapString == "cool"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Cool );
    }
  else if( colormapString == "hot"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Hot );
    }
  else if( colormapString == "spring"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Spring );
    }
  else if( colormapString == "autumn"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Autumn );
    }
  else if( colormapString == "winter"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Winter );
    }
  else if( colormapString == "copper"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Copper );
    }
  else if( colormapString == "summer"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Summer );
    }
  else if( colormapString == "jet"  )
    {
    rgbfilter->SetColormap( RGBFilterType::Jet );
//    typedef itk::Function::JetColormapFunction<typename RealImageType::PixelType,
//      typename RGBImageType::PixelType> ColormapType;
//    typename ColormapType::Pointer colormap = ColormapType::New();
//    rgbfilter->SetColormap( colormap );
    }
  else if( colormapString == "hsv"  )
    {
    rgbfilter->SetColormap( RGBFilterType::HSV );
//    typedef itk::Function::HSVColormapFunction<typename RealImageType::PixelType,
//      typename RGBImageType::PixelType> ColormapType;
//    typename ColormapType::Pointer colormap = ColormapType::New();
//    rgbfilter->SetColormap( colormap );
    }
  else if( colormapString == "overunder"  )
    {
    rgbfilter->SetColormap( RGBFilterType::OverUnder );
    }
  else if( colormapString == "custom"  )
    {
    typedef itk::Function::CustomColormapFunction<typename RealImageType::PixelType,
                                                  typename RGBImageType::PixelType> ColormapType;
    typename ColormapType::Pointer colormap = ColormapType::New();

    std::ifstream str( argv[6] );
    std::string   line;

    // Get red values
      {
      std::getline( str, line );
      std::istringstream iss( line );
      float              value;
      typename ColormapType::ChannelType channel;
      while( iss >> value )
        {
        channel.push_back( value );
        }

      colormap->SetRedChannel( channel );
      }

    // Get green values
      {
      std::getline( str, line );
      std::istringstream iss( line );
      float              value;
      typename ColormapType::ChannelType channel;
      while( iss >> value )
        {
        channel.push_back( value );
        }

      colormap->SetGreenChannel( channel );
      }
    // Get blue values
      {
      std::getline( str, line );
      std::istringstream iss( line );
      float              value;
      typename ColormapType::ChannelType channel;
      while( iss >> value )
        {
        channel.push_back( value );
        }

      colormap->SetBlueChannel( channel );
      }
    rgbfilter->SetColormap( colormap );
    }

  RealType minimumValue = itk::NumericTraits<RealType>::max();
  RealType maximumValue = itk::NumericTraits<RealType>::NonpositiveMin();

  itk::ImageRegionIteratorWithIndex<RealImageType> ItS(
    reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() );
  for( ItS.GoToBegin(); !ItS.IsAtEnd(); ++ItS )
    {
    if( !maskImage || maskImage->GetPixel( ItS.GetIndex() ) != 0 )
      {
      if( minimumValue >= ItS.Get() )
        {
        minimumValue = ItS.Get();
        }
      if( maximumValue <= ItS.Get() )
        {
        maximumValue = ItS.Get();
        }
      }
    }

  rgbfilter->SetUseInputImageExtremaForScaling( false );
  rgbfilter->GetModifiableColormap()->SetMinimumInputValue( minimumValue );
  rgbfilter->GetModifiableColormap()->SetMaximumInputValue( maximumValue );

  rgbfilter->GetModifiableColormap()->SetMinimumRGBComponentValue(
    ( argc > 9 ) ? static_cast<
      typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 );
  rgbfilter->GetModifiableColormap()->SetMaximumRGBComponentValue(
    ( argc > 10 ) ? static_cast<
      typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 );

  if( argc > 7 )
    {
    std::string argvString( argv[7] );
    if( argvString != "min" || argvString != "minimum" )
      {
      rgbfilter->GetModifiableColormap()->SetMinimumInputValue(
        static_cast<RealType>( atof( argv[7] ) ) );
      }
    }

  if( argc > 8 )
    {
    std::string argvString( argv[8] );
    if( argvString != "max" || argvString != "maximum" )
      {
      rgbfilter->GetModifiableColormap()->SetMaximumInputValue(
        static_cast<RealType>( atof( argv[8] ) ) );
      }
    }

  try
    {
    rgbfilter->Update();
    }
  catch( ... )
    {
    return EXIT_FAILURE;
    }

  if( maskImage )
    {
    itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
                                                 maskImage->GetLargestPossibleRegion() );
    itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(),
                                                rgbfilter->GetOutput()->GetLargestPossibleRegion() );
    itk::ImageRegionIterator<RealImageType> ItS2( reader->GetOutput(),
                                                 reader->GetOutput()->GetLargestPossibleRegion() );

    ItM.GoToBegin();
    ItC.GoToBegin();
    ItS2.GoToBegin();

    while( !ItM.IsAtEnd() )
      {
      if( ItM.Get() == 0 )
        {
        RGBPixelType rgbpixel;

//        RealType minimumValue = rgbfilter->GetModifiableColormap()->GetMinimumInputValue();
//        RealType maximumValue = rgbfilter->GetModifiableColormap()->GetMaximumInputValue();
//
//        RealType minimumRGBValue
//          = rgbfilter->GetModifiableColormap()->GetMinimumRGBComponentValue();
//        RealType maximumRGBValue
//          = rgbfilter->GetModifiableColormap()->GetMaximumRGBComponentValue();
//
//        RealType ratio = ( ItS2.Get() - minimumValue ) / ( maximumValue - minimumValue );
//
//        rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue )
//          + minimumRGBValue );
        rgbpixel.Fill( itk::NumericTraits<typename RGBPixelType::ComponentType>::Zero );

        ItC.Set( rgbpixel );
        }
      ++ItM;
      ++ItC;
      ++ItS2;
      }
    }

  typedef itk::ImageFileWriter<RGBImageType> WriterType;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetInput( rgbfilter->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();

  return EXIT_SUCCESS;
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int ConvertScalarImageToRGB( std::vector<std::string> args, std::ostream* /*out_stream = NULL */ )
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert( args.begin(), "ConvertScalarImageToRGB" );
  int     argc = args.size();
  char* * argv = new char *[args.size() + 1];
  for( unsigned int i = 0; i < args.size(); ++i )
    {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy( argv[i], args[i].c_str(), args[i].length() );
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
    }
  argv[argc] = 0;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
public:
    Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
    {
    }

    ~Cleanup_argv()
    {
      for( unsigned int i = 0; i < argc_plus_one; ++i )
        {
        delete[] argv[i];
        }
      delete[] argv;
    }

private:
    char* *      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv( argv, argc + 1 );

  // antscout->set_stream( out_stream );

  if( argc < 6 )
    {
    std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage "
             << "mask colormap [customColormapFile] [minimumInput] [maximumInput] "
             << "[minimumRGBOutput=0] [maximumRGBOutput=255]" << std::endl;
    std::cout << "  Possible colormaps: grey, red, green, blue, copper, jet, hsv, ";
    std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl;
    if( argc >= 2 &&
        ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
      {
      return EXIT_SUCCESS;
      }
    return EXIT_FAILURE;
    }

  switch( atoi( argv[1] ) )
    {
    case 2:
      {
      ConvertScalarImageToRGB<2>( argc, argv );
      }
      break;
    case 3:
      {
      ConvertScalarImageToRGB<3>( argc, argv );
      }
      break;
    default:
      std::cout << "Unsupported dimension" << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
} // namespace ants
<|endoftext|>


<commit_before>/** @file editorview.cpp
 * 	@brief Класс, реализующий представление в схеме Model/View
 * */
#include <QtGui>

#ifdef QT_OPENGL_LIB
#include <QtOpenGL/QGLWidget>
#endif

#include "editorview.h"

EditorView::EditorView(QWidget *parent)
		: QGraphicsView(parent)
{
	setRenderHint(QPainter::Antialiasing, true);

	EditorViewScene *myScene = new EditorViewScene(this);
	mv_iface = new EditorViewMViface(this, myScene);
	setScene(myScene);

	setAcceptDrops(true);
}

EditorView::~EditorView()
{
}
/*
void EditorView::mousePressEvent(QMouseEvent *event)
{
//    if (QGraphicsItem *item = itemAt(event->pos())) {
//	mv_iface->raiseClick(item);
//    }

	QGraphicsView::mousePressEvent(event);
}
*/
void EditorView::toggleAntialiasing(bool checked)
{
	setRenderHint(QPainter::Antialiasing, checked);
	setRenderHint(QPainter::SmoothPixmapTransform, checked);
}

void EditorView::toggleOpenGL(bool checked)
{
	Q_UNUSED(checked)
#ifdef QT_OPENGL_LIB
			setViewport(checked ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget);
#endif
}

void EditorView::zoomIn()
{
	scale(1.5,1.5);
}

void EditorView::zoomOut()
{
	scale(0.666,0.666);
}

void EditorView::setMainWindow(qReal::MainWindow *mainWindow) {
	mv_iface->scene()->setMainWindow(mainWindow);
}

<commit_msg>Enable mouse region selection<commit_after>/** @file editorview.cpp
 * 	@brief Класс, реализующий представление в схеме Model/View
 * */
#include <QtGui>

#ifdef QT_OPENGL_LIB
#include <QtOpenGL/QGLWidget>
#endif

#include "editorview.h"

EditorView::EditorView(QWidget *parent)
		: QGraphicsView(parent)
{
	setRenderHint(QPainter::Antialiasing, true);

	EditorViewScene *myScene = new EditorViewScene(this);
	mv_iface = new EditorViewMViface(this, myScene);
	setScene(myScene);

	setAcceptDrops(true);
	setDragMode(RubberBandDrag);
}

EditorView::~EditorView()
{
}
/*
void EditorView::mousePressEvent(QMouseEvent *event)
{
//    if (QGraphicsItem *item = itemAt(event->pos())) {
//	mv_iface->raiseClick(item);
//    }

	QGraphicsView::mousePressEvent(event);
}
*/
void EditorView::toggleAntialiasing(bool checked)
{
	setRenderHint(QPainter::Antialiasing, checked);
	setRenderHint(QPainter::SmoothPixmapTransform, checked);
}

void EditorView::toggleOpenGL(bool checked)
{
	Q_UNUSED(checked)
#ifdef QT_OPENGL_LIB
			setViewport(checked ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget);
#endif
}

void EditorView::zoomIn()
{
	scale(1.5,1.5);
}

void EditorView::zoomOut()
{
	scale(0.666,0.666);
}

void EditorView::setMainWindow(qReal::MainWindow *mainWindow) {
	mv_iface->scene()->setMainWindow(mainWindow);
}

<|endoftext|>


<commit_before>#include "tests-base.hpp"

#include "utf8rewind.h"

TEST(TransformDecompose, Found)
{
	const char* c = "Bj\xC3\xB6rn Zonderland";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(18, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("Bjo\xCC\x88rn Zonderland", b);
}

TEST(TransformDecompose, FoundFirst)
{
	const char* c = "\xC3\x80";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("A\xCC\x80", b);
}

TEST(TransformDecompose, FoundLast)
{
	const char* c = "\xF0\xAF\xA8\x9D";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(4, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xF0\xAA\x98\x80", b);
}

TEST(TransformDecompose, FoundNotEnoughSpace)
{
	const char* c = "\xE1\xB8\xAE";
	const size_t s = 4;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("", b);
}

TEST(TransformDecompose, ExpandedNotEnoughSpace)
{
	const char* c = "Am\xC3\x87zing";
	const size_t s = 7;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("AmC\xCC\xA7z", b);
}

TEST(TransformDecompose, NoChange)
{
	const char* c = "\xE1\xA2\xA2";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xE1\xA2\xA2", b);
}

TEST(TransformDecompose, NoChangeNotEnoughSpace)
{
	const char* c = "\xE2\xA0\x81";
	const size_t s = 3;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("", b);
}

TEST(TransformDecompose, Ascii)
{
	const char* c = "Ruler";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(5, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("Ruler", b);
}

TEST(TransformDecompose, AsciiNotEnoughSpace)
{
	const char* c = "Spacebro";
	const size_t s = 6;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(5, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("Space", b);
}

TEST(TransformDecompose, JustEnoughSpace)
{
	const char* c = "Ar\xE1\xB9\x9Eogance";
	const size_t s = 12;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(11, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("ArR\xCC\xB1ogance", b);
}

TEST(TransformDecompose, JustEnoughSpaceAtEnd)
{
	const char* c = "Pounc\xE1\xB8\x94";
	const size_t s = 11;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(10, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("PouncE\xCC\x84\xCC\x80", b);
}

TEST(TransformDecompose, JustEnoughSpaceAtStart)
{
	const char* c = "\xE1\xB8\x9C";
	const size_t s = 6;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(5, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("E\xCC\xA7\xCC\x86", b);
}

TEST(TransformDecompose, InvalidCodepointSurrogatePair)
{
	const char* c = "\xED\xA0\x80\xED\xB0\x81";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xEF\xBF\xBD\xEF\xBF\xBD", b);
}

TEST(TransformDecompose, InvalidCodepointOverlong)
{
	const char* c = "\xF8\x80\x80\x80\xAF";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xEF\xBF\xBD", b);
}

TEST(TransformDecompose, InvalidCodepointNotEnoughData)
{
	const char* c = "\xED\xAB";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xEF\xBF\xBD", b);
}

TEST(TransformDecompose, InvalidCodepointNotEnoughSpace)
{
	const char* c = "\xF0\x91\x88\x81";
	const size_t s = 3;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("", b);
}

TEST(TransformDecompose, AmountOfBytes)
{
	const char* c = "\xCA\xB4";
	int32_t errors = 0;

	EXPECT_EQ(2, utf8transform(c, strlen(c), nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
}

TEST(TransformDecompose, AmountOfBytesString)
{
	const char* c = "Brill\xC3\x95";
	int32_t errors = 0;

	EXPECT_EQ(7, utf8transform(c, strlen(c), nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
}

TEST(TransformDecompose, AmountOfBytesNoChange)
{
	const char* c = "\xE9\xAA\x88";
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
}

TEST(TransformDecompose, AmountOfBytesNoData)
{
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(nullptr, 1, nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors);
}<commit_msg>suite-transform-decompose: Added tests for Hangul codepoints.<commit_after>#include "tests-base.hpp"

#include "utf8rewind.h"

TEST(TransformDecompose, Found)
{
	const char* c = "Bj\xC3\xB6rn Zonderland";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(18, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("Bjo\xCC\x88rn Zonderland", b);
}

TEST(TransformDecompose, FoundFirst)
{
	const char* c = "\xC3\x80";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("A\xCC\x80", b);
}

TEST(TransformDecompose, FoundLast)
{
	const char* c = "\xF0\xAF\xA8\x9D";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(4, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xF0\xAA\x98\x80", b);
}

TEST(TransformDecompose, FoundNotEnoughSpace)
{
	const char* c = "\xE1\xB8\xAE";
	const size_t s = 4;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("", b);
}

TEST(TransformDecompose, ExpandedNotEnoughSpace)
{
	const char* c = "Am\xC3\x87zing";
	const size_t s = 7;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("AmC\xCC\xA7z", b);
}

TEST(TransformDecompose, NoChange)
{
	const char* c = "\xE1\xA2\xA2";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xE1\xA2\xA2", b);
}

TEST(TransformDecompose, NoChangeNotEnoughSpace)
{
	const char* c = "\xE2\xA0\x81";
	const size_t s = 3;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("", b);
}

TEST(TransformDecompose, Ascii)
{
	const char* c = "Ruler";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(5, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("Ruler", b);
}

TEST(TransformDecompose, AsciiNotEnoughSpace)
{
	const char* c = "Spacebro";
	const size_t s = 6;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(5, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("Space", b);
}

TEST(TransformDecompose, Hangul)
{
	const char* c = "\xED\x9B\xBD";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(9, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xE1\x84\x92\xE1\x85\xB0\xE1\x86\xA8", b);
}

TEST(TransformDecompose, HangulFirst)
{
	const char* c = "\xEA\xB0\x80";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xE1\x84\x80\xE1\x85\xA1", b);
}

TEST(TransformDecompose, HangulLast)
{
	const char* c = "\xED\x9E\xA3";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(9, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xE1\x84\x92\xE1\x85\xB5\xE1\x87\x82", b);
}

TEST(TransformDecompose, JustEnoughSpace)
{
	const char* c = "Ar\xE1\xB9\x9Eogance";
	const size_t s = 12;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(11, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("ArR\xCC\xB1ogance", b);
}

TEST(TransformDecompose, JustEnoughSpaceAtEnd)
{
	const char* c = "Pounc\xE1\xB8\x94";
	const size_t s = 11;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(10, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("PouncE\xCC\x84\xCC\x80", b);
}

TEST(TransformDecompose, JustEnoughSpaceAtStart)
{
	const char* c = "\xE1\xB8\x9C";
	const size_t s = 6;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(5, utf8transform(c, strlen(c), b, s - 1, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("E\xCC\xA7\xCC\x86", b);
}

TEST(TransformDecompose, InvalidCodepointSurrogatePair)
{
	const char* c = "\xED\xA0\x80\xED\xB0\x81";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xEF\xBF\xBD\xEF\xBF\xBD", b);
}

TEST(TransformDecompose, InvalidCodepointOverlong)
{
	const char* c = "\xF8\x80\x80\x80\xAF";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xEF\xBF\xBD", b);
}

TEST(TransformDecompose, InvalidCodepointNotEnoughData)
{
	const char* c = "\xED\xAB";
	const size_t s = 512;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_STREQ("\xEF\xBF\xBD", b);
}

TEST(TransformDecompose, InvalidCodepointNotEnoughSpace)
{
	const char* c = "\xF0\x91\x88\x81";
	const size_t s = 3;
	char b[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(c, strlen(c), b, s, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
	EXPECT_STREQ("", b);
}

TEST(TransformDecompose, AmountOfBytes)
{
	const char* c = "\xCA\xB4";
	int32_t errors = 0;

	EXPECT_EQ(2, utf8transform(c, strlen(c), nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
}

TEST(TransformDecompose, AmountOfBytesString)
{
	const char* c = "Brill\xC3\x95";
	int32_t errors = 0;

	EXPECT_EQ(7, utf8transform(c, strlen(c), nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
}

TEST(TransformDecompose, AmountOfBytesNoChange)
{
	const char* c = "\xE9\xAA\x88";
	int32_t errors = 0;

	EXPECT_EQ(3, utf8transform(c, strlen(c), nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(0, errors);
}

TEST(TransformDecompose, AmountOfBytesNoData)
{
	int32_t errors = 0;

	EXPECT_EQ(0, utf8transform(nullptr, 1, nullptr, 0, UTF8_TRANSFORM_DECOMPOSED, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors);
}<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "swirl_user.h"
#include <fclaw2d_forestclaw.h>
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack5.h>
#include <fc2d_dummy.h>

/* Leave these in for demonstration purposes */
#include <fclaw2d_output_ascii.h>
#include <fclaw2d_regrid_default.h>

static fclaw2d_vtable_t vt;
static fc2d_clawpack5_vtable_t classic_claw;

void swirl_link_solvers(fclaw2d_domain_t *domain)
{
    fclaw2d_init_vtable(&vt);

    vt.problem_setup            = &fc2d_clawpack5_setprob;

    vt.patch_setup              = &swirl_patch_setup;
    vt.patch_initialize         = &swirl_patch_initialize;
    vt.patch_physical_bc        = &swirl_patch_physical_bc;
    vt.patch_single_step_update = &fc2d_clawpack5_update;  /* Includes b4step2 and src2 */

    vt.regrid_tag4refinement     = &swirl_patch_tag4refinement;
    vt.fort_tag4refinement      = &TAG4REFINEMENT;

    vt.regrid_tag4coarsening     = &swirl_patch_tag4coarsening;
    vt.fort_tag4coarsening      = &TAG4COARSENING;

    vt.write_header             = &fclaw2d_output_header_ascii;
    vt.fort_write_header        = &FCLAW2D_FORT_WRITE_HEADER;

    vt.patch_write_file         = &fclaw2d_output_patch_ascii;
    vt.fort_write_file          = &FCLAW2D_FORT_WRITE_FILE;

    fclaw2d_set_vtable(domain,&vt);

    /* Needed for the clawpack5 package */
    classic_claw.qinit = &QINIT;
    classic_claw.bc2 = &BC2;
    classic_claw.setaux = &SETAUX;
    classic_claw.setprob = &SETPROB;
    classic_claw.b4step2 = &B4STEP2;
    classic_claw.rpn2 = &RPN2;
    classic_claw.rpt2 = &RPT2;

    fc2d_clawpack5_set_vtable(&classic_claw);

}

void swirl_patch_setup(fclaw2d_domain_t *domain,
                          fclaw2d_patch_t *this_patch,
                          int this_block_idx,
                          int this_patch_idx)
{
    /* Dummy setup - use multiple libraries */
    fc2d_clawpack5_setaux(domain,this_patch,this_block_idx,this_patch_idx);
    fc2d_dummy_setup_patch(domain,this_patch,this_block_idx,this_patch_idx);
}

void swirl_patch_initialize(fclaw2d_domain_t *domain,
                            fclaw2d_patch_t *this_patch,
                            int this_block_idx,
                            int this_patch_idx)
{
    /* This is an example of how to call the initialization routines explicitly
       This routine can be replaced by setting the appropriate fclaw2d_vtable_t,
       entry above, or by calling fclaw2d_clawpack5_qinit(...) from here. */

    int mx,my,mbc,meqn, maux, maxmx, maxmy;
    double xlower,ylower,dx,dy;
    double *q, *aux;

    vt = fclaw2d_get_vtable(domain);

    fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);
    fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);

    /* Call to used defined, classic Clawpack (ver. 4.6)  'qinit' routine.
       Header is in the Clawpack package
    */
    maxmx = mx;
    maxmy = my;

    QINIT(&meqn,&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,q,&maux,aux);
}

void swirl_patch_physical_bc(fclaw2d_domain *domain,
                             fclaw2d_patch_t *this_patch,
                             int this_block_idx,
                             int this_patch_idx,
                             double t,
                             double dt,
                             fclaw_bool intersects_bc[],
                             fclaw_bool time_interp)
{
    /* This calls bc2 in swirl/user_4.6;  that file isn't changed but
       is included to show that both the local version of bc2.f and the
       clawpack5 library code can be included */
    fc2d_clawpack5_bc2(domain,this_patch,this_block_idx,this_patch_idx,
                     t,dt,intersects_bc,time_interp);
}

int swirl_patch_tag4refinement(fclaw2d_domain_t *domain,
                               fclaw2d_patch_t *this_patch,
                               int blockno, int this_patch_idx,
                               int initflag)
{
    fclaw2d_vtable_t vt;
    int mx,my,mbc,meqn;
    double xlower,ylower,dx,dy;
    double *q;
    int tag_patch;
    const amr_options_t *amropt;
    double rt;

    amropt = get_domain_parms(domain);
    rt = amropt->refine_threshold;

    vt = fclaw2d_get_vtable(domain);

    fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);

    tag_patch = 0;
    vt.fort_tag4refinement(&mx,&my,&mbc,&meqn,&xlower,&ylower,
                           &dx,&dy,&blockno, q,&rt,&initflag,
                           &tag_patch);
    return tag_patch;
}

int swirl_patch_tag4coarsening(fclaw2d_domain_t *domain,
                               fclaw2d_patch_t *fine_patches,
                               int blockno, int patchno)

{
    fclaw2d_vtable_t vt;

    int mx,my,mbc,meqn;
    double xlower,ylower,dx,dy;
    double *q[4];
    int tag_patch,igrid;
    double coarsen_threshold;
    fclaw2d_patch_t *patch0;

    patch0 = &fine_patches[0];

    const amr_options_t *amropt;
    amropt = get_domain_parms(domain);

    coarsen_threshold = amropt->coarsen_threshold;

    vt = fclaw2d_get_vtable(domain);

    fclaw2d_clawpatch_grid_data(domain,patch0,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    for (igrid = 0; igrid < 4; igrid++)
    {
        fclaw2d_clawpatch_soln_data(domain,&fine_patches[igrid],&q[igrid],&meqn);
    }
    tag_patch = 0;
    vt.fort_tag4coarsening(&mx,&my,&mbc,&meqn,&xlower,&ylower,&dx,&dy,
                           &blockno, q[0],q[1],q[2],q[3],
                           &coarsen_threshold, &tag_patch);
    return tag_patch;

}
<commit_msg>(swirl) Remove unused variables<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "swirl_user.h"
#include <fclaw2d_forestclaw.h>
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack5.h>
#include <fc2d_dummy.h>

/* Leave these in for demonstration purposes */
#include <fclaw2d_output_ascii.h>
#include <fclaw2d_regrid_default.h>

static fclaw2d_vtable_t vt;
static fc2d_clawpack5_vtable_t classic_claw;

void swirl_link_solvers(fclaw2d_domain_t *domain)
{
    fclaw2d_init_vtable(&vt);

    vt.problem_setup            = &fc2d_clawpack5_setprob;

    vt.patch_setup              = &swirl_patch_setup;
    vt.patch_initialize         = &swirl_patch_initialize;
    vt.patch_physical_bc        = &swirl_patch_physical_bc;
    vt.patch_single_step_update = &fc2d_clawpack5_update;  /* Includes b4step2 and src2 */

    vt.regrid_tag4refinement     = &swirl_patch_tag4refinement;
    vt.fort_tag4refinement      = &TAG4REFINEMENT;

    vt.regrid_tag4coarsening     = &swirl_patch_tag4coarsening;
    vt.fort_tag4coarsening      = &TAG4COARSENING;

    vt.write_header             = &fclaw2d_output_header_ascii;
    vt.fort_write_header        = &FCLAW2D_FORT_WRITE_HEADER;

    vt.patch_write_file         = &fclaw2d_output_patch_ascii;
    vt.fort_write_file          = &FCLAW2D_FORT_WRITE_FILE;

    fclaw2d_set_vtable(domain,&vt);

    /* Needed for the clawpack5 package */
    classic_claw.qinit = &QINIT;
    classic_claw.bc2 = &BC2;
    classic_claw.setaux = &SETAUX;
    classic_claw.setprob = &SETPROB;
    classic_claw.b4step2 = &B4STEP2;
    classic_claw.rpn2 = &RPN2;
    classic_claw.rpt2 = &RPT2;

    fc2d_clawpack5_set_vtable(&classic_claw);

}

void swirl_patch_setup(fclaw2d_domain_t *domain,
                          fclaw2d_patch_t *this_patch,
                          int this_block_idx,
                          int this_patch_idx)
{
    /* Dummy setup - use multiple libraries */
    fc2d_clawpack5_setaux(domain,this_patch,this_block_idx,this_patch_idx);
    fc2d_dummy_setup_patch(domain,this_patch,this_block_idx,this_patch_idx);
}

void swirl_patch_initialize(fclaw2d_domain_t *domain,
                            fclaw2d_patch_t *this_patch,
                            int this_block_idx,
                            int this_patch_idx)
{
    /* This is an example of how to call the initialization routines explicitly
       This routine can be replaced by setting the appropriate fclaw2d_vtable_t,
       entry above, or by calling fclaw2d_clawpack5_qinit(...) from here. */

    int mx,my,mbc,meqn, maux;
    double xlower,ylower,dx,dy;
    double *q, *aux;

    vt = fclaw2d_get_vtable(domain);

    fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);
    fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);

    /* Call to used defined, classic Clawpack (ver. 4.6)  'qinit' routine.
       Header is in the Clawpack package
    */
    QINIT(&meqn,&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,q,&maux,aux);
}

void swirl_patch_physical_bc(fclaw2d_domain *domain,
                             fclaw2d_patch_t *this_patch,
                             int this_block_idx,
                             int this_patch_idx,
                             double t,
                             double dt,
                             fclaw_bool intersects_bc[],
                             fclaw_bool time_interp)
{
    /* This calls bc2 in swirl/user_4.6;  that file isn't changed but
       is included to show that both the local version of bc2.f and the
       clawpack5 library code can be included */
    fc2d_clawpack5_bc2(domain,this_patch,this_block_idx,this_patch_idx,
                     t,dt,intersects_bc,time_interp);
}

int swirl_patch_tag4refinement(fclaw2d_domain_t *domain,
                               fclaw2d_patch_t *this_patch,
                               int blockno, int this_patch_idx,
                               int initflag)
{
    fclaw2d_vtable_t vt;
    int mx,my,mbc,meqn;
    double xlower,ylower,dx,dy;
    double *q;
    int tag_patch;
    const amr_options_t *amropt;
    double rt;

    amropt = get_domain_parms(domain);
    rt = amropt->refine_threshold;

    vt = fclaw2d_get_vtable(domain);

    fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);

    tag_patch = 0;
    vt.fort_tag4refinement(&mx,&my,&mbc,&meqn,&xlower,&ylower,
                           &dx,&dy,&blockno, q,&rt,&initflag,
                           &tag_patch);
    return tag_patch;
}

int swirl_patch_tag4coarsening(fclaw2d_domain_t *domain,
                               fclaw2d_patch_t *fine_patches,
                               int blockno, int patchno)

{
    fclaw2d_vtable_t vt;

    int mx,my,mbc,meqn;
    double xlower,ylower,dx,dy;
    double *q[4];
    int tag_patch,igrid;
    double coarsen_threshold;
    fclaw2d_patch_t *patch0;

    patch0 = &fine_patches[0];

    const amr_options_t *amropt;
    amropt = get_domain_parms(domain);

    coarsen_threshold = amropt->coarsen_threshold;

    vt = fclaw2d_get_vtable(domain);

    fclaw2d_clawpatch_grid_data(domain,patch0,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    for (igrid = 0; igrid < 4; igrid++)
    {
        fclaw2d_clawpatch_soln_data(domain,&fine_patches[igrid],&q[igrid],&meqn);
    }
    tag_patch = 0;
    vt.fort_tag4coarsening(&mx,&my,&mbc,&meqn,&xlower,&ylower,&dx,&dy,
                           &blockno, q[0],q[1],q[2],q[3],
                           &coarsen_threshold, &tag_patch);
    return tag_patch;

}
<|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/chromeos/ui/setting_level_bubble.h"

#include <algorithm>

#include "chrome/browser/chromeos/login/base_login_display_host.h"
#include "chrome/browser/chromeos/login/login_display_host.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/ui/setting_level_bubble_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/window.h"
#include "ui/gfx/screen.h"
#include "ui/views/bubble/bubble_delegate.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/root_view.h"

using base::TimeDelta;
using base::TimeTicks;
using std::max;
using std::min;

namespace {

// How long should the bubble be shown onscreen whenever the setting changes?
const int kBubbleShowTimeoutMs = 1000;

// How long should the level initially take to move up or down when it changes?
// (The rate adapts to handle keyboard autorepeat.)
const int64 kInitialAnimationDurationMs = 200;

// Horizontal position of the center of the bubble on the screen: 0 is left
// edge, 0.5 is center, 1 is right edge.
const double kBubbleXRatio = 0.5;

// Vertical gap from the bottom of the screen in pixels.
const int kBubbleBottomGap = 30;

// Duration between animation frames.
// Chosen to match ui::SlideAnimation's kDefaultFramerateHz.
const int kAnimationIntervalMs = 1000 / 50;

double LimitPercent(double percent) {
  return min(max(percent, 0.0), 100.0);
}

}  // namespace

namespace chromeos {

// SettingLevelBubbleDelegateView ----------------------------------------------
class SettingLevelBubbleDelegateView : public views::BubbleDelegateView {
 public:
  // BubbleDelegate overrides:
  virtual gfx::Rect GetAnchorRect() OVERRIDE;

  // Create the bubble delegate view.
  SettingLevelBubbleDelegateView();
  virtual ~SettingLevelBubbleDelegateView();

  SettingLevelBubbleView* view() { return view_; }

 protected:
  // BubbleDelegate overrides:
  virtual void Init() OVERRIDE;

 private:
  SettingLevelBubbleView* view_;

  DISALLOW_COPY_AND_ASSIGN(SettingLevelBubbleDelegateView);
};

gfx::Rect SettingLevelBubbleDelegateView::GetAnchorRect() {
  gfx::Size view_size = GetPreferredSize();
  // Calculate the position in screen coordinates that the bubble should
  // "point" at (since we use BubbleBorder::FLOAT, this position actually
  // specifies the center of the bubble).
  gfx::Rect monitor_area = gfx::Screen::GetMonitorAreaNearestWindow(NULL);
  return (gfx::Rect(
      monitor_area.x() + kBubbleXRatio * monitor_area.width(),
      monitor_area.bottom() - view_size.height() / 2 - kBubbleBottomGap, 0, 0));
}

SettingLevelBubbleDelegateView::SettingLevelBubbleDelegateView()
    : BubbleDelegateView(NULL, views::BubbleBorder::FLOAT),
      view_(NULL) {
  set_close_on_esc(false);
  set_use_focusless(true);
}

SettingLevelBubbleDelegateView::~SettingLevelBubbleDelegateView() {
  view_ = NULL;
}

void SettingLevelBubbleDelegateView::Init() {
  SetLayoutManager(new views::FillLayout());
  view_ = new SettingLevelBubbleView();
  AddChildView(view_);
}

// SettingLevelBubble ----------------------------------------------------------
void SettingLevelBubble::ShowBubble(double percent, bool enabled) {
  hide_timer_.Stop();

  // Set up target percent and icon.
  const double old_target_percent = target_percent_;
  UpdateTargetPercent(percent);
  SkBitmap* current_icon = increase_icon_;
  if (!enabled || target_percent_ == 0)
    current_icon = disabled_icon_;
  else if (old_target_percent >= 0 && target_percent_ < old_target_percent)
    current_icon = decrease_icon_;

  if (!view_) {
    view_ = CreateView();
    view_->Init(current_icon, percent, enabled);
  } else {
    // Reset fade sequence, if the bubble is already fading.
    SettingLevelBubbleDelegateView* delegate =
        static_cast<SettingLevelBubbleDelegateView*>
        (view_->GetWidget()->widget_delegate());
    delegate->ResetFade();
    view_->SetIcon(current_icon);
    view_->SetEnabled(enabled);
  }
  view_->GetWidget()->Show();
  // When the timer runs out, start the fade sequence.
  hide_timer_.Start(FROM_HERE,
                    base::TimeDelta::FromMilliseconds(kBubbleShowTimeoutMs),
                    this, &SettingLevelBubble::OnHideTimeout);
}

void SettingLevelBubble::HideBubble() {
  hide_timer_.Stop();
  if (view_) {
    view_->GetWidget()->Close();
    view_ = NULL;
  }
}

void SettingLevelBubble::UpdateWithoutShowingBubble(double percent,
                                                    bool enabled) {
  UpdateTargetPercent(percent);
  if (view_)
    view_->SetEnabled(enabled);
}

SettingLevelBubble::SettingLevelBubble(SkBitmap* increase_icon,
                                       SkBitmap* decrease_icon,
                                       SkBitmap* disabled_icon)
    :  current_percent_(-1.0),
       target_percent_(-1.0),
       increase_icon_(increase_icon),
       decrease_icon_(decrease_icon),
       disabled_icon_(disabled_icon),
       view_(NULL),
       is_animating_(false) {
}

SettingLevelBubble::~SettingLevelBubble() {
  view_ = NULL;
}

void SettingLevelBubble::OnWidgetClosing(views::Widget* widget) {
  if (view_ && view_->GetWidget() == widget) {
    view_->GetWidget()->RemoveObserver(this);
    view_ = NULL;
  }
  // Update states.
  current_percent_ = target_percent_;
  target_time_ = TimeTicks();
  last_animation_update_time_ = TimeTicks();
  last_target_update_time_ = TimeTicks();
  hide_timer_.Stop();
  StopAnimation();
}

SettingLevelBubbleView* SettingLevelBubble::CreateView() {
  SettingLevelBubbleDelegateView* delegate = new SettingLevelBubbleDelegateView;
  views::Widget* widget = browser::CreateViewsBubbleAboveLockScreen(delegate);
  widget->AddObserver(this);
  // Hold on to the content view.
  return delegate->view();
}

void SettingLevelBubble::OnHideTimeout() {
  // Start fading away.
  if (view_) {
    SettingLevelBubbleDelegateView* delegate =
        static_cast<SettingLevelBubbleDelegateView*>
        (view_->GetWidget()->widget_delegate());
    delegate->StartFade(false);
  }
}

void SettingLevelBubble::OnAnimationTimeout() {
  const TimeTicks now = TimeTicks::Now();
  const int64 remaining_ms = (target_time_ - now).InMilliseconds();

  if (remaining_ms <= 0) {
    current_percent_ = target_percent_;
    StopAnimation();
  } else {
    // Figure out what fraction of the total time until we want to reach the
    // target has elapsed since the last update.
    const double remaining_percent = target_percent_ - current_percent_;
    const int64 elapsed_ms =
        (now - last_animation_update_time_).InMilliseconds();
    current_percent_ +=
        remaining_percent *
        (static_cast<double>(elapsed_ms) / (elapsed_ms + remaining_ms));
  }
  last_animation_update_time_ = now;

  if (view_)
    view_->SetLevel(current_percent_);
}

void SettingLevelBubble::UpdateTargetPercent(double percent) {
  target_percent_ = LimitPercent(percent);
  const TimeTicks now = TimeTicks::Now();

  if (current_percent_ < 0.0) {
    // If we're setting the level for the first time, no need to animate.
    current_percent_ = target_percent_;
    if (view_)
      view_->SetLevel(current_percent_);
  } else {
    // Use the time since the last request as a hint for the duration of the
    // animation.  This makes us automatically adapt to the repeat rate if a key
    // is being held down to change a setting (which prevents us from lagging
    // behind when the key is finally released).
    int64 duration_ms = kInitialAnimationDurationMs;
    if (!last_target_update_time_.is_null())
      duration_ms = min(kInitialAnimationDurationMs,
                        (now - last_target_update_time_).InMilliseconds());
    target_time_ = now + TimeDelta::FromMilliseconds(duration_ms);

    if (!is_animating_) {
      animation_timer_.Start(FROM_HERE,
                             TimeDelta::FromMilliseconds(kAnimationIntervalMs),
                             this,
                             &SettingLevelBubble::OnAnimationTimeout);
      is_animating_ = true;
      last_animation_update_time_ = now;
    }
  }

  last_target_update_time_ = now;
}

void SettingLevelBubble::StopAnimation() {
  animation_timer_.Stop();
  is_animating_ = false;
}

}  // namespace chromeos
<commit_msg>chromeos: Do not show the old setting bubbles when volume/brightness changes if the uber-tray is active.<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/chromeos/ui/setting_level_bubble.h"

#include <algorithm>

#include "ash/shell.h"
#include "chrome/browser/chromeos/login/base_login_display_host.h"
#include "chrome/browser/chromeos/login/login_display_host.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/ui/setting_level_bubble_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/window.h"
#include "ui/gfx/screen.h"
#include "ui/views/bubble/bubble_delegate.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/root_view.h"

using base::TimeDelta;
using base::TimeTicks;
using std::max;
using std::min;

namespace {

// How long should the bubble be shown onscreen whenever the setting changes?
const int kBubbleShowTimeoutMs = 1000;

// How long should the level initially take to move up or down when it changes?
// (The rate adapts to handle keyboard autorepeat.)
const int64 kInitialAnimationDurationMs = 200;

// Horizontal position of the center of the bubble on the screen: 0 is left
// edge, 0.5 is center, 1 is right edge.
const double kBubbleXRatio = 0.5;

// Vertical gap from the bottom of the screen in pixels.
const int kBubbleBottomGap = 30;

// Duration between animation frames.
// Chosen to match ui::SlideAnimation's kDefaultFramerateHz.
const int kAnimationIntervalMs = 1000 / 50;

double LimitPercent(double percent) {
  return min(max(percent, 0.0), 100.0);
}

}  // namespace

namespace chromeos {

// SettingLevelBubbleDelegateView ----------------------------------------------
class SettingLevelBubbleDelegateView : public views::BubbleDelegateView {
 public:
  // BubbleDelegate overrides:
  virtual gfx::Rect GetAnchorRect() OVERRIDE;

  // Create the bubble delegate view.
  SettingLevelBubbleDelegateView();
  virtual ~SettingLevelBubbleDelegateView();

  SettingLevelBubbleView* view() { return view_; }

 protected:
  // BubbleDelegate overrides:
  virtual void Init() OVERRIDE;

 private:
  SettingLevelBubbleView* view_;

  DISALLOW_COPY_AND_ASSIGN(SettingLevelBubbleDelegateView);
};

gfx::Rect SettingLevelBubbleDelegateView::GetAnchorRect() {
  gfx::Size view_size = GetPreferredSize();
  // Calculate the position in screen coordinates that the bubble should
  // "point" at (since we use BubbleBorder::FLOAT, this position actually
  // specifies the center of the bubble).
  gfx::Rect monitor_area = gfx::Screen::GetMonitorAreaNearestWindow(NULL);
  return (gfx::Rect(
      monitor_area.x() + kBubbleXRatio * monitor_area.width(),
      monitor_area.bottom() - view_size.height() / 2 - kBubbleBottomGap, 0, 0));
}

SettingLevelBubbleDelegateView::SettingLevelBubbleDelegateView()
    : BubbleDelegateView(NULL, views::BubbleBorder::FLOAT),
      view_(NULL) {
  set_close_on_esc(false);
  set_use_focusless(true);
}

SettingLevelBubbleDelegateView::~SettingLevelBubbleDelegateView() {
  view_ = NULL;
}

void SettingLevelBubbleDelegateView::Init() {
  SetLayoutManager(new views::FillLayout());
  view_ = new SettingLevelBubbleView();
  AddChildView(view_);
}

// SettingLevelBubble ----------------------------------------------------------
void SettingLevelBubble::ShowBubble(double percent, bool enabled) {
  if (ash::Shell::GetInstance()->tray())
    return;
  hide_timer_.Stop();

  // Set up target percent and icon.
  const double old_target_percent = target_percent_;
  UpdateTargetPercent(percent);
  SkBitmap* current_icon = increase_icon_;
  if (!enabled || target_percent_ == 0)
    current_icon = disabled_icon_;
  else if (old_target_percent >= 0 && target_percent_ < old_target_percent)
    current_icon = decrease_icon_;

  if (!view_) {
    view_ = CreateView();
    view_->Init(current_icon, percent, enabled);
  } else {
    // Reset fade sequence, if the bubble is already fading.
    SettingLevelBubbleDelegateView* delegate =
        static_cast<SettingLevelBubbleDelegateView*>
        (view_->GetWidget()->widget_delegate());
    delegate->ResetFade();
    view_->SetIcon(current_icon);
    view_->SetEnabled(enabled);
  }
  view_->GetWidget()->Show();
  // When the timer runs out, start the fade sequence.
  hide_timer_.Start(FROM_HERE,
                    base::TimeDelta::FromMilliseconds(kBubbleShowTimeoutMs),
                    this, &SettingLevelBubble::OnHideTimeout);
}

void SettingLevelBubble::HideBubble() {
  if (ash::Shell::GetInstance()->tray())
    return;
  hide_timer_.Stop();
  if (view_) {
    view_->GetWidget()->Close();
    view_ = NULL;
  }
}

void SettingLevelBubble::UpdateWithoutShowingBubble(double percent,
                                                    bool enabled) {
  UpdateTargetPercent(percent);
  if (view_)
    view_->SetEnabled(enabled);
}

SettingLevelBubble::SettingLevelBubble(SkBitmap* increase_icon,
                                       SkBitmap* decrease_icon,
                                       SkBitmap* disabled_icon)
    :  current_percent_(-1.0),
       target_percent_(-1.0),
       increase_icon_(increase_icon),
       decrease_icon_(decrease_icon),
       disabled_icon_(disabled_icon),
       view_(NULL),
       is_animating_(false) {
}

SettingLevelBubble::~SettingLevelBubble() {
  view_ = NULL;
}

void SettingLevelBubble::OnWidgetClosing(views::Widget* widget) {
  if (view_ && view_->GetWidget() == widget) {
    view_->GetWidget()->RemoveObserver(this);
    view_ = NULL;
  }
  // Update states.
  current_percent_ = target_percent_;
  target_time_ = TimeTicks();
  last_animation_update_time_ = TimeTicks();
  last_target_update_time_ = TimeTicks();
  hide_timer_.Stop();
  StopAnimation();
}

SettingLevelBubbleView* SettingLevelBubble::CreateView() {
  SettingLevelBubbleDelegateView* delegate = new SettingLevelBubbleDelegateView;
  views::Widget* widget = browser::CreateViewsBubbleAboveLockScreen(delegate);
  widget->AddObserver(this);
  // Hold on to the content view.
  return delegate->view();
}

void SettingLevelBubble::OnHideTimeout() {
  // Start fading away.
  if (view_) {
    SettingLevelBubbleDelegateView* delegate =
        static_cast<SettingLevelBubbleDelegateView*>
        (view_->GetWidget()->widget_delegate());
    delegate->StartFade(false);
  }
}

void SettingLevelBubble::OnAnimationTimeout() {
  const TimeTicks now = TimeTicks::Now();
  const int64 remaining_ms = (target_time_ - now).InMilliseconds();

  if (remaining_ms <= 0) {
    current_percent_ = target_percent_;
    StopAnimation();
  } else {
    // Figure out what fraction of the total time until we want to reach the
    // target has elapsed since the last update.
    const double remaining_percent = target_percent_ - current_percent_;
    const int64 elapsed_ms =
        (now - last_animation_update_time_).InMilliseconds();
    current_percent_ +=
        remaining_percent *
        (static_cast<double>(elapsed_ms) / (elapsed_ms + remaining_ms));
  }
  last_animation_update_time_ = now;

  if (view_)
    view_->SetLevel(current_percent_);
}

void SettingLevelBubble::UpdateTargetPercent(double percent) {
  target_percent_ = LimitPercent(percent);
  const TimeTicks now = TimeTicks::Now();

  if (current_percent_ < 0.0) {
    // If we're setting the level for the first time, no need to animate.
    current_percent_ = target_percent_;
    if (view_)
      view_->SetLevel(current_percent_);
  } else {
    // Use the time since the last request as a hint for the duration of the
    // animation.  This makes us automatically adapt to the repeat rate if a key
    // is being held down to change a setting (which prevents us from lagging
    // behind when the key is finally released).
    int64 duration_ms = kInitialAnimationDurationMs;
    if (!last_target_update_time_.is_null())
      duration_ms = min(kInitialAnimationDurationMs,
                        (now - last_target_update_time_).InMilliseconds());
    target_time_ = now + TimeDelta::FromMilliseconds(duration_ms);

    if (!is_animating_) {
      animation_timer_.Start(FROM_HERE,
                             TimeDelta::FromMilliseconds(kAnimationIntervalMs),
                             this,
                             &SettingLevelBubble::OnAnimationTimeout);
      is_animating_ = true;
      last_animation_update_time_ = now;
    }
  }

  last_target_update_time_ = now;
}

void SettingLevelBubble::StopAnimation() {
  animation_timer_.Stop();
  is_animating_ = false;
}

}  // namespace chromeos
<|endoftext|>